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 |
---|---|---|---|---|---|---|---|---|---|---|---|
SelectFromPreviousWindowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SelectFromPreviousWindowCommand.java | /*
* SelectFromPreviousWindowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.Lane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Set;
/**
* select from previous window
* Daniel Huson, 5.2015
*/
public class SelectFromPreviousWindowCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Set<String> previousSelection = ProjectManager.getPreviouslySelectedNodeLabels();
viewer.getSelectedBlock().clear();
if (previousSelection.size() > 0) {
final Alignment alignment = viewer.getAlignment();
for (int row = 0; row < alignment.getNumberOfSequences(); row++) {
Lane lane = alignment.getLane(row);
if (previousSelection.contains(StringUtils.getFirstWord(lane.getName()))) {
int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(lane.getFirstNonGapPosition());
int firstCol = lane.getFirstNonGapPosition() - firstJump;
int lastCol = lane.getLastNonGapPosition() - firstJump - 1;
row = alignment.getRowCompressor().getRow(row);
viewer.getSelectedBlock().select(row, firstCol, row, lastCol, alignment.isTranslate());
System.err.println("Found: " + lane.getName());
executeImmediately("zoom axis=both what=selection;");
return;
}
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "select what=previous;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("select what=previous;");
}
public boolean isApplicable() {
return true;
}
public String getAltName() {
return "From Previous Alignment";
}
public String getName() {
return "From Previous Window";
}
public String getDescription() {
return "Select from previous window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 3,758 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetMinimumSizeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetMinimumSizeCommand.java | /*
* SetMinimumSizeCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class SetMinimumSizeCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set minReadsAlignment=");
int value = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase(";");
ProgramProperties.put(MeganProperties.MININUM_READS_IN_ALIGNMENT, value);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set minReadsAlignment={number};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
int value = ProgramProperties.get(MeganProperties.MININUM_READS_IN_ALIGNMENT, 10);
String result = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter minimum number of reads required for an alignment", "" + value);
if (result != null && NumberUtils.isInteger(result))
execute("set minReadsAlignment=" + result + ";");
}
private static final String NAME = "Set Minimum Number of Reads...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Globally set the minimum number of aligned reads required for a reference sequence to be listed in the alignment viewers";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,456 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetNucleotideColorSchemeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetNucleotideColorSchemeCommand.java | /*
* SetNucleotideColorSchemeCommand.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.alignment.commands;
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.alignment.AlignmentViewer;
import megan.alignment.gui.colors.ColorSchemeNucleotides;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 4.2012
*/
public class SetNucleotideColorSchemeCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set nucleotideColors=");
String value = np.getWordMatchesIgnoringCase(StringUtils.toString(ColorSchemeNucleotides.getNames(), " "));
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.setNucleotideColoringScheme(value);
// the following forces re-coloring:
viewer.setShowAminoAcids(viewer.isShowAminoAcids());
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set nucleotideColors=[" + StringUtils.toString(ColorSchemeNucleotides.getNames(), "|") + "];";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
String choice = ProgramProperties.get("NucleotideColorScheme", ColorSchemeNucleotides.NAMES.Default.toString());
String result = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose nucleotide color scheme", "Choose colors", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(),
ColorSchemeNucleotides.getNames(), choice);
if (result != null) {
result = result.trim();
if (result.length() > 0) {
ProgramProperties.put("NucleotideColorScheme", result);
execute("set nucleotideColors='" + result + "';");
}
}
}
private static final String NAME = "Set Nucleotide Colors...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the coloring scheme for nucleotides";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 4,013 | 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/alignment/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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2011
*/
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());
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getSelectedBlock().clear();
}
public String getSyntax() {
return "select what=none;";
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Select None";
}
public String getDescription() {
return "Select none of the cells of the alignment";
}
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() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,361 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetColorMismatchesVsConsensusCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetColorMismatchesVsConsensusCommand.java | /*
* SetColorMismatchesVsConsensusCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class SetColorMismatchesVsConsensusCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignmentViewerPanel().getAlignmentPanel().isColorMismatchesVsConsensus();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set colorMismatchesVsConsensus=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getAlignmentViewerPanel().getAlignmentPanel().setColorMismatchesVsConsensus(value);
ProgramProperties.put("ColorMismatches", value);
viewer.repaint();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set colorMismatchesVsConsensus={true|false};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("set colorMismatchesVsConsensus=" + (!isSelected()) + ";");
}
private static final String NAME = "Mismatches Vs Consensus";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Color letters that do not match the consensus sequence";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,511 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToFitCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ZoomToFitCommand.java | /*
* ZoomToFitCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.alignment.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ZoomToFitCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("expand axis=both what=fit;");
}
public boolean isApplicable() {
return true;
}
final static public String NAME = "Zoom To Fit";
public String getName() {
return NAME;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
public String getDescription() {
return "Zoom to fit";
}
public boolean isCritical() {
return true;
}
}
| 1,785 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutByStartCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutByStartCommand.java | /*
* LayoutByStartCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class LayoutByStartCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return ((AlignmentViewer) getViewer()).getAlignmentLayout() == AlignmentViewer.AlignmentLayout.ByStart;
}
/**
* 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) {
execute("set layout=" + AlignmentViewer.AlignmentLayout.ByStart + ";expand axis=both what=fit;");
}
public static final String NAME = "By Start";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Layout sequences by their start positions";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("AlignmentView16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,026 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyReadNamesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/CopyReadNamesCommand.java | /*
* CopyReadNamesCommand.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.alignment.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.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.Lane;
import megan.alignment.gui.SelectedBlock;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 4.2014
*/
public class CopyReadNamesCommand extends CommandBase implements ICommand {
/**
* 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) {
final AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Alignment alignment = viewer.getAlignment();
final SelectedBlock block = viewer.getSelectedBlock();
StringBuilder buf = new StringBuilder();
int count = 0;
for (int row = 0; row < alignment.getRowCompressor().getNumberRows(); row++) {
if (block.isSelectedRow(row)) {
for (Integer read : alignment.getRowCompressor().getCompressedRow2Reads(row)) {
Lane lane = alignment.getLane(read);
int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(block.getFirstCol());
if ((block.isSelectedCol(lane.getFirstNonGapPosition() - firstJump + 1) /* && block.isSelectedCol(lane.getLastNonGapPosition() - firstJump) */)) {
if (count++ > 0)
buf.append("\n");
buf.append(StringUtils.getFirstWord(lane.getName()));
}
}
}
}
if (count > 1)
buf.append("\n");
if (count > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
final public static String NAME = "Copy Read Names";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Copy the names of selected reads to the clip-board";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((AlignmentViewer) getViewer()).getSelectedBlock().isSelected();
}
}
| 4,339 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MoveDownCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/MoveDownCommand.java | /*
* MoveDownCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class MoveDownCommand extends CommandBase implements ICommand {
/**
* 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) {
execute("move dir=down;");
}
public static final String NAME = "Move Down";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Move selected sequences down";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Down16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignment().getNumberOfSequences() > 0 && viewer.getSelectedBlock().isSelected()
&& viewer.getSelectedBlock().getLastRow() < viewer.getAlignment().getNumberOfSequences() - 1;
}
}
| 3,162 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FindReadCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/FindReadCommand.java | /*
* FindReadCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.Lane;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* * selection command
* * Daniel Huson, 4.2015
*/
public class FindReadCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("find read=");
String regularExpression = np.getWordRespectCase();
np.matchIgnoreCase(";");
Pattern pattern = Pattern.compile(regularExpression);
AlignmentViewer viewer = (AlignmentViewer) getViewer();
for (int row = 0; row < viewer.getAlignment().getNumberOfSequences(); row++) {
Lane lane = viewer.getAlignment().getLane(row);
Matcher matcher = pattern.matcher(lane.getName());
if (matcher.find()) {
final Alignment alignment = viewer.getAlignment();
int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(lane.getFirstNonGapPosition());
int firstCol = lane.getFirstNonGapPosition() - firstJump;
int lastCol = lane.getLastNonGapPosition() - firstJump - 1;
row = alignment.getRowCompressor().getRow(row);
viewer.getSelectedBlock().select(row, firstCol, row, lastCol, alignment.isTranslate());
System.err.println("Found: " + lane.getName());
executeImmediately("zoom axis=both what=selection;");
return;
}
}
System.err.println("No match");
}
public String getSyntax() {
return "find read=<regular-expression>;";
}
public void actionPerformed(ActionEvent event) {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
String regularExpression = ProgramProperties.get(MeganProperties.FINDREAD, "");
regularExpression = JOptionPane.showInputDialog(viewer.getFrame(), "Enter regular expression for read names:", regularExpression);
if (regularExpression != null && regularExpression.trim().length() != 0) {
regularExpression = regularExpression.trim();
ProgramProperties.put(MeganProperties.FINDREAD, regularExpression);
execute("find read='" + regularExpression + "';");
}
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Find Read...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Find and select a read using a regular expression";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Find16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 4,238 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ContractGapsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ContractGapsCommand.java | /*
* ContractGapsCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class ContractGapsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.isContractGaps();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set contract-gaps=");
boolean collapse = np.getBoolean();
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getAlignmentViewerPanel().getSelectedBlock().clear();
viewer.setContractGaps(collapse);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set contract-gaps={true|false};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("set contract-gaps=" + !isSelected() + ";");
}
private static final String NAME = "Contract Gaps";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Contract all columns consisting only of gaps";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("ContractGaps16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,330 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExpandToHeightCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExpandToHeightCommand.java | /*
* ExpandToHeightCommand.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.alignment.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ExpandToHeightCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("expand axis=vertical what=reset;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand To Height";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignJustifyVertical16.gif");
}
public String getDescription() {
return "Expand to readable height";
}
public boolean isCritical() {
return true;
}
}
| 1,781 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeDiversityCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ComputeDiversityCommand.java | /*
* ComputeDiversityCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.ComputeAlignmentProperties;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class ComputeDiversityCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("compute diversityRatio kmer=");
int kmer = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("step=");
int step = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("mindepth=");
int mindepth = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
Pair<Double, Double> kn = ComputeAlignmentProperties.computeSequenceDiversityRatio(viewer.getAlignment(), step, kmer, mindepth, ((Director) getDir()).getDocument().getProgressListener());
((Director) getDir()).getDocument().getProgressListener().close();
NotificationsInSwing.showInformation(viewer.getFrame(), "Average diversity ratio:\n" + (float) (0 + kn.getFirst()) + " / " + (float) (0 + kn.getSecond()) + " = " + (float) (kn.getFirst() / kn.getSecond()));
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "compute diversityRatio kmer=<number> step=<number> mindepth=<number>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("compute diversityRatio kmer=25 step=25 mindepth=10;");
}
private static final String NAME = "Compute Diversity...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Compute diversity ratio";
}
/**
* 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignment().getLength() > 0;
}
}
| 3,955 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MoveUpCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/MoveUpCommand.java | /*
* MoveUpCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.AlignmentSorter;
import megan.alignment.gui.SelectedBlock;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class MoveUpCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("move dir=");
String dir = np.getWordMatchesIgnoringCase("up down");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
SelectedBlock selectedBlock = viewer.getSelectedBlock();
if (selectedBlock.isSelected()) {
if (dir.equals("up")) {
if ((viewer.isShowAsMapping() && viewer.getAlignment().getRowCompressor().moveUp(selectedBlock.getFirstRow(), selectedBlock.getLastRow()))
|| (!viewer.isShowAsMapping() && AlignmentSorter.moveUp(viewer.getAlignment(), selectedBlock.getFirstRow(), selectedBlock.getLastRow()))) {
selectedBlock.setFirstRow(selectedBlock.getFirstRow() - 1);
selectedBlock.setLastRow(selectedBlock.getLastRow() - 1);
selectedBlock.fireSelectionChanged();
}
} else if (dir.equals("down")) {
if ((viewer.isShowAsMapping() && viewer.getAlignment().getRowCompressor().moveDown(selectedBlock.getFirstRow(), selectedBlock.getLastRow()))
|| (!viewer.isShowAsMapping() && AlignmentSorter.moveDown(viewer.getAlignment(), selectedBlock.getFirstRow(), selectedBlock.getLastRow()))) {
selectedBlock.setFirstRow(selectedBlock.getFirstRow() + 1);
selectedBlock.setLastRow(selectedBlock.getLastRow() + 1);
selectedBlock.fireSelectionChanged();
}
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "move dir=<up|down>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("move dir=up;");
}
public static final String NAME = "Move Up";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Move selected sequences up";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Up16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_UP, 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
SelectedBlock selectedBlock = viewer.getSelectedBlock();
return viewer.getAlignment().getNumberOfSequences() > 0 && selectedBlock.isSelected() && selectedBlock.getFirstRow() > 0;
}
}
| 4,734 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetColorMatchesVsConsensusCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetColorMatchesVsConsensusCommand.java | /*
* SetColorMatchesVsConsensusCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class SetColorMatchesVsConsensusCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignmentViewerPanel().getAlignmentPanel().isColorMatchesVsConsensus();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set colorMatchesVsConsensus=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getAlignmentViewerPanel().getAlignmentPanel().setColorMatchesVsConsensus(value);
ProgramProperties.put("ColorMatchesVsConsensus", value);
viewer.repaint();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set colorMatchesVsConsensus={true|false};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("set colorMatchesVsConsensus=" + (!isSelected()) + ";");
}
private static final String NAME = "Matches Vs Consensus";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Color letters that match the consensus sequence";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,488 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutByNameCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutByNameCommand.java | /*
* LayoutByNameCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class LayoutByNameCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return ((AlignmentViewer) getViewer()).getAlignmentLayout() == AlignmentViewer.AlignmentLayout.ByName;
}
/**
* 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) {
execute("set layout=" + AlignmentViewer.AlignmentLayout.ByName + ";expand axis=both what=fit;");
}
public static final String NAME = "By Name";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Layout sequences alphabetically by their names";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("AlignmentView16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,026 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowMatchCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowMatchCommand.java | /*
* ShowMatchCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.Lane;
import megan.alignment.gui.SelectedBlock;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class ShowMatchCommand extends CommandBase implements ICommand {
/**
* 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) {
Director.showMessageWindow();
final AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Alignment alignment = viewer.getAlignment();
final SelectedBlock block = viewer.getSelectedBlock();
for (int row = 0; row < alignment.getRowCompressor().getNumberRows(); row++) {
if (block.isSelectedRow(row)) {
for (Integer read : alignment.getRowCompressor().getCompressedRow2Reads(row)) {
Lane lane = alignment.getLane(read);
int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(block.getFirstCol());
if ((block.isSelectedCol(lane.getFirstNonGapPosition() - firstJump + 1) /* && block.isSelectedCol(lane.getLastNonGapPosition() - firstJump) */)) {
System.out.println();
System.out.println(viewer.getSelectedReference());
System.out.println(lane.getText());
}
}
}
}
}
final public static String NAME = "Show Match...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show the match for a given read";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/History16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* 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 ((AlignmentViewer) getViewer()).getSelectedBlock().isSelected();
}
}
| 3,987 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportReferenceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExportReferenceCommand.java | /*
* ExportReferenceCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.SelectedBlock;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* save data command
* Daniel Huson, 11.2010
*/
public class ExportReferenceCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export reference file=<filename> [what={all|selection}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export reference file=");
String fileName = np.getAbsoluteFileName();
boolean saveAll = true;
if (np.peekMatchIgnoreCase("what")) {
np.matchIgnoreCase("what=");
saveAll = np.getWordMatchesIgnoringCase("selected all").equalsIgnoreCase("all");
}
np.matchIgnoreCase(";");
try {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
if (saveAll) {
System.err.println("Exporting complete reference to: " + fileName);
Alignment alignment = viewer.getAlignment();
String string = alignment.getReference().toStringIncludingLeadingAndTrailingGaps().replaceAll(" ", "");
Writer w = new FileWriter(fileName);
w.write(string);
w.write("\n");
w.close();
} else {
System.err.println("Exporting selected reference to: " + fileName);
Writer w = new FileWriter(fileName);
w.write(viewer.getAlignmentViewerPanel().getSelectedReference());
w.write("\n");
w.close();
}
} catch (IOException e) {
NotificationsInSwing.showError("Export Reference failed: " + e.getMessage());
}
}
public void actionPerformed(ActionEvent event) {
File lastOpenFile = ProgramProperties.getFile("SaveReference");
String fileName = ((AlignmentViewer) getViewer()).getAlignment().getName();
if (fileName == null)
fileName = "Untitled";
else
fileName = StringUtils.toCleanName(fileName);
if (lastOpenFile != null) {
fileName = new File(lastOpenFile.getParent(), fileName).getPath();
}
fileName = FileUtils.replaceFileSuffix(fileName, "-reference.fasta");
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new FastaFileFilter(), new FastaFileFilter(), event, "Save reference file", ".fasta");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".txt");
ProgramProperties.put("SaveReference", file);
SelectedBlock selectedBlock = ((AlignmentViewer) getViewer()).getSelectedBlock();
executeImmediately("export reference file='" + file.getPath() + "' what=" + (selectedBlock == null || !selectedBlock.isSelected() ? "all" : "Selected") + ";");
}
}
public boolean isApplicable() {
return ((AlignmentViewer) getViewer()).getAlignment().getLength() > 0;
}
public String getName() {
return "Reference...";
}
public String getAltName() {
return "Export Reference...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export reference sequence to a file";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 4,939 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutCommand.java | /*
* LayoutCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* layout command
* Daniel Huson, 8.2011
*/
public class LayoutCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set layout=");
String layout = np.getWordMatchesIgnoringCase(StringUtils.toString(AlignmentViewer.AlignmentLayout.values(), " "));
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getSelectedBlock().clear();
viewer.setAlignmentLayout(AlignmentViewer.AlignmentLayout.valueOfIgnoreCase(layout), ((Director) getDir()).getDocument().getProgressListener());
viewer.getAlignmentViewerPanel().zoom("both", "fit", null);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set layout={" + StringUtils.toString(AlignmentViewer.AlignmentLayout.values(), "|") + "};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
}
private static final String NAME = "Layout";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Determine how to layout the alignment";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,343 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetColorMismatchesVsReferenceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetColorMismatchesVsReferenceCommand.java | /*
* SetColorMismatchesVsReferenceCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class SetColorMismatchesVsReferenceCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignmentViewerPanel().getAlignmentPanel().isColorMismatchesVsReference();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set colorMismatchesVsReference=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getAlignmentViewerPanel().getAlignmentPanel().setColorMismatchesVsReference(value);
ProgramProperties.put("ColorMismatches", value);
viewer.repaint();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set colorMismatchesVsReference={true|false};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("set colorMismatchesVsReference=" + (!isSelected()) + ";");
}
private static final String NAME = "Mismatches Vs Reference";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Color letters that do not match the reference sequence";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,511 | 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/alignment/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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection 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());
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getSelectedBlock().selectAll();
}
public String getSyntax() {
return "select what=all;";
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Select All";
}
public String getDescription() {
return "Select all cells of the alignment";
}
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,309 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowUnalignedSequenceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowUnalignedSequenceCommand.java | /*
* ShowUnalignedSequenceCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class ShowUnalignedSequenceCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignmentViewerPanel().getAlignmentPanel().isShowUnalignedChars();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set show-unaligned=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
viewer.getAlignmentViewerPanel().getAlignmentPanel().setShowUnalignedChars(value);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set show-unaligned={true|false};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("set show-unaligned=" + !isSelected() + ";");
}
private static final String NAME = "Show Unaligned";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show the unaligned prefix and suffix of reads";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("ShowUnaligned16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignment().getLength() > 0;
}
}
| 3,480 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutByOriginalOrderCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutByOriginalOrderCommand.java | /*
* LayoutByOriginalOrderCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class LayoutByOriginalOrderCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return ((AlignmentViewer) getViewer()).getAlignmentLayout() == AlignmentViewer.AlignmentLayout.Unsorted;
}
/**
* 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) {
execute("set layout=" + AlignmentViewer.AlignmentLayout.Unsorted + ";expand axis=both what=fit;");
}
private static final String NAME = "Unsorted";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Layout sequences in unsorted order";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("AlignmentView16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,038 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExpandVerticalCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExpandVerticalCommand.java | /*
* ExpandVerticalCommand.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.alignment.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ExpandVerticalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("expand axis=vertical what=in;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand Vertical";
}
public String getAltName() {
return "Expand Vertical Alignment";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ExpandVertical16.gif");
}
public String getDescription() {
return "Expand view vertically";
}
public boolean isCritical() {
return true;
}
}
| 1,851 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportOverlapGraphCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExportOverlapGraphCommand.java | /*
* ExportOverlapGraphCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.Pair;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.assembly.alignment.AlignmentAssembler;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* save overlap graph
* Daniel Huson, 5.2015
*/
public class ExportOverlapGraphCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export overlapGraph file=<filename> [minOverap=<number>] [showGraph={false|true}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export overlapGraph file=");
String fileName = np.getAbsoluteFileName();
final int minOverlap;
if (np.peekMatchIgnoreCase("minOverlap")) {
np.matchIgnoreCase("minOverlap=");
minOverlap = np.getInt(1, 1000000);
} else
minOverlap = ProgramProperties.get("AssemblyMinOverlap", 20);
boolean showGraph = false;
if (np.peekMatchIgnoreCase("showGraph")) {
np.matchIgnoreCase("showGraph=");
showGraph = np.getBoolean();
}
np.matchIgnoreCase(";");
try {
System.err.println("Building overlap graph and exporting to file: " + fileName);
final AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Director dir = (Director) getDir();
final Writer w = new FileWriter(fileName);
final AlignmentAssembler alignmentAssembler = new AlignmentAssembler();
alignmentAssembler.computeOverlapGraph(minOverlap, viewer.getAlignment(), dir.getDocument().getProgressListener());
final Pair<Integer, Integer> nodesAndEdges = alignmentAssembler.writeOverlapGraph(w);
w.close();
NotificationsInSwing.showInformation(viewer.getFrame(), "Wrote " + nodesAndEdges.getFirst() + " nodes and " + nodesAndEdges.getSecond() + " edges");
if (showGraph)
alignmentAssembler.showOverlapGraph(dir, dir.getDocument().getProgressListener());
} catch (IOException e) {
NotificationsInSwing.showError("Export overlap file FAILED: " + e.getMessage());
}
}
public void actionPerformed(ActionEvent event) {
File lastOpenFile = ProgramProperties.getFile("OverlapGraphFile");
String fileName = ((AlignmentViewer) getViewer()).getAlignment().getName();
if (fileName == null)
fileName = "Untitled";
else
fileName = StringUtils.toCleanName(fileName);
if (lastOpenFile != null) {
fileName = new File(lastOpenFile.getParent(), fileName).getPath();
}
fileName = FileUtils.replaceFileSuffix(fileName, "-overlap.gml");
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new FastaFileFilter(), new FastaFileFilter(), event, "Save contigs file", ".fasta");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".gml");
ProgramProperties.put("OverlapGraphFile", file);
execute("export overlapGraph file='" + file.getPath() + "' minOverlap=" + ProgramProperties.get("AssemblyMinOverlap", 20) + " showGraph=false;");
}
}
public boolean isApplicable() {
return ((AlignmentViewer) getViewer()).getAlignment().getLength() > 0;
}
public String getName() {
return "Overlap Graph...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Build and save overlap graph";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 5,130 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutByContigsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutByContigsCommand.java | /*
* LayoutByContigsCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class LayoutByContigsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return ((AlignmentViewer) getViewer()).getAlignmentLayout() == AlignmentViewer.AlignmentLayout.ByContigs;
}
/**
* 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) {
execute("set layout=" + AlignmentViewer.AlignmentLayout.ByContigs + ";expand axis=both what=fit;");
}
public static final String NAME = "By Contigs";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Layout sequences by assembled contigs";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("AlignmentView16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,032 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowDiversityPlotCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowDiversityPlotCommand.java | /*
* ShowDiversityPlotCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.chart.DiversityPlotViewer;
import megan.core.Director;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class ShowDiversityPlotCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("chart wordCount kmer=");
int kmer = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("step=");
int step = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("mindepth=");
int mindepth = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase(";");
AlignmentViewer alignmentViewer = (AlignmentViewer) getViewer();
DiversityPlotViewer viewer = new DiversityPlotViewer((Director) getDir(), alignmentViewer, kmer, step, mindepth);
getDir().addViewer(viewer);
viewer.setVisible(true);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "chart wordCount kmer=<number> step=<number> mindepth=<number>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
AlignmentViewer alignmentViewer = (AlignmentViewer) getViewer();
int nSequences = alignmentViewer.getAlignment().getNumberOfSequences();
int step = 1;
if (nSequences > 10000 && nSequences <= 20000)
step = 2;
else if (nSequences > 20000 && nSequences <= 30000)
step = 4;
else if (nSequences > 30000)
step = 6;
execute("chart wordCount kmer=25 step=" + step + " mindepth=10;");
}
private static final String NAME = "Chart Diversity...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Chart diversity ratio";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("RareFaction16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignment().getLength() > 0;
}
}
| 4,188 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowNucleotidesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowNucleotidesCommand.java | /*
* ShowNucleotidesCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 8.2011
*/
public class ShowNucleotidesCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return !viewer.isShowAminoAcids();
}
/**
* 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) {
execute("set showAminoAcids=false;");
}
private static final String NAME = "Show Nucleotides";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show nucleotides in alignment";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("Nucleotides16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.isAllowNucleotides() && viewer.isShowAminoAcids();
}
}
| 3,076 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowInspectReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowInspectReadsCommand.java | /*
* ShowInspectReadsCommand.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.alignment.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.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.alignment.gui.Lane;
import megan.alignment.gui.SelectedBlock;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
/**
* command
* Daniel Huson, 4.2014
*/
public class ShowInspectReadsCommand extends CommandBase implements ICommand {
/**
* 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) {
final AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Alignment alignment = viewer.getAlignment();
final SelectedBlock block = viewer.getSelectedBlock();
final ArrayList<String> names = new ArrayList<>();
for (int row = 0; row < alignment.getRowCompressor().getNumberRows(); row++) {
if (block.isSelectedRow(row)) {
for (Integer read : alignment.getRowCompressor().getCompressedRow2Reads(row)) {
Lane lane = alignment.getLane(read);
int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(block.getFirstCol());
if ((block.isSelectedCol(lane.getFirstNonGapPosition() - firstJump + 1) /* && block.isSelectedCol(lane.getLastNonGapPosition() - firstJump) */)) {
names.add(StringUtils.getFirstWord(lane.getName()));
}
}
}
}
if (names.size() > 0) {
executeImmediately("show window=Inspector;");
final InspectorWindow inspectorWindow = (InspectorWindow) getDir().getViewerByClass(InspectorWindow.class);
if (inspectorWindow != null) {
final String command = "show read='\\Q" + StringUtils.toString(names, "\\E|\\Q") + "\\E';";
System.err.println(command);
getDir().execute(command, inspectorWindow.getCommandManager());
}
}
}
final public static String NAME = "Inspect Reads...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show all selected reads in the inspector window";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("Inspector16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((AlignmentViewer) getViewer()).getSelectedBlock().isSelected();
}
}
| 4,487 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeWordCountAnalysisCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ComputeWordCountAnalysisCommand.java | /*
* ComputeWordCountAnalysisCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.WordCountAnalysis;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.LinkedList;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* command
* Daniel Huson, 8.2011
*/
public class ComputeWordCountAnalysisCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("compute wordCount kmer=");
int kmer = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("step=");
int step = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase("mindepth=");
int mindepth = np.getInt(1, Integer.MAX_VALUE);
np.matchIgnoreCase(";");
AlignmentViewer viewer = (AlignmentViewer) getViewer();
LinkedList<Pair<Number, Number>> depthVsDifferences = new LinkedList<>();
SortedMap<Number, Number> rank2percentage = new TreeMap<>();
WordCountAnalysis.apply(viewer.getAlignment(), kmer, step, mindepth, ((Director) getDir()).getDocument().getProgressListener(), depthVsDifferences, rank2percentage);
System.out.println("Depth vs Differences (" + depthVsDifferences.size() + "):");
for (Pair<Number, Number> pair : depthVsDifferences) {
System.out.println(pair.getFirst() + " " + pair.getSecond());
}
System.out.println("done");
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "compute wordCount kmer=<number> step=<number> mindepth=<number>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("compute wordCount kmer=25 step=25 mindepth=10;");
}
private static final String NAME = "Compute Diversity...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Compute diversity ratio";
}
/**
* 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getAlignment().getLength() > 0;
}
}
| 4,095 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LayoutByMappingCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/LayoutByMappingCommand.java | /*
* LayoutByMappingCommand.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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* mapping command
* Daniel Huson, 11.2010
*/
public class LayoutByMappingCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return ((AlignmentViewer) getViewer()).getAlignmentLayout() == AlignmentViewer.AlignmentLayout.Mapping;
}
/**
* 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) {
execute("set layout=" + AlignmentViewer.AlignmentLayout.Mapping + ";expand axis=both what=fit;");
}
private static final String NAME = "As Mapping";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Layout sequences as mapped";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("MappingView16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,024 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyAlignmentCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/CopyAlignmentCommand.java | /*
* CopyAlignmentCommand.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.alignment.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.commands.clipboard.ClipboardBase;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CopyAlignmentCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
if (!viewer.getAlignmentViewerPanel().copyAlignment()) {
Action action = findAction(DefaultEditorKit.copyAction);
if (action != null)
action.actionPerformed(event);
}
}
public boolean isApplicable() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getSelectedBlock().isSelected();
}
public String getName() {
return "Copy Alignment";
}
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() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,414 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TranslateSelectedSequenceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/TranslateSelectedSequenceCommand.java | /*
* TranslateSelectedSequenceCommand.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.alignment.commands;
import jloda.seq.SequenceUtils;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.StringWriter;
/**
* translate selected sequence command
* Daniel Huson, 11.2011
*/
public class TranslateSelectedSequenceCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
AlignmentViewer viewer = (AlignmentViewer) getViewer();
String fastA = viewer.getAlignmentViewerPanel().getSelectedAlignment();
if (fastA != null) {
StringWriter w = new StringWriter();
BufferedReader r = new BufferedReader(new StringReader(fastA));
String aLine;
while ((aLine = r.readLine()) != null) {
aLine = aLine.trim();
if (aLine.startsWith(">"))
w.write(aLine + "\n");
else {
for (int i = 0; i < aLine.length() - 2; i += 3) {
w.write(SequenceUtils.getAminoAcid(aLine.charAt(i), aLine.charAt(i + 1), aLine.charAt(i + 2)));
}
w.write("\n");
}
}
System.out.println(w);
NotificationsInSwing.showInformation(viewer.getFrame(), w.toString());
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "translate sequence=selected;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute(getSyntax());
}
private static final String NAME = "Translate...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Translate sequenced DNA or cDNA sequence";
}
/**
* 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getSelectedBlock().isSelected() &&
(viewer.getAlignment().getSequenceType().equalsIgnoreCase(Alignment.DNA) || viewer.getAlignment().getSequenceType().equalsIgnoreCase(Alignment.cDNA))
&& !viewer.isShowAminoAcids();
}
}
| 4,291 | 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/alignment/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.alignment.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.alignment.gui.Alignment;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* apply command
* Daniel Huson, 1.2012
*/
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());
final AlignmentViewer viewer = (AlignmentViewer) getViewer();
final Alignment alignment = viewer.getAlignment();
final Document doc = ((Director) getDir()).getDocument();
viewer.getSelectedBlock().clear();
String reference = viewer.getSelectedReference();
if (reference != null) {
final int posDoubleColon = reference.lastIndexOf("::");
if (posDoubleColon > 0 && NumberUtils.isInteger(reference.substring(posDoubleColon + 2)))
reference = reference.substring(0, posDoubleColon);
if (reference.length() > 0) {
doc.getProgressListener().setTasks("Alignment viewer", "Calculating alignment");
viewer.getBlast2Alignment().makeAlignment(reference, alignment, viewer.isShowInsertions(), doc.getProgressListener());
viewer.setShowAminoAcids(alignment.getSequenceType().equals(Alignment.PROTEIN));
doc.getProgressListener().setTasks("Alignment viewer", "Drawing alignment");
doc.getProgressListener().setMaximum(100);
doc.getProgressListener().setProgress(-1);
viewer.setAlignment(alignment, true);
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "apply;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute(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 "Compute an alignment for all sequences that match the given reference sequence";
}
/**
* 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() {
AlignmentViewer viewer = (AlignmentViewer) getViewer();
return viewer.getSelectedReference() != null;
}
}
| 4,214 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TimeSeriesViewer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/TimeSeriesViewer.java | /*
* TimeSeriesViewer.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.timeseriesviewer;
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.RememberingComboBox;
import jloda.swing.util.ToolBar;
import jloda.swing.window.MenuBar;
import jloda.util.Table;
import megan.core.Director;
import megan.core.SampleAttributeTable;
import megan.core.SelectionSet;
import megan.main.MeganProperties;
import megan.timeseriesviewer.commands.CompareSamplesCommand;
import megan.timeseriesviewer.commands.CompareSubjectsCommand;
import megan.timeseriesviewer.commands.CompareTimePointsCommand;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.*;
/**
* times series viewer
* Daniel Huson, 6.2015
*/
public class TimeSeriesViewer extends JFrame implements IDirectableViewer {
private final Director dir;
private boolean uptoDate;
private boolean locked = false;
private final MenuBar menuBar;
private final CommandManager commandManager;
private final SubjectJTable subjectJTable;
private final DataJTable dataJTable;
private final RememberingComboBox subjectDefiningAttribute;
private final RememberingComboBox timepointsDefiningAttribute;
private final SelectionSet.SelectionListener selectionListener;
/**
* constructor
*
*/
public TimeSeriesViewer(JFrame parent, final Director dir) {
this.dir = dir;
commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.timeseriesviewer.commands"}, !ProgramProperties.isUseGUI());
setTitle();
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setIconImages(ProgramProperties.getProgramIconImages());
int[] geometry = ProgramProperties.get(getClassName() + "Geometry", new int[]{100, 100, 800, 600});
if (parent != null)
getFrame().setLocationRelativeTo(parent);
else
getFrame().setLocation(geometry[0] + (dir.getID() - 1) * 20, geometry[1] + (dir.getID() - 1) * 20);
getFrame().setSize(geometry[2], geometry[3]);
menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), commandManager);
setJMenuBar(menuBar);
MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu());
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
final ToolBar toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager);
mainPanel.add(toolBar, BorderLayout.NORTH);
subjectJTable = new SubjectJTable(this);
dataJTable = new DataJTable(this);
final JScrollPane seriesScrollPane = new JScrollPane(subjectJTable.getJTable());
seriesScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
seriesScrollPane.setAutoscrolls(true);
seriesScrollPane.setWheelScrollingEnabled(false);
seriesScrollPane.getViewport().setBackground(new Color(240, 240, 240));
final JScrollPane dataScrollPane = new JScrollPane(dataJTable.getJTable());
dataScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
dataScrollPane.setAutoscrolls(true);
dataScrollPane.setWheelScrollingEnabled(false);
dataScrollPane.getViewport().setBackground(new Color(240, 240, 240));
seriesScrollPane.getVerticalScrollBar().setModel(dataScrollPane.getVerticalScrollBar().getModel());
selectionListener = dataJTable::selectSamples;
dir.getDocument().getSampleSelection().addSampleSelectionListener(selectionListener);
final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, seriesScrollPane, dataScrollPane);
splitPane.setBorder(BorderFactory.createEmptyBorder(1, 3, 1, 3));
splitPane.setOneTouchExpandable(true);
splitPane.setEnabled(true);
splitPane.setResizeWeight(0);
splitPane.setDividerLocation(150);
splitPane.setLastDividerLocation(0);
mainPanel.add(splitPane, BorderLayout.CENTER);
dataJTable.getJTable().setFillsViewportHeight(true);
{
final JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.LINE_AXIS));
buttonsPanel.setBorder(new EmptyBorder(2, 5, 2, 5));
final JButton applyButton = new JButton(new AbstractAction("Apply") {
@Override
public void actionPerformed(ActionEvent e) {
setupTable(Objects.requireNonNull(subjectDefiningAttribute.getSelectedItem()).toString(), Objects.requireNonNull(timepointsDefiningAttribute.getSelectedItem()).toString());
}
});
buttonsPanel.add(new JLabel("Subjects:"));
subjectDefiningAttribute = new RememberingComboBox();
subjectDefiningAttribute.setMaximumSize(new Dimension(150, 20));
subjectDefiningAttribute.setEditable(false);
subjectDefiningAttribute.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Object a = subjectDefiningAttribute.getSelectedItem();
Object b = timepointsDefiningAttribute.getSelectedItem();
applyButton.setEnabled(a != null && b != null && ((String) a).length() > 0 && ((String) b).length() > 0
&& !a.equals(b));
}
});
buttonsPanel.add(subjectDefiningAttribute);
subjectDefiningAttribute.setToolTipText("Select metadata attribute that defines the different subjects");
buttonsPanel.add(new JLabel("Time points:"));
timepointsDefiningAttribute = new RememberingComboBox();
timepointsDefiningAttribute.setEditable(false);
timepointsDefiningAttribute.setMaximumSize(new Dimension(150, 20));
timepointsDefiningAttribute.addItemListener(e -> {
Object a = subjectDefiningAttribute.getSelectedItem();
Object b = timepointsDefiningAttribute.getSelectedItem();
applyButton.setEnabled(a != null && b != null && ((String) a).length() > 0 && ((String) b).length() > 0
&& !a.equals(b));
});
buttonsPanel.add(timepointsDefiningAttribute);
timepointsDefiningAttribute.setToolTipText("Select metadata attribute that defines the different time points");
buttonsPanel.add(applyButton);
mainPanel.add(buttonsPanel, BorderLayout.NORTH);
}
{
JPanel aLine = new JPanel();
aLine.setLayout(new BoxLayout(aLine, BoxLayout.LINE_AXIS));
aLine.add(Box.createHorizontalGlue());
aLine.add(commandManager.getButton(CompareSubjectsCommand.NAME));
aLine.add(commandManager.getButton(CompareTimePointsCommand.NAME));
aLine.add(commandManager.getButton(CompareSamplesCommand.NAME));
mainPanel.add(aLine, BorderLayout.SOUTH);
}
getContentPane().setLayout(new BorderLayout());
getContentPane().add(toolBar, BorderLayout.NORTH);
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().validate();
commandManager.updateEnableState();
getFrame().setVisible(true);
}
public boolean isUptoDate() {
return uptoDate;
}
public JFrame getFrame() {
return this;
}
public void updateView(String what) {
uptoDate = false;
setTitle();
commandManager.updateEnableState();
if (what.equals(IDirector.ALL)) {
if (getSubjectDefiningAttribute() == null || getTimePointsDefiningAttribute() == null) {
dataJTable.setDefault();
dataJTable.updateView();
subjectJTable.setDefault();
subjectJTable.updateView();
}
final Collection<String> attributes = dir.getDocument().getSampleAttributeTable().getAttributeOrder();
final Object selectedSeriesDefiningAttribute = subjectDefiningAttribute.getSelectedItem();
subjectDefiningAttribute.removeAllItems();
for (String attribute : attributes) {
if (!attribute.startsWith("@"))
subjectDefiningAttribute.addItem(attribute);
}
subjectDefiningAttribute.setSelectedItem(selectedSeriesDefiningAttribute);
final Object selectedTimepointDefiningAttribute = timepointsDefiningAttribute.getSelectedItem();
timepointsDefiningAttribute.removeAllItems();
for (String attribute : attributes) {
if (!attribute.startsWith("@"))
timepointsDefiningAttribute.addItem(attribute);
}
timepointsDefiningAttribute.setSelectedItem(selectedTimepointDefiningAttribute);
}
uptoDate = true;
}
public void lockUserInput() {
locked = true;
commandManager.setEnableCritical(false);
menuBar.setEnableRecentFileMenuItems(false);
}
public void unlockUserInput() {
commandManager.setEnableCritical(true);
menuBar.setEnableRecentFileMenuItems(true);
locked = false;
}
/**
* is viewer currently locked?
*
* @return true, if locked
*/
public boolean isLocked() {
return locked;
}
public void destroyView() {
ProgramProperties.put(getClassName() + "Geometry", new int[]
{getFrame().getLocation().x, getFrame().getLocation().y, getFrame().getSize().width, getFrame().getSize().height});
MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener());
dir.removeViewer(this);
dispose();
}
public void setUptoDate(boolean flag) {
uptoDate = flag;
}
/**
* set the title of the window
*/
private void setTitle() {
String newTitle = "Time Series Viewer - " + dir.getDocument().getTitle();
/*
if (dir.getDocument().isDirty())
newTitle += "*";
*/
if (dir.getID() == 1)
newTitle += " - " + ProgramProperties.getProgramVersion();
else
newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion();
if (!getFrame().getTitle().equals(newTitle)) {
getFrame().setTitle(newTitle);
ProjectManager.updateWindowMenus();
}
}
public CommandManager getCommandManager() {
return commandManager;
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "TimesSeriesViewer";
}
public Director getDirector() {
return dir;
}
public SubjectJTable getSubjectJTable() {
return subjectJTable;
}
public DataJTable getDataJTable() {
return dataJTable;
}
/**
* sets up the table based on the chosen series attribute and time point attribute
*
*/
private void setupTable(String seriesAttribute, String timePointAttribute) {
final Table<String, String, java.util.List<String>> seriesAndTimePoint2Samples = new Table<>();
final ArrayList<String> subjectsOrder = new ArrayList<>();
final ArrayList<String> timePointOrder = new ArrayList<>();
final Map<String, Integer> timePoint2MaxCount = new HashMap<>();
final SampleAttributeTable sampleAttributeTable = dir.getDocument().getSampleAttributeTable();
for (String sample : dir.getDocument().getSampleNames()) {
Object series = sampleAttributeTable.get(sample, seriesAttribute);
if (series == null)
series = "NA";
if (!subjectsOrder.contains(series.toString()))
subjectsOrder.add(series.toString());
Object timePoint = sampleAttributeTable.get(sample, timePointAttribute);
if (timePoint == null)
timePoint = "NA";
if (!timePointOrder.contains(timePoint.toString()))
timePointOrder.add(timePoint.toString());
java.util.List<String> list = seriesAndTimePoint2Samples.get(series.toString(), timePoint.toString());
if (list == null) {
list = new ArrayList<>();
seriesAndTimePoint2Samples.put(series.toString(), timePoint.toString(), list);
}
list.add(sample);
Integer count = timePoint2MaxCount.get(timePoint.toString());
if (count == null || list.size() > count)
timePoint2MaxCount.put(timePoint.toString(), list.size());
}
int rows = subjectsOrder.size();
int cols = 0;
for (Integer count : timePoint2MaxCount.values())
cols += count;
dataJTable.setRowsAndCols(rows, cols);
subjectJTable.setRows(rows);
BitSet headersAlreadySet = new BitSet();
int row = 0;
for (String series : subjectsOrder) {
int col = 0;
for (String timePoint : timePointOrder) {
int countPlaced = 0;
final Collection<String> samples = seriesAndTimePoint2Samples.get(series, timePoint);
if (samples != null) {
for (String sample : samples) {
if (!headersAlreadySet.get(col))
dataJTable.setColumnName(col, timePoint);
dataJTable.putCell(row, col++, sample);
countPlaced++;
}
}
while (countPlaced < timePoint2MaxCount.get(timePoint)) {
if (!headersAlreadySet.get(col))
dataJTable.setColumnName(col, timePoint);
dataJTable.putCell(row, col++, "NA");
countPlaced++;
}
}
row++;
}
dataJTable.updateView();
subjectJTable.updateView();
}
public String getSubjectDefiningAttribute() {
return subjectDefiningAttribute.getCurrentText(false);
}
public String getTimePointsDefiningAttribute() {
return timepointsDefiningAttribute.getCurrentText(false);
}
}
| 15,643 | 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/timeseriesviewer/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.timeseriesviewer;
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;Options;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Close;|;Quit;");
menuConfig.defineMenu("Open Recent", ";");
menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;");
menuConfig.defineMenu("Edit", "Cut;Copy;Paste;|;Select All;Select None;|;Find...;Find Again;|;");
menuConfig.defineMenu("Options", "Compare Samples...;Compare Subjects...;Compare Time Points...;");
menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" +
"Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Sample Viewers...;|;" +
ChartCommandHelper.getOpenChartMenuString() + "|;Chart Microbial Attributes...;|;");
menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;");
return menuConfig;
}
/**
* gets the tool bar configuration
*
* @return configuration
*/
public static String getToolBarConfiguration() {
return "Open...;|;Find...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Sample Viewers...;";
}
/**
* gets the bottom tool bar configuration
*
* @return configuration
*/
public static String getBottomToolBarConfiguration() {
return "Compare Subjects...;Compare Time Points...;Compare Samples...;";
}
/**
* gets the row header configuration
*
* @return configuration
*/
public static String getSubjectPopupConfiguration() {
return "";
}
/**
* gets the column header configuration
*
* @return configuration
*/
public static String getSubjectColumnHeaderPopupConfiguration() {
return "";
}
/**
* gets the row header configuration
*
* @return configuration
*/
public static String getDataPopupConfiguration() {
return "Select All;Select None;|;Compare Samples...;Compare Subjects...;Compare Time Points...;";
}
/**
* gets the column header configuration
*
* @return configuration
*/
public static String getDataColumnHeaderPopupConfiguration() {
return "";
}
}
| 3,838 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SubjectJTable.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/SubjectJTable.java | /*
* SubjectJTable.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.timeseriesviewer;
import jloda.swing.director.IDirector;
import jloda.swing.util.PopupMenu;
import megan.core.Director;
import megan.core.Document;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* the table allowing arrangement of series and time points
*/
public class SubjectJTable {
private final TimeSeriesViewer viewer;
private final Director dir;
private final Document doc;
private final JTable jTable;
private final MyTableModel tableModel;
private final MyCellRenderer renderer;
private final static Color selectionBackgroundColor = new Color(255, 240, 240);
/**
* Constructor
*
*/
public SubjectJTable(TimeSeriesViewer viewer) {
this.viewer = viewer;
this.dir = viewer.getDirector();
this.doc = dir.getDocument();
jTable = new JTable();
renderer = new MyCellRenderer();
tableModel = new MyTableModel();
setDefault();
jTable.setModel(tableModel);
jTable.createDefaultColumnsFromModel();
jTable.setColumnSelectionAllowed(false);
jTable.setRowSelectionAllowed(true);
jTable.setCellSelectionEnabled(true);
jTable.setGridColor(Color.LIGHT_GRAY);
jTable.setShowGrid(true);
jTable.addMouseListener(new MyMouseListener());
jTable.getTableHeader().setReorderingAllowed(false);
jTable.getTableHeader().addMouseListener(new MyMouseListener());
// setRowSorter(new TableRowSorter<DefaultTableModel>());
MySelectionListener mySelectionListener = new MySelectionListener();
jTable.getSelectionModel().addListSelectionListener(mySelectionListener);
jTable.getColumnModel().getSelectionModel().addListSelectionListener(mySelectionListener);
}
public void setDefault() {
int rows = (int) Math.sqrt(doc.getNumberOfSamples());
tableModel.resize(rows);
tableModel.setColumnName(0, "Subject");
for (int row = 0; row < rows; row++) {
tableModel.put(row, "" + row);
}
}
public void setRows(int rows) {
tableModel.resize(rows);
tableModel.setColumnName(0, "Subject");
for (int row = 0; row < rows; row++) {
tableModel.put(row, "" + row);
}
}
/**
* get the table
*
* @return table
*/
public JTable getJTable() {
return jTable;
}
public Font getFont() {
return jTable.getFont();
}
public void updateView() {
jTable.createDefaultColumnsFromModel();
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn col = jTable.getColumnModel().getColumn(i);
col.setCellRenderer(renderer);
}
jTable.revalidate();
}
/**
* table model
*/
static class MyTableModel extends AbstractTableModel {
private String columnName = "Subject";
private DataNode[][] data;
MyTableModel() {
}
void resize(int rows) {
data = new DataNode[rows][1];
}
void put(int row, String name) {
data[row][0] = new DataNode(name);
}
public int getColumnCount() {
return 1;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return (col == 0 ? columnName : "??");
}
void setColumnName(int col, String name) {
if (col == 0)
columnName = name;
}
public Object getValueAt(int row, int col) {
return (col == 0 ? data[row][col] : null);
}
public Class getColumnClass(int c) {
return (c == 0 ? getValueAt(0, c).getClass() : null);
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return col >= 2;
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (col == 0) {
data[row][col] = (DataNode) value;
fireTableCellUpdated(row, col);
}
}
}
static class DataNode {
private final String name;
private boolean selected;
DataNode(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String toString() {
return name;
}
String getName() {
return name;
}
}
static class MyCellRenderer implements TableCellRenderer {
private JPanel panel;
private JLabel label;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
if (panel == null) {
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel();
panel.setPreferredSize(new Dimension(label.getPreferredSize().width + 100, label.getPreferredSize().height));
panel.setMinimumSize(label.getPreferredSize());
panel.add(label, BorderLayout.CENTER);
}
label.setEnabled(isEnabled(row));
label.setForeground(label.isEnabled() ? Color.BLACK : Color.GRAY);
DataNode dataNode = (DataNode) value;
label.setText(dataNode.getName());
if (isSelected) {
//label.setBorder(BorderFactory.createLineBorder(Color.RED));
panel.setBackground(selectionBackgroundColor);
} else {
label.setBorder(null);
panel.setBackground(label.getBackground());
}
//label.setBackground(isEnabled(row) ? selectionBackgroundColor : Color.LIGHT_GRAY);
return panel;
}
boolean isEnabled(int modelRow) {
//String sampleName = tableModel.getValueAt(modelRow, 0).toString();
return true;
}
}
class MySelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
// The mouse button has not yet been released
} else {
//dir.updateView(IDirector.ENABLE_STATE);
//jTable.repaint();
viewer.getDataJTable().clearSelection();
for (int row = 0; row < jTable.getRowCount(); row++) {
viewer.getDataJTable().selectRow(row, jTable.isRowSelected(row));
}
viewer.getDataJTable().getJTable().repaint();
viewer.updateView(IDirector.ENABLE_STATE);
}
}
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
}
}
}
private void showPopupMenu(final MouseEvent e) {
// show the header popup menu:
if (e.getSource() instanceof JTableHeader) {
(new PopupMenu(this, GUIConfiguration.getSubjectColumnHeaderPopupConfiguration(), dir.getCommandManager())).show(e.getComponent(), e.getX(), e.getY());
} else if (e.getSource() instanceof JTable && e.getSource() == jTable) {
(new PopupMenu(this, GUIConfiguration.getSubjectPopupConfiguration(), dir.getCommandManager())).show(e.getComponent(), e.getX(), e.getY());
}
}
}
| 9,247 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DataJTable.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/DataJTable.java | /*
* DataJTable.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.timeseriesviewer;
import jloda.swing.director.IDirector;
import jloda.swing.util.PopupMenu;
import megan.chart.ChartColorManager;
import megan.core.Director;
import megan.core.Document;
import megan.core.SampleAttributeTable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
/**
* the table allowing arrangement of series and time points
*/
public class DataJTable {
private final TimeSeriesViewer viewer;
private final Director dir;
private final Document doc;
private final ChartColorManager chartColorManager;
private final JTable jTable;
private final MyCellRenderer renderer;
private final MyTableModel tableModel;
private final Set<String> disabledSamples = new HashSet<>();
private final Set<String> selectedSamples = new HashSet<>();
private final static Color selectionBackgroundColor = new Color(255, 240, 240);
private final static Color backgroundColor = new Color(230, 230, 230);
private int columnPressed = -1;
/**
* Constructor
*
*/
public DataJTable(TimeSeriesViewer viewer) {
this.viewer = viewer;
this.dir = viewer.getDirector();
this.doc = dir.getDocument();
this.chartColorManager = doc.getChartColorManager();
jTable = new JTable();
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
renderer = new MyCellRenderer();
jTable.setColumnModel(new DefaultTableColumnModel() {
public void addColumn(TableColumn tc) {
tc.setMinWidth(150);
super.addColumn(tc);
}
});
jTable.addMouseListener(new MyMouseListener());
jTable.getTableHeader().addMouseListener(new MyMouseListener());
tableModel = new MyTableModel();
setDefault();
jTable.setModel(tableModel);
final MySelectionListener mySelectionListener = new MySelectionListener();
jTable.getSelectionModel().addListSelectionListener(mySelectionListener);
jTable.getColumnModel().getSelectionModel().addListSelectionListener(mySelectionListener);
}
public void setDefault() {
int numberOfSamples = doc.getNumberOfSamples();
int rows = (int) Math.sqrt(numberOfSamples);
int cols = 0;
while (rows * cols < numberOfSamples)
cols++;
setRowsAndCols(rows, cols);
String[] sampleNames = doc.getSampleNamesAsArray();
int count = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (row == 0)
setColumnName(col, "Time " + col);
if (count < numberOfSamples)
putCell(row, col, sampleNames[count++]);
else
putCell(row, col, null);
}
}
updateView();
}
public void setRowsAndCols(int rows, int cols) {
tableModel.resize(rows, cols);
}
public void putCell(int row, int col, String sample) {
tableModel.put(row, col, sample);
}
public void setColumnName(int col, String name) {
tableModel.setColumnName(col, name);
}
public void updateView() {
jTable.createDefaultColumnsFromModel();
for (int i = 0; i < jTable.getColumnCount(); i++) {
TableColumn col = jTable.getColumnModel().getColumn(i);
col.setCellRenderer(renderer);
}
jTable.revalidate();
}
/**
* get the table
*
* @return table
*/
public JTable getJTable() {
return jTable;
}
private Font getFont() {
return jTable.getFont();
}
public void selectRow(int row, boolean select) {
if (row >= 0) {
for (int col = 0; col < tableModel.getColumnCount(); col++) {
final DataNode dataNode = (DataNode) tableModel.getValueAt(row, col);
if (dataNode != null) {
dataNode.setSelected(select);
}
}
}
}
private void selectColumn(int col, boolean select) {
if (col >= 0) {
for (int row = 0; row < tableModel.getRowCount(); row++) {
final DataNode dataNode = (DataNode) tableModel.getValueAt(row, col);
if (dataNode != null) {
dataNode.setSelected(select);
}
}
}
}
public void select(String name, boolean select) {
for (int row = 0; row < getJTable().getRowCount(); row++) {
for (int col = 0; col < getJTable().getColumnCount(); col++) {
final DataNode dataNode = (DataNode) tableModel.getValueAt(row, col);
if (dataNode != null && dataNode.getName() != null && dataNode.getName().endsWith(name)) {
dataNode.setSelected(select);
}
}
}
}
public void clearSelection() {
jTable.clearSelection();
for (int row = 0; row < getJTable().getRowCount(); row++) {
for (int col = 0; col < getJTable().getColumnCount(); col++) {
((DataNode) tableModel.getValueAt(row, col)).setSelected(false);
}
}
}
public void selectAll() {
jTable.selectAll();
for (int row = 0; row < getJTable().getRowCount(); row++) {
for (int col = 0; col < getJTable().getColumnCount(); col++) {
((DataNode) tableModel.getValueAt(row, col)).setSelected(true);
}
}
}
public int getColumnPressed() {
return columnPressed;
}
public void setColumnPressed(int columnPressed) {
this.columnPressed = columnPressed;
}
private boolean isEnabled(int modelRow) {
Object sampleName = jTable.getModel().getValueAt(modelRow, 0);
return sampleName != null && !disabledSamples.contains(sampleName.toString());
}
public String getSampleName(int modelRow) {
return jTable.getModel().getValueAt(modelRow, 0).toString();
}
public void setDisabledSamples(Collection<String> disabledSamples) {
this.disabledSamples.clear();
this.disabledSamples.addAll(disabledSamples);
}
public Set<String> getDisabledSamples() {
return disabledSamples;
}
public void selectSamples(Collection<String> names, boolean select) {
for (int row = 0; row < tableModel.getRowCount(); row++) {
for (int col = 0; col < tableModel.getColumnCount(); col++) {
final DataNode dataNode = (DataNode) tableModel.getValueAt(row, col);
if (dataNode != null && dataNode.getName() != null && names.contains(dataNode.getName())) {
dataNode.setSelected(select);
}
}
}
}
public Collection<String> getSelectedSamples() {
ArrayList<String> selectedSamples = new ArrayList<>(tableModel.getRowCount() * tableModel.getColumnCount());
int[] columnsInView = getColumnsInView();
for (int row = 0; row < tableModel.getRowCount(); row++) {
for (int col : columnsInView) {
final DataNode dataNode = (DataNode) tableModel.getValueAt(row, col);
if (dataNode != null && dataNode.isSelected()) {
selectedSamples.add(dataNode.getName());
}
}
}
return selectedSamples;
}
private int[] getColumnsInView() {
int[] result = new int[jTable.getColumnCount()];
// Use an enumeration
Enumeration<TableColumn> e = jTable.getColumnModel().getColumns();
for (int i = 0; e.hasMoreElements(); i++) {
result[i] = e.nextElement().getModelIndex();
}
return result;
}
/**
* table model
*/
static class MyTableModel extends AbstractTableModel {
private DataNode[][] data;
private String[] columnNames;
MyTableModel() {
}
void resize(int rows, int cols) {
data = new DataNode[rows][cols];
columnNames = new String[cols];
}
void put(int row, int col, String name) {
data[row][col] = new DataNode(name);
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
void setColumnName(int col, String name) {
columnNames[col] = name;
}
public Object getValueAt(int row, int col) {
if (row < data.length && data[row] != null && col < data[row].length)
return data[row][col];
else
return null;
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return col >= 2;
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
data[row][col] = (DataNode) value;
fireTableCellUpdated(row, col);
}
}
static class DataNode {
private final String name;
private boolean selected;
DataNode(String name) {
this.name = name;
}
boolean isSelected() {
return selected;
}
void setSelected(boolean selected) {
this.selected = selected;
}
public String toString() {
return name;
}
String getName() {
return name;
}
}
class MyCellRenderer implements TableCellRenderer {
private JLabel label;
private Swatch swatch;
private JPanel both;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
if (both == null) {
both = new JPanel();
both.setLayout(new BoxLayout(both, BoxLayout.X_AXIS));
swatch = new Swatch();
swatch.setMaximumSize(new Dimension(getFont().getSize(), getFont().getSize()));
swatch.setBorder(BorderFactory.createLineBorder(Color.WHITE));
label = new JLabel();
both.add(swatch);
both.add(Box.createHorizontalStrut(4));
both.add(label);
label.setPreferredSize(new Dimension(label.getPreferredSize().width + 100, label.getPreferredSize().height));
label.setMinimumSize(label.getPreferredSize());
}
both.setEnabled(isEnabled(row));
label.setForeground(both.isEnabled() ? Color.BLACK : Color.GRAY);
if (value != null) {
final DataNode dataNode = (DataNode) value;
label.setText(doc.getSampleLabelGetter().getLabel(dataNode.getName()));
if (dataNode.isSelected())
both.setBorder(BorderFactory.createLineBorder(Color.RED));
else
both.setBorder(null);
Color color = chartColorManager.getSampleColor(dataNode.getName());
if (dataNode.getName() != null && dataNode.isSelected()) {
both.setBackground(selectionBackgroundColor);
} else
both.setBackground(backgroundColor);
swatch.setBackground(isEnabled(row) ? color : Color.LIGHT_GRAY);
if (dataNode.getName() != null)
swatch.setShape((String) dir.getDocument().getSampleAttributeTable().get(dataNode.getName(), SampleAttributeTable.HiddenAttribute.Shape.toString()));
else
swatch.setShape("None");
final String description = (String) dir.getDocument().getSampleAttributeTable().get(dataNode.getName(), SampleAttributeTable.DescriptionAttribute);
if (description != null && description.length() > 0)
both.setToolTipText(description);
else
both.setToolTipText(dataNode.getName());
}
return both;
}
}
private static class Swatch extends JPanel {
private String shape;
void setShape(String shape) {
this.shape = shape;
}
public void paint(Graphics gc0) {
Graphics2D gc = (Graphics2D) gc0;
if (shape != null && shape.equalsIgnoreCase("Square")) {
gc.setColor(getBackground());
gc.fillRect(1, 1, getWidth() - 2, getHeight() - 2);
gc.setColor(Color.BLACK);
gc.drawRect(1, 1, getWidth() - 2, getHeight() - 2);
} else if (shape != null && shape.equalsIgnoreCase("Triangle")) {
Shape polygon = new Polygon(new int[]{1, getWidth() - 1, getWidth() / 2}, new int[]{getHeight() - 1, getHeight() - 1, 1}, 3);
gc.setColor(getBackground());
gc.fill(polygon);
gc.setColor(Color.BLACK);
gc.draw(polygon);
} else if (shape != null && shape.equalsIgnoreCase("Diamond")) {
Shape polygon = new Polygon(new int[]{1, (int) Math.round(getWidth() / 2.0), getWidth() - 1, (int) Math.round(getWidth() / 2.0)},
new int[]{(int) Math.round(getHeight() / 2.0), getHeight() - 1, (int) Math.round(getHeight() / 2.0), 1}, 4);
gc.setColor(getBackground());
gc.fill(polygon);
gc.setColor(Color.BLACK);
gc.draw(polygon);
} else if (shape == null || !shape.equalsIgnoreCase("None")) { // circle
gc.setColor(getBackground());
gc.fillOval(1, 1, getWidth() - 2, getHeight() - 2);
gc.setColor(Color.BLACK);
gc.drawOval(1, 1, getWidth() - 2, getHeight() - 2);
}
}
}
class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
jTable.repaint();
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
} else {
if (e.getSource() instanceof JTableHeader) {
columnPressed = jTable.getTableHeader().columnAtPoint(e.getPoint());
if (columnPressed >= 0) {
if (!e.isShiftDown() && !e.isMetaDown())
clearSelection();
selectColumn(columnPressed, true);
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
}
jTable.repaint();
}
}
private void showPopupMenu(final MouseEvent e) {
// show the header popup menu:
if (e.getSource() instanceof JTableHeader) {
columnPressed = jTable.getTableHeader().columnAtPoint(e.getPoint());
(new PopupMenu(this, GUIConfiguration.getDataColumnHeaderPopupConfiguration(), dir.getCommandManager())).show(e.getComponent(), e.getX(), e.getY());
} else if (e.getSource() instanceof JTable && e.getSource() == jTable) {
JPopupMenu popupMenu = (new PopupMenu(this, GUIConfiguration.getDataPopupConfiguration(), dir.getCommandManager()));
popupMenu.addSeparator();
popupMenu.add(new AbstractAction("Select Row") {
public void actionPerformed(ActionEvent ae) {
clearSelection();
selectRow(jTable.rowAtPoint(e.getPoint()), true);
}
});
popupMenu.add(new AbstractAction("Select Column") {
public void actionPerformed(ActionEvent ae) {
clearSelection();
selectColumn(jTable.columnAtPoint(e.getPoint()), true);
}
});
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
class MySelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
// The mouse button has not yet been released
} else {
Set<String> toSelect = new HashSet<>();
for (int row = 0; row < jTable.getRowCount(); row++) {
for (int col = 0; col < jTable.getColumnCount(); col++) {
Object sample = jTable.getValueAt(row, col);
if (sample != null) {
boolean selectedInDocument = doc.getSampleSelection().isSelected(sample.toString());
boolean selectedOnGrid = jTable.isRowSelected(row) && jTable.isColumnSelected(col);
if (selectedOnGrid || (selectedInDocument && (jTable.isRowSelected(row) || jTable.isColumnSelected(col))))
toSelect.add(sample.toString());
}
}
}
doc.getSampleSelection().clear();
doc.getSampleSelection().setSelected(toSelect, true);
viewer.updateView(IDirector.ENABLE_STATE);
}
}
}
}
| 18,883 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CompareTimePointsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/commands/CompareTimePointsCommand.java | /*
* CompareTimePointsCommand.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.timeseriesviewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Document;
import megan.timeseriesviewer.TimeSeriesViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
/**
* * compare time points command
* * Daniel Huson, 6.2015
*/
public class CompareTimePointsCommand 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 TimeSeriesViewer viewer = (TimeSeriesViewer) getViewer();
final Document doc = viewer.getDirector().getDocument();
final Map<String, ArrayList<String>> timePoint2samples = new TreeMap<>();
final ArrayList<String> timePointOrder = new ArrayList<>();
final String timePointAttribute = viewer.getTimePointsDefiningAttribute();
for (String sample : viewer.getDataJTable().getSelectedSamples()) {
final Object timePoint = doc.getSampleAttributeTable().get(sample, timePointAttribute);
if (timePoint != null) {
ArrayList<String> list = timePoint2samples.get(timePoint.toString());
if (list == null) {
list = new ArrayList<>();
timePoint2samples.put(timePoint.toString(), list);
timePointOrder.add(timePoint.toString());
}
list.add(sample);
}
}
if (timePoint2samples.size() > 0) {
final StringBuilder buf = new StringBuilder();
buf.append("compare title='").append(FileUtils.replaceFileSuffix(doc.getTitle(), "")).append("-").append(timePointAttribute).append("'");
for (String timePoint : timePointOrder) {
buf.append(" name='").append(timePointAttribute).append(":").append(timePoint).append("' samples=");
for (String sample : timePoint2samples.get(timePoint)) {
buf.append(" '").append(sample).append("'");
}
}
buf.append(";");
execute(buf.toString());
}
}
public boolean isApplicable() {
return ((TimeSeriesViewer) getViewer()).getDataJTable().getSelectedSamples().size() > 0;
}
public final static String NAME = "Compare Time Points...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Compare all selected time points in a new document";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,806 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CompareSamplesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/commands/CompareSamplesCommand.java | /*
* CompareSamplesCommand.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.timeseriesviewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.timeseriesviewer.TimeSeriesViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
/**
* * open samples command
* * Daniel Huson, 6.2015
*/
public class CompareSamplesCommand 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) {
TimeSeriesViewer viewer = (TimeSeriesViewer) getViewer();
Collection<String> samples = viewer.getDataJTable().getSelectedSamples();
if (samples.size() > 0) {
execute("extract samples='" + StringUtils.toString(samples, "' '") + "';");
}
}
public boolean isApplicable() {
return ((TimeSeriesViewer) getViewer()).getDataJTable().getSelectedSamples().size() > 0;
}
public final static String NAME = "Compare Samples...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Compare all selected samples in a new document";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_M, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,499 | 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/timeseriesviewer/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.timeseriesviewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
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 SelectNoneCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set select=none;");
}
public boolean isApplicable() {
return true;
}
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,037 | 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/timeseriesviewer/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.timeseriesviewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.timeseriesviewer.DataJTable;
import megan.timeseriesviewer.TimeSeriesViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectAllCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set select={all|none|sample|name=<string>|row=<number>|col=<number>};";
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set select=");
TimeSeriesViewer viewer = (TimeSeriesViewer) getViewer();
DataJTable dataJTable = viewer.getDataJTable();
if (np.peekMatchIgnoreCase("all")) {
np.matchIgnoreCase("all");
dataJTable.selectAll();
} else if (np.peekMatchIgnoreCase("none")) {
np.matchIgnoreCase("none");
dataJTable.clearSelection();
} else if (np.peekMatchIgnoreCase("name")) {
np.matchIgnoreCase("name=");
String name = np.getWordRespectCase();
dataJTable.select(name, true);
}
np.matchIgnoreCase(";");
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set select=all;");
}
public boolean isApplicable() {
return true;
}
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());
}
}
| 2,812 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CompareSubjectsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/timeseriesviewer/commands/CompareSubjectsCommand.java | /*
* CompareSubjectsCommand.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.timeseriesviewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Document;
import megan.timeseriesviewer.TimeSeriesViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
/**
* * compare subjects command
* * Daniel Huson, 7.2015
*/
public class CompareSubjectsCommand 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 TimeSeriesViewer viewer = (TimeSeriesViewer) getViewer();
final Document doc = viewer.getDirector().getDocument();
final Map<String, ArrayList<String>> subject2samples = new TreeMap<>();
final ArrayList<String> subjectOrder = new ArrayList<>();
final String subjectDefiningAttribute = viewer.getSubjectDefiningAttribute();
for (String sample : viewer.getDataJTable().getSelectedSamples()) {
final Object subject = doc.getSampleAttributeTable().get(sample, subjectDefiningAttribute);
if (subject != null) {
ArrayList<String> list = subject2samples.get(subject.toString());
if (list == null) {
list = new ArrayList<>();
subject2samples.put(subject.toString(), list);
subjectOrder.add(subject.toString());
}
list.add(sample);
}
}
if (subject2samples.size() > 0) {
final StringBuilder buf = new StringBuilder();
buf.append("compare title='").append(FileUtils.replaceFileSuffix(doc.getTitle(), "")).append("-").append(subjectDefiningAttribute).append("'");
for (String subject : subjectOrder) {
buf.append(" name='").append(subjectDefiningAttribute).append(":").append(subject).append("' samples=");
for (String sample : subject2samples.get(subject)) {
buf.append(" '").append(sample).append("'");
}
}
buf.append(";");
execute(buf.toString());
}
}
public boolean isApplicable() {
return ((TimeSeriesViewer) getViewer()).getDataJTable().getSelectedSamples().size() > 0;
}
public final static String NAME = "Compare Subjects...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Compare all selected subjects in a new document";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,782 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LongFilePutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/LongFilePutter.java | /*
* LongFilePutter.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Open a file for reading and writing
* <p/>
* Daniel Huson, 4.2015
*/
public class LongFilePutter extends BaseFileGetterPutter implements ILongPutter, ILongGetter {
/**
* constructor to read and write values from an existing file
*
*/
public LongFilePutter(File file) throws IOException {
super(file, 0, Mode.READ_WRITE);
}
/**
* constructs a long file putter using the given file and limit
*
* @param limit length of array
*/
public LongFilePutter(File file, long limit) throws IOException {
this(file, limit, false);
}
/**
* constructs a long file putter using the given file and limit
*
* @param limit length of array
*/
public LongFilePutter(File file, long limit, boolean inMemory) throws IOException {
super(file, 8 * limit, (inMemory ? Mode.CREATE_READ_WRITE_IN_MEMORY : Mode.CREATE_READ_WRITE));
}
/**
* gets value for given index
*
* @return value or 0
*/
public long get(long index) {
if (index < limit()) {
index <<= 3; // convert to file position
final ByteBuffer buf = buffers[getWhichBuffer(index)];
int indexBuffer = getIndexInBuffer(index);
return (((long) buf.get(indexBuffer++)) << 56) + ((long) (buf.get(indexBuffer++) & 0xFF) << 48) + ((long) (buf.get(indexBuffer++) & 0xFF) << 40) +
((long) (buf.get(indexBuffer++) & 0xFF) << 32) + ((long) (buf.get(indexBuffer++) & 0xFF) << 24) + ((long) (buf.get(indexBuffer++) & 0xFF) << 16) +
((long) (buf.get(indexBuffer++) & 0xFF) << 8) + (((long) buf.get(indexBuffer) & 0xFF));
} else
return 0;
}
/**
* puts value for given index
*
*/
@Override
public ILongPutter put(long index, long value) {
if (index < limit()) {
index <<= 3; // convert to file position
final ByteBuffer buf = buffers[getWhichBuffer(index)];
int indexBuffer = getIndexInBuffer(index);
buf.put(indexBuffer++, (byte) (value >> 56));
buf.put(indexBuffer++, (byte) (value >> 48));
buf.put(indexBuffer++, (byte) (value >> 40));
buf.put(indexBuffer++, (byte) (value >> 32));
buf.put(indexBuffer++, (byte) (value >> 24));
buf.put(indexBuffer++, (byte) (value >> 16));
buf.put(indexBuffer++, (byte) (value >> 8));
buf.put(indexBuffer, (byte) (value));
} else
throw new ArrayIndexOutOfBoundsException("" + index);
return this;
}
/**
* length of array (file length / 8)
*
* @return array length
*/
@Override
public long limit() {
return fileLength >>> 3;
}
/**
* set a new limit for a file
*
*/
public static void setLimit(File file, long newLimit) throws IOException {
resize(file, 8 * (newLimit + 1));
}
}
| 3,878 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFileGetterInMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntFileGetterInMemory.java | /*
* IntFileGetterInMemory.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.io;
import jloda.util.progress.ProgressPercentage;
import java.io.*;
/**
* int file getter in memory
* Daniel Huson, 5.2015
*/
public class IntFileGetterInMemory implements IIntGetter {
private final int BITS = 30;
private final long BIT_MASK = (1L << (long) BITS) - 1L;
private final int[][] data;
private final long limit;
/**
* int file getter in memory
*
*/
public IntFileGetterInMemory(File file) throws IOException {
limit = file.length() / 4;
data = new int[(int) ((limit >>> BITS)) + 1][];
final int length0 = 1 << BITS;
for (int i = 0; i < data.length; i++) {
int length = (i < data.length - 1 ? length0 : (int) (limit & BIT_MASK) + 1);
data[i] = new int[length];
}
try (InputStream ins = new BufferedInputStream(new FileInputStream(file)); ProgressPercentage progress = new ProgressPercentage("Reading file: " + file, limit)) {
int whichArray = 0;
int indexInArray = 0;
int[] row = data[0];
for (long index = 0; index < limit; index++) {
row[indexInArray] = ((ins.read() & 0xFF) << 24) + (((ins.read()) & 0xFF) << 16) + (((ins.read()) & 0xFF) << 8) + (ins.read() & 0xFF);
if (++indexInArray == length0) {
row = data[++whichArray];
indexInArray = 0;
}
progress.setProgress(index);
}
}
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) {
return data[(int) (index >>> BITS)][(int) (index & BIT_MASK)];
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
}
}
| 2,757 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFileGetterHashMap.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntFileGetterHashMap.java | /*
* IntFileGetterHashMap.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.io;
import jloda.util.FileLineIterator;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* map-based int getter
* Daniel 4.2015
*/
public class IntFileGetterHashMap implements IIntGetter {
private final Map<Long, Integer> map;
private long limit;
public IntFileGetterHashMap(File file) throws IOException {
map = new HashMap<>();
final FileLineIterator it = new FileLineIterator(file.getPath());
while (it.hasNext()) {
String aLine = it.next().trim();
if (!aLine.startsWith("#")) {
int pos = aLine.indexOf('\t');
if (pos > 0) {
long key = Long.parseLong(aLine.substring(0, pos));
if (key + 1 >= limit)
limit = key + 1;
map.put(key, Integer.parseInt(aLine.substring(pos + 1)));
}
}
}
it.close();
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) {
Integer value = map.get(index);
return Objects.requireNonNullElse(value, 0);
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
}
}
| 2,297 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
OutputWriter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/OutputWriter.java | /*
* OutputWriter.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.io;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* class for writing output
* Daniel Huson, 6.2009, 8.2015
*/
public class OutputWriter implements IOutputWriter, IInputReaderOutputWriter {
private static final int BUFFER_SIZE = 8192;
private final BufferedOutputStream outs;
private long position;
private final Compressor compressor = new Compressor();
private byte[] byteBuffer = new byte[1000];
private boolean useCompression = true;
/**
* constructor
*
*/
public OutputWriter(File file) throws IOException {
this.outs = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
position = 0;
}
/**
* constructor
*
*/
public OutputWriter(File file, boolean append) throws IOException {
this.outs = new BufferedOutputStream(new FileOutputStream(file, append), BUFFER_SIZE);
position = file.length();
}
/**
* write an int
*
*/
public void writeInt(int a) throws IOException {
outs.write((byte) (a >> 24));
outs.write((byte) (a >> 16));
outs.write((byte) (a >> 8));
outs.write((byte) (a));
position += 4;
}
/**
* write a char
*
*/
public void writeChar(char a) throws IOException {
outs.write((byte) (a >> 8));
outs.write((byte) (a));
position += 2;
}
/**
* write a long
*
*/
public void writeLong(long a) throws IOException {
outs.write((byte) (a >> 56));
outs.write((byte) (a >> 48));
outs.write((byte) (a >> 40));
outs.write((byte) (a >> 32));
outs.write((byte) (a >> 24));
outs.write((byte) (a >> 16));
outs.write((byte) (a >> 8));
outs.write((byte) (a));
position += 8;
}
/**
* write a float
*
*/
public void writeFloat(float a) throws IOException {
writeInt(Float.floatToIntBits(a));
}
/**
* write a byte-byte-int
*
*/
public void writeByteByteInt(ByteByteInt a) throws IOException {
outs.write(a.getByte1());
outs.write(a.getByte2());
position += 2;
writeInt(a.getValue());
}
/**
* write a string, compressed, if long enough
*
*/
public void writeString(String str) throws IOException {
if (str == null)
writeInt(0);
else {
if (useCompression && str.length() >= Compressor.MIN_SIZE_FOR_DEFLATION) {
byte[] bytes = compressor.deflateString2ByteArray(str);
writeInt(-bytes.length);
outs.write(bytes, 0, bytes.length);
position += bytes.length;
} else {
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
writeInt(bytes.length);
outs.write(bytes, 0, bytes.length);
position += bytes.length;
}
}
}
/**
* write a string, compressed, if long enough
*
*/
public void writeString(byte[] str, int offset, int length) throws IOException {
if (str == null)
writeInt(0);
else {
if (useCompression && length >= Compressor.MIN_SIZE_FOR_DEFLATION) {
if (byteBuffer.length < length)
byteBuffer = new byte[2 * length]; // surely compressed with never be longer than 2*uncompressed
int numberOfBytes = compressor.deflateString2ByteArray(str, offset, length, byteBuffer);
writeInt(numberOfBytes);
outs.write(byteBuffer, 0, Math.abs(numberOfBytes));
position += Math.abs(numberOfBytes);
} else {
writeInt(length);
outs.write(str, offset, length);
position += length;
}
}
}
/**
* Write a string without compression
*
*/
public void writeStringNoCompression(String str) throws IOException {
if (str == null) {
writeInt(0);
//do nothing
} else {
writeInt(str.length());
for (int i = 0; i < str.length(); i++)
outs.write((byte) str.charAt(i));
position += str.length();
}
}
/**
* compress strings?
*
* @return true, if strings are compressed
*/
public boolean isUseCompression() {
return useCompression;
}
/**
* compress strings?
*
*/
public void setUseCompression(boolean useCompression) {
this.useCompression = useCompression;
}
/**
* get position file
*
* @return position
*/
public long getPosition() {
return position;
}
/**
* write bytes
*
*/
public void write(byte[] bytes, int offset, int length) throws IOException {
outs.write(bytes, offset, length);
position += length;
}
/**
* writes bytes
*
*/
public void write(byte[] bytes) throws IOException {
outs.write(bytes);
position += bytes.length;
}
/**
* write a single byte
*
*/
public void write(int a) throws IOException {
outs.write(a);
position++;
}
/**
* close
*
*/
public void close() throws IOException {
outs.close();
}
/**
* supports seek?
*
* @return false
*/
public boolean supportsSeek() {
return false;
}
/**
* seek to the given position
*
*/
public void seek(long pos) throws IOException {
throw new IOException("seek(" + pos + "): not supported");
}
/**
* get length of file
*
* @return length
*/
public long length() {
return position;
}
@Override
public int read() throws IOException {
throw new IOException("Not implemented");
}
@Override
public int read(byte[] bytes, int offset, int len) throws IOException {
throw new IOException("Not implemented");
}
@Override
public int skipBytes(int bytes) throws IOException {
throw new IOException("Not implemented");
}
@Override
public void setLength(long length) throws IOException {
throw new IOException("Not implemented");
}
@Override
public int readInt() throws IOException {
throw new IOException("Not implemented");
}
@Override
public int readChar() throws IOException {
throw new IOException("Not implemented");
}
@Override
public long readLong() throws IOException {
throw new IOException("Not implemented");
}
@Override
public float readFloat() throws IOException {
throw new IOException("Not implemented");
}
@Override
public ByteByteInt readByteByteInt() throws IOException {
throw new IOException("Not implemented");
}
@Override
public String readString() throws IOException {
throw new IOException("Not implemented");
}
}
| 7,998 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BaseFileGetterPutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/BaseFileGetterPutter.java | /*
* BaseFileGetterPutter.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.io;
import jloda.util.Basic;
import jloda.util.progress.ProgressPercentage;
import java.io.*;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.LinkedList;
/**
* Base for memory-mapped file-based getters or putters
* Daniel Huson, 4.2015
*/
public abstract class BaseFileGetterPutter {
protected enum Mode {READ_ONLY, READ_WRITE, CREATE_READ_WRITE, CREATE_READ_WRITE_IN_MEMORY}
static final int BITS = 30;
static final int BLOCK_SIZE = (1 << BITS);
static final long BIT_MASK = (BLOCK_SIZE - 1L);
final ByteBuffer[] buffers;
private final FileChannel fileChannel;
final long fileLength;
private final File file;
private final boolean inMemory;
/**
* opens the named file as READ_ONLY
*/
protected BaseFileGetterPutter(File file) throws IOException {
this(file, 0, Mode.READ_ONLY);
}
/**
* constructor
*
* @param fileLength length of file to be created when mode==CREATE_READ_WRITE, otherwise ignored
*/
protected BaseFileGetterPutter(File file, long fileLength, Mode mode) throws IOException {
System.err.println("Opening file: " + file);
this.file = file;
this.inMemory = (mode == Mode.CREATE_READ_WRITE_IN_MEMORY);
final FileChannel.MapMode fileChannelMapMode;
switch (mode) {
case CREATE_READ_WRITE_IN_MEMORY:
case CREATE_READ_WRITE: {
// create the file and ensure that it has the given size
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
raf.setLength(fileLength);
} catch (IOException ex) {
System.err.println("Attempted file size: " + fileLength);
throw ex;
}
raf.close();
// fall through to READ_WRITE case....
}
case READ_WRITE: {
fileChannel = (new RandomAccessFile(file, "rw")).getChannel();
fileChannelMapMode = FileChannel.MapMode.READ_WRITE;
break;
}
default:
case READ_ONLY: {
fileChannel = (new RandomAccessFile(file, "r")).getChannel();
fileChannelMapMode = FileChannel.MapMode.READ_ONLY;
break;
}
}
// determine file size
{
if (!file.exists())
throw new IOException("No such file: " + file);
try (var raf = new RandomAccessFile(file, "r")) {
this.fileLength = raf.length();
}
if (fileLength > 0 && this.fileLength != fileLength) {
throw new IOException("File length expected: " + fileLength + ", got: " + this.fileLength);
}
}
if (inMemory)
System.err.println("Allocating: " + Basic.getMemorySizeString(this.fileLength));
final var list = new LinkedList<ByteBuffer>();
var blockNumber = 0L;
while (true) {
var start = blockNumber * BLOCK_SIZE;
var remaining = Math.min(BLOCK_SIZE, this.fileLength - start);
if (remaining > 0) {
if (inMemory) {
try {
ByteBuffer buffer = ByteBuffer.allocate((int) remaining);
list.add(buffer);
} catch (Exception ex) {
System.err.println("Memory allocation failed");
System.exit(1);
}
} else
list.add(fileChannel.map(fileChannelMapMode, start, remaining));
} else
break;
blockNumber++;
}
buffers = list.toArray(new ByteBuffer[0]);
if (mode == Mode.CREATE_READ_WRITE)
erase(); // clear the file
// System.err.println("Buffers: " + buffers.length);
}
static int getWhichBuffer(long filePos) {
return (int) (filePos >>> BITS);
}
static int getIndexInBuffer(long filePos) {
return (int) (filePos & BIT_MASK);
}
/**
* close the file
*/
public void close() {
try {
if (inMemory) {
fileChannel.close();
final ProgressPercentage progress = new ProgressPercentage("Writing file: " + file, buffers.length);
try (OutputStream outs = new BufferedOutputStream(new FileOutputStream(file), 1024000)) {
{
long total = 0;
for (ByteBuffer buffer : buffers)
total += buffer.limit();
System.err.println("Size: " + Basic.getMemorySizeString(total));
}
for (var buffer : buffers) {
// fileChannel.write(buffer); // only use this if buffer is direct because otherwise a direct copy is constructed during write
buffer.position(0);
while (true) {
try {
outs.write(buffer.get());
} catch (BufferUnderflowException | IndexOutOfBoundsException e) {
break; // buffer.get() also checks limit, so no need for us to check limit...
}
}
progress.incrementProgress();
}
}
progress.close();
}
Arrays.fill(buffers, null);
fileChannel.close();
} catch (IOException e) {
Basic.caught(e);
}
}
/**
* erase file by setting all bytes to 0
*/
private void erase() {
byte[] bytes = null;
for (var buffer : buffers) {
if (bytes == null || bytes.length < buffer.limit())
bytes = new byte[buffer.limit()];
buffer.position(0);
buffer.put(bytes, 0, buffer.limit());
buffer.position(0);
}
}
/**
* length of array
*
* @return array length
*/
abstract public long limit();
/**
* resize a file and fill new bytes with zeros
*/
static void resize(File file, long newLength) throws IOException {
final long oldLength;
try (var raf = new RandomAccessFile(file, "r")) {
oldLength = raf.length();
if (newLength < oldLength) {
raf.setLength(newLength);
}
}
if (newLength > oldLength) {
try (var outs = new BufferedOutputStream(new FileOutputStream(file, true))) {
var count = newLength - oldLength;
while (--count >= 0) {
outs.write(0);
}
}
}
if(oldLength!=newLength) {
var theLength = file.length();
if (theLength != newLength)
throw new IOException("Failed to resize file to length: " + newLength + ", length is: " + theLength);
}
}
}
| 6,719 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InputStreamAdapter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/InputStreamAdapter.java | /*
* InputStreamAdapter.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.io;
import java.io.IOException;
import java.io.InputStream;
/**
* Input adapter
* Daniel Huson, 6.2009
*/
public class InputStreamAdapter implements IInput {
private final InputStream ins;
private long position;
public InputStreamAdapter(InputStream ins) {
this.ins = ins;
}
public void seek(long pos) {
}
public boolean supportsSeek() {
return false;
}
/**
* skip some bytes
*
* @return number of bytes skipped
*/
public int skipBytes(int bytes) throws IOException {
int skipped = (int) ins.skip(bytes);
position += skipped;
return skipped;
}
/**
* read some bytes
*
* @return number of bytes read
*/
public int read(byte[] bytes, int offset, int len) throws IOException {
int count = ins.read(bytes, offset, len);
position += count;
return count;
}
public long getPosition() {
return position;
}
public long length() throws IOException {
if (ins instanceof IInput)
return ((IInput) ins).length();
return Long.MAX_VALUE;
}
@Override
public int read() throws IOException {
position++;
return ins.read();
}
@Override
public void close() throws IOException {
ins.close();
}
}
| 2,171 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IInputReader.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IInputReader.java | /*
* IInputReader.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.io;
import java.io.Closeable;
import java.io.IOException;
/**
* common interface for both InputReader and InputOutputReaderWriter
* Daniel Huson, 8.2008
*/
public interface IInputReader extends Closeable {
int readInt() throws IOException;
int readChar() throws IOException;
int read() throws IOException;
int read(byte[] bytes, int offset, int len) throws IOException;
long readLong() throws IOException;
float readFloat() throws IOException;
ByteByteInt readByteByteInt() throws IOException;
String readString() throws IOException;
int skipBytes(int bytes) throws IOException;
long length() throws IOException;
long getPosition() throws IOException;
boolean supportsSeek() throws IOException;
void seek(long pos) throws IOException;
}
| 1,629 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IInputOutput.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IInputOutput.java | /*
* IInputOutput.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.io;
import java.io.IOException;
/**
* interface for read-write access
* Daniel Huson, 6.2009
*/
interface IInputOutput extends IBaseIO {
int read() throws IOException;
int read(byte[] bytes, int offset, int len) throws IOException;
void write(int a) throws IOException;
void write(byte[] bytes, int offset, int length) throws IOException;
int skipBytes(int bytes) throws IOException;
void setLength(long length) throws IOException;
}
| 1,290 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IByteGetter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IByteGetter.java | /*
* IByteGetter.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.io;
import java.io.IOException;
/**
* A readonly long-indexed array of bytes
* Daniel Huson, 4.2015
*/
public interface IByteGetter extends AutoCloseable {
/**
* gets value for given index
*
* @return value or 0
*/
int get(long index) throws IOException;
/**
* bulk get
*
*/
int get(long index, byte[] bytes, int offset, int len) throws IOException;
/**
* gets next four bytes as a single integer
*
* @return integer
*/
int getInt(long index) throws IOException;
/**
* length of array
*
* @return array length
*/
long limit();
/**
* close the file
*/
void close();
}
| 1,516 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ILongPutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/ILongPutter.java | /*
* ILongPutter.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.io;
/**
* A read and write long-indexed array of longs
* Daniel Huson, 4.2015
*/
public interface ILongPutter extends AutoCloseable {
/**
* gets value for given index
*
* @return value or 0
*/
long get(long index);
/**
* puts value for given index
*
* @param value return the putter
*/
ILongPutter put(long index, long value);
/**
* length of array
*
* @return array length
*/
long limit();
/**
* close the array
*/
void close();
}
| 1,359 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LongFileGetterInMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/LongFileGetterInMemory.java | /*
* LongFileGetterInMemory.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.io;
import jloda.util.progress.ProgressPercentage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* long file getter in memory
* Daniel Huson, 5.2015
*/
public class LongFileGetterInMemory implements ILongGetter {
private final int BITS = 30;
private final long BIT_MASK = (1L << (long) BITS) - 1L;
private final long[][] data;
private final long limit;
/**
* long file getter in memory
*
*/
public LongFileGetterInMemory(File file) throws IOException {
limit = file.length() / 8;
data = new long[(int) ((limit >>> BITS)) + 1][];
final int length0 = (1 << BITS);
for (int i = 0; i < data.length; i++) {
int length = (i < data.length - 1 ? length0 : (int) (limit & BIT_MASK) + 1);
data[i] = new long[length];
}
try (BufferedInputStream ins = new BufferedInputStream(new FileInputStream(file)); ProgressPercentage progress = new ProgressPercentage("Reading file: " + file, limit)) {
int whichArray = 0;
int indexInArray = 0;
for (long index = 0; index < limit; index++) {
data[whichArray][indexInArray] = (((long) ins.read()) << 56) | (((long) ins.read()) << 48) | (((long) ins.read()) << 40) | (((long) ins.read()) << 32)
| (((long) ins.read()) << 24) | (((long) ins.read() & 0xFF) << 16) | (((long) ins.read() & 0xFF) << 8) | (((long) ins.read() & 0xFF));
if (++indexInArray == length0) {
whichArray++;
indexInArray = 0;
}
progress.setProgress(index);
}
}
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public long get(long index) {
return data[(int) (index >>> BITS)][(int) (index & BIT_MASK)];
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
}
}
| 3,007 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IOutputWriter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IOutputWriter.java | /*
* IOutputWriter.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.io;
import java.io.Closeable;
import java.io.IOException;
/**
* common interface for both OutputWriter and InputOutputReaderWriter
* Daniel Huson, 8.2008
*/
public interface IOutputWriter extends Closeable {
void writeInt(int a) throws IOException;
void writeChar(char a) throws IOException;
void write(int a) throws IOException;
void write(byte[] bytes, int offset, int length) throws IOException;
void write(byte[] bytes) throws IOException;
void writeLong(long a) throws IOException;
void writeFloat(float a) throws IOException;
void writeByteByteInt(ByteByteInt a) throws IOException;
void writeString(String str) throws IOException;
void writeString(byte[] str, int offset, int length) throws IOException;
void writeStringNoCompression(String str) throws IOException;
long length() throws IOException;
long getPosition() throws IOException;
boolean isUseCompression();
void setUseCompression(boolean use);
}
| 1,816 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LongFileGetterMappedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/LongFileGetterMappedMemory.java | /*
* LongFileGetterMappedMemory.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Open and read file of longs. File can be arbitrarily large, uses memory mapping.
* <p/>
* Daniel Huson, 4.2015
*/
public class LongFileGetterMappedMemory extends BaseFileGetterPutter implements ILongGetter {
/**
* constructor
*
*/
public LongFileGetterMappedMemory(File file) throws IOException {
super(file);
}
/**
* gets value for given index
*
* @return value or 0
*/
public long get(long index) {
if (index < limit()) {
index <<= 3; // convert to file position
final ByteBuffer buf = buffers[getWhichBuffer(index)];
int indexBuffer = getIndexInBuffer(index);
return (((long) buf.get(indexBuffer++)) << 56) + ((long) (buf.get(indexBuffer++) & 0xFF) << 48) + ((long) (buf.get(indexBuffer++) & 0xFF) << 40) +
((long) (buf.get(indexBuffer++) & 0xFF) << 32) + ((long) (buf.get(indexBuffer++) & 0xFF) << 24) + ((long) (buf.get(indexBuffer++) & 0xFF) << 16) +
((long) (buf.get(indexBuffer++) & 0xFF) << 8) + (((long) buf.get(indexBuffer) & 0xFF));
} else
return 0;
}
/**
* length of array (file length / 8)
*
* @return array length
*/
@Override
public long limit() {
return fileLength >>> 3;
}
}
| 2,245 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFilePutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntFilePutter.java | /*
* IntFilePutter.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Open a file for reading and writing
* <p/>
* Daniel Huson, 4.2015
*/
public class IntFilePutter extends BaseFileGetterPutter implements IIntPutter, IIntGetter {
/**
* constructor to read and write values from an existing file
*
*/
public IntFilePutter(File file) throws IOException {
super(file, 0, Mode.READ_WRITE);
}
/**
* constructs a int file putter using the given file and limit. (Is not in-memory)
*
* @param limit length of array
*/
public IntFilePutter(File file, long limit) throws IOException {
this(file, limit, false);
}
/**
* constructs a int file putter using the given file and limit
*
* @param limit length of array
* @param inMemory create in memory and then save on close? This uses more memory, but may be faster
*/
public IntFilePutter(File file, long limit, boolean inMemory) throws IOException {
super(file, 4 * limit, inMemory ? Mode.CREATE_READ_WRITE_IN_MEMORY : Mode.CREATE_READ_WRITE);
}
/**
* gets value for given index
*
* @return value or 0
*/
public int get(long index) {
if (index < limit()) {
index <<= 2; // convert to file position
final ByteBuffer buf = buffers[getWhichBuffer(index)];
int indexBuffer = getIndexInBuffer(index);
return ((buf.get(indexBuffer++)) << 24) + ((buf.get(indexBuffer++) & 0xFF) << 16) +
((buf.get(indexBuffer++) & 0xFF) << 8) + ((buf.get(indexBuffer) & 0xFF));
} else
return 0;
}
/**
* puts value for given index
*
*/
@Override
public void put(long index, int value) {
index <<= 2; // convert to file position
if (index < fileLength) {
final ByteBuffer buf = buffers[getWhichBuffer(index)];
int indexBuffer = getIndexInBuffer(index);
buf.put(indexBuffer++, (byte) (value >> 24));
buf.put(indexBuffer++, (byte) (value >> 16));
buf.put(indexBuffer++, (byte) (value >> 8));
buf.put(indexBuffer, (byte) (value));
} else {
throw new ArrayIndexOutOfBoundsException("" + index);
}
}
/**
* length of array (file length / 4)
*
* @return array length
*/
@Override
public long limit() {
return fileLength >>> 2;
}
/**
* set a new limit for a file
*
*/
public static void setLimit(File file, long newLimit) throws IOException {
System.err.println("new limit: " + newLimit);
resize(file, 4 * (newLimit + 1));
}
}
| 3,553 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FileRandomAccessReadWriteAdapter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/FileRandomAccessReadWriteAdapter.java | /*
* FileRandomAccessReadWriteAdapter.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.io;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* wrapper from random access read-write file
* Daniel Huson, 6.2009
*/
public class FileRandomAccessReadWriteAdapter extends RandomAccessFile implements IInputOutput, IOutput {
public FileRandomAccessReadWriteAdapter(String file, String mode) throws FileNotFoundException {
super(file, mode);
}
public long getPosition() throws IOException {
return getChannel().position();
}
public boolean supportsSeek() {
return true;
}
}
| 1,432 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IInput.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IInput.java | /*
* IInput.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.io;
import java.io.IOException;
/**
* minimal input interface
* Daniel Huson, 6.2009
*/
public interface IInput extends IBaseIO {
int read() throws IOException;
int read(byte[] bytes, int offset, int len) throws IOException;
int skipBytes(int bytes) throws IOException;
}
| 1,108 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
OutputWriterHumanReadable.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/OutputWriterHumanReadable.java | /*
* OutputWriterHumanReadable.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.io;
import jloda.util.StringUtils;
import java.io.IOException;
import java.io.Writer;
/**
* human readable output writer for debugging
* daniel HUson, 5.2015
*/
public class OutputWriterHumanReadable implements IOutputWriter {
private final Writer w;
private long pos = 0;
/**
* constructor
*
*/
public OutputWriterHumanReadable(Writer w) {
this.w = w;
}
@Override
public void writeInt(int a) throws IOException {
writeString(String.format("%d", a));
}
@Override
public void writeChar(char a) throws IOException {
writeString(String.format("%c", a));
}
@Override
public void write(int a) throws IOException {
writeString(String.format("%c", (char) a));
}
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
writeString(StringUtils.toString(bytes, offset, length));
}
@Override
public void write(byte[] bytes) throws IOException {
writeString(StringUtils.toString(bytes));
}
@Override
public void writeLong(long a) throws IOException {
writeString(String.format("%d", a));
}
@Override
public void writeFloat(float a) throws IOException {
writeString(String.format("%g", a));
}
@Override
public void writeByteByteInt(ByteByteInt a) throws IOException {
writeString(a.toString());
}
@Override
public void writeString(String str) throws IOException {
w.write(str + "\n");
if (str != null)
pos += str.length() + 1;
}
@Override
public void writeString(byte[] str, int offset, int length) throws IOException {
for (int i = 0; i < length; i++)
w.write("" + str[i]);
w.write("\n");
pos += length;
}
@Override
public void writeStringNoCompression(String str) throws IOException {
writeString(str);
}
@Override
public long length() {
return pos;
}
@Override
public long getPosition() {
return pos;
}
@Override
public boolean isUseCompression() {
return false;
}
@Override
public void setUseCompression(boolean use) {
}
@Override
public void close() throws IOException {
w.close();
}
public String toString() {
return w.toString();
}
}
| 3,224 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFileGetterMappedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntFileGetterMappedMemory.java | /*
* IntFileGetterMappedMemory.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Open and read file of integers. File can be arbitrarily large, uses memory mapping.
* <p/>
* Daniel Huson, 4.2015
*/
public class IntFileGetterMappedMemory extends BaseFileGetterPutter implements IIntGetter {
/**
* constructor
*
*/
public IntFileGetterMappedMemory(File file) throws IOException {
super(file);
}
/**
* gets value for given index
*
* @return integer
*/
public int get(long index) {
if (index < limit()) {
index <<= 2; // convert to file position
// the following works because we buffers overlap by 4 bytes
int indexBuffer = getIndexInBuffer(index);
final ByteBuffer buf = buffers[getWhichBuffer(index)];
return ((buf.get(indexBuffer++)) << 24) + ((buf.get(indexBuffer++) & 0xFF) << 16) + ((buf.get(indexBuffer++) & 0xFF) << 8) + ((buf.get(indexBuffer) & 0xFF));
} else
return 0;
}
/**
* length of array (file length/4)
*
* @return array length
*/
@Override
public long limit() {
return fileLength >>> 2;
}
}
| 2,044 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IBaseIO.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IBaseIO.java | /*
* IBaseIO.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.io;
import java.io.Closeable;
import java.io.IOException;
/**
* basic file access
* Daniel Huson, 6.2009
*/
public interface IBaseIO extends Closeable {
long getPosition() throws IOException;
long length() throws IOException;
boolean supportsSeek() throws IOException;
void seek(long pos) throws IOException;
}
| 1,152 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InputOutputReaderWriter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/InputOutputReaderWriter.java | /*
* InputOutputReaderWriter.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;
/**
* read input and write output
* Daniel Huson, 6.2009
*/
public class InputOutputReaderWriter implements IInputReaderOutputWriter {
private final Compressor compressor = new Compressor();
private boolean useCompression = true;
private final IInputOutput io;
private byte[] byteBuffer = new byte[1000];
private long offset = 0;
/**
* constructor.
*
* @param io an input-output class
*/
public InputOutputReaderWriter(IInputOutput io) {
this.io = io;
}
public InputOutputReaderWriter(String file) throws IOException {
this(file, "r");
//this(new FileRandomAccessReadWriteAdapter(file));
}
public InputOutputReaderWriter(File file, String mode) throws IOException {
this(file.getPath(), mode);
}
public InputOutputReaderWriter(String file, String mode) throws IOException {
this.io = new FileRandomAccessReadWriteAdapter(file, mode);
}
public int readInt() throws IOException {
return ((io.read()) << 24) + ((io.read() & 0xFF) << 16) + ((io.read() & 0xFF) << 8) + ((io.read() & 0xFF));
}
public int readChar() throws IOException {
return ((io.read() & 0xFF) << 8) + ((io.read() & 0xFF));
}
public long readLong() throws IOException {
return (((long) io.read()) << 56) + (((long) io.read()) << 48) + (((long) io.read()) << 40) + (((long) io.read()) << 32)
+ (((long) io.read()) << 24) + (((long) io.read() & 0xFF) << 16) + (((long) io.read() & 0xFF) << 8) + (((long) io.read() & 0xFF));
}
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
public ByteByteInt readByteByteInt() throws IOException {
return new ByteByteInt((byte) io.read(), (byte) io.read(), readInt());
}
/**
* reads an archived string
*
* @return string
*/
public String readString() throws IOException {
int size = readInt();
if (Math.abs(size) > 100000000)
throw new IOException("Unreasonable string length: " + Math.abs(size));
byte[] bytes = new byte[Math.abs(size)];
int got = io.read(bytes, 0, Math.abs(size));
if (got != Math.abs(size))
throw new IOException("Bytes read: " + got + ", expected: " + Math.abs(size));
if (size < 0) // is zip compressed
{
try {
return compressor.inflateByteArray2String(-size, bytes);
} catch (DataFormatException e) {
throw new IOException(e.getMessage());
}
} else {
return Compressor.convertUncompressedByteArray2String(size, bytes);
}
}
/**
* skip some bytes
*
*/
public int skipBytes(int bytes) throws IOException {
return io.skipBytes(bytes);
}
public int read() throws IOException {
return io.read();
}
public int read(byte[] bytes, int offset, int len) throws IOException {
return io.read(bytes, offset, len);
}
/**
* write an int
*
*/
public void writeInt(int a) throws IOException {
io.write((byte) (a >> 24));
io.write((byte) (a >> 16));
io.write((byte) (a >> 8));
io.write((byte) (a));
}
/**
* write a char
*
*/
public void writeChar(char a) throws IOException {
io.write((byte) (a >> 8));
io.write((byte) (a));
}
/**
* write a long
*
*/
public void writeLong(long a) throws IOException {
io.write((byte) (a >> 56));
io.write((byte) (a >> 48));
io.write((byte) (a >> 40));
io.write((byte) (a >> 32));
io.write((byte) (a >> 24));
io.write((byte) (a >> 16));
io.write((byte) (a >> 8));
io.write((byte) (a));
}
/**
* write a float
*
*/
public void writeFloat(float a) throws IOException {
writeInt(Float.floatToIntBits(a));
}
/**
* write a byte-byte-int
*
*/
public void writeByteByteInt(ByteByteInt a) throws IOException {
io.write(a.getByte1());
io.write(a.getByte2());
writeInt(a.getValue());
}
/**
* write a string
*
*/
public void writeString(String str) throws IOException {
if (str == null)
writeInt(0);
else {
if (useCompression && str.length() >= Compressor.MIN_SIZE_FOR_DEFLATION) {
byte[] bytes = compressor.deflateString2ByteArray(str);
writeInt(-bytes.length);
io.write(bytes, 0, bytes.length);
} else {
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
writeInt(bytes.length);
io.write(bytes, 0, bytes.length);
}
}
}
/**
* write a string, compressed, if long enough
*
*/
@Override
public void writeString(byte[] str, int offset, int length) throws IOException {
if (str == null)
writeInt(0);
else {
if (useCompression && length >= Compressor.MIN_SIZE_FOR_DEFLATION) {
if (byteBuffer.length < length)
byteBuffer = new byte[2 * length]; // surely compressed with never be longer than 2*uncompressed
int numberOfBytes = compressor.deflateString2ByteArray(str, offset, length, byteBuffer);
writeInt(numberOfBytes);
io.write(byteBuffer, 0, Math.abs(numberOfBytes));
} else {
writeInt(length);
io.write(str, offset, length);
}
}
}
/**
* Write a string without compression
*
*/
public void writeStringNoCompression(String str) throws IOException {
if (str == null) {
writeInt(0);
//do nothing
} else {
writeInt(str.length());
for (int i = 0; i < str.length(); i++)
io.write((byte) str.charAt(i));
}
}
public long getPosition() throws IOException {
return io.getPosition() - offset;
}
public void write(byte[] bytes, int offset, int length) throws IOException {
io.write(bytes, offset, length);
}
public void write(byte[] bytes) throws IOException {
io.write(bytes, 0, bytes.length);
}
public void write(int a) throws IOException {
io.write(a);
}
public void close() throws IOException {
io.close();
}
public long length() throws IOException {
return io.length() + offset;
}
/**
* compress strings?
*
* @return true, if strings are compressed
*/
public boolean isUseCompression() {
return useCompression;
}
/**
* compress strings?
*
*/
public void setUseCompression(boolean useCompression) {
this.useCompression = useCompression;
}
public void setLength(long length) throws IOException {
io.setLength(length);
}
/**
* get the offset that is applied to all seek() calls
*
* @return offest
*/
public long getOffset() {
return offset;
}
/**
* set offset that is applied to all seek() calls
*
*/
public void setOffset(long offset) {
this.offset = offset;
}
public void seekToEnd() throws IOException {
io.seek(io.length());
}
public boolean supportsSeek() throws IOException {
return io.supportsSeek();
}
public void seek(long pos) throws IOException {
io.seek(pos + offset);
}
}
| 8,620 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteFileGetterInMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/ByteFileGetterInMemory.java | /*
* ByteFileGetterInMemory.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.io;
import jloda.util.CanceledException;
import jloda.util.progress.ProgressPercentage;
import java.io.*;
/**
* byte file getter in memory
* Daniel Huson, 5.2015
*/
public class ByteFileGetterInMemory implements IByteGetter {
private final int BITS = 30;
private final long BIT_MASK = (1L << (long) BITS) - 1L;
private final byte[][] data;
private final long limit;
/**
* int file getter in memory
*
*/
public ByteFileGetterInMemory(File file) throws IOException, CanceledException {
limit = file.length();
data = new byte[(int) ((limit >>> BITS)) + 1][];
final int length0 = (1 << BITS);
for (int i = 0; i < data.length; i++) {
int length = (i < data.length - 1 ? length0 : (int) (limit & BIT_MASK) + 1);
data[i] = new byte[length];
}
try (InputStream ins = new BufferedInputStream(new FileInputStream(file)); ProgressPercentage progress = new ProgressPercentage("Reading file: " + file, limit)) {
int whichArray = 0;
int indexInArray = 0;
for (long index = 0; index < limit; index++) {
data[whichArray][indexInArray] = (byte) ins.read();
if (++indexInArray == length0) {
whichArray++;
indexInArray = 0;
}
progress.setProgress(index);
}
}
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) {
return data[(int) (index >>> BITS)][(int) (index & BIT_MASK)];
}
/**
* bulk get
*
*/
@Override
public int get(long index, byte[] bytes, int offset, int len) {
for (int i = 0; i < len; i++) {
// bytes[offset + i]=get(index++);
bytes[offset + i] = data[(int) (index >>> BITS)][(int) (index & BIT_MASK)];
index++;
}
return len;
}
/**
* gets next four bytes as a single integer
*
* @return integer
*/
@Override
public int getInt(long index) {
//return ((get(index++) & 0xFF) << 24) + ((get(index++) & 0xFF) << 16) + ((get(index++) & 0xFF) << 8) + ((get(index) & 0xFF));
return (((int) (data[(int) (index >>> BITS)][(int) (index++ & BIT_MASK)]) & 0xFF) << 24)
+ (((int) (data[(int) (index >>> BITS)][(int) (index++ & BIT_MASK)]) & 0xFF) << 16)
+ (((int) (data[(int) (index >>> BITS)][(int) (index++ & BIT_MASK)]) & 0xFF) << 8)
+ (((int) (data[(int) (index >>> BITS)][(int) (index & BIT_MASK)]) & 0xFF));
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
}
/**
* get current array
*
* @return array index
* @deprecated
*/
@Deprecated
private int dataIndex(long index) {
return (int) (index >>> BITS);
}
/**
* get position in current array
*
* @return pos
* @deprecated
*/
@Deprecated
private int dataPos(long index) {
return (int) (index & BIT_MASK);
}
/**
* test indexing
*
*/
public static void main(String[] args) throws Exception {
ByteFileGetterInMemory byteFileGetterInMemory = new ByteFileGetterInMemory(new File("/dev/null"));
int length0 = (1 << byteFileGetterInMemory.BITS);
for (long i = 0; i < 10L * Integer.MAX_VALUE; i++) {
int index = byteFileGetterInMemory.dataIndex(i);
int pos = byteFileGetterInMemory.dataPos(i);
long result = (long) index * (long) length0 + (long) pos;
if (result != i)
throw new Exception("i=" + i + " != result=" + result);
}
}
}
| 4,751 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InputReader.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/InputReader.java | /*
* InputReader.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.io;
import jloda.util.Basic;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.zip.DataFormatException;
/**
* a class to access input with, memory-mapped, if possible
* Daniel Huson, 2.2011
*/
public class InputReader implements IInputReader {
private final boolean useAbsoluteFilePositions;
private final Compressor compressor = new Compressor();
private final FileChannel channel;
private final long start;
private final long length;
private final IInput in;
/**
* constructor from input class
*
* @param in an input input class
*/
public InputReader(IInput in) throws IOException {
this.in = in;
start = 0;
useAbsoluteFilePositions = true;
length = this.in.length();
channel = null;
}
/**
* constructor
*
*/
public InputReader(File file) throws IOException {
this(file, null, null, true);
}
/**
* constructor
*
* @param file file to read
* @param start start position in file or null
* @param end end position in file or null
* @param useAbsoluteFilePositions use absolute positions in file rather than relative to start
*/
public InputReader(File file, Long start, Long end, boolean useAbsoluteFilePositions) throws IOException {
if (start == null)
start = 0L;
if (end == null) {
// need to grab the true length from here: (not from File.length())
RandomAccessFile fr = new RandomAccessFile(file, "r");
end = fr.length();
fr.close();
}
this.start = start;
// System.err.println("InputReader(file=" + file.get() + ",start=" + start + ",end=" + end + ",useAbs=" + useAbsoluteFilePositions + ",mapped=" + mapped + ")");
this.useAbsoluteFilePositions = useAbsoluteFilePositions;
try {
FileRandomAccessReadOnlyAdapter in = new FileRandomAccessReadOnlyAdapter(file);
channel = in.getChannel();
this.in = in;
if (useAbsoluteFilePositions) {
length = end;
seek(start);
} else {
length = end - start;
seek(0);
}
} catch (IOException ex) {
Basic.caught(ex);
throw ex;
}
}
public int readInt() throws IOException {
return ((in.read()) << 24) | ((in.read() & 0xFF) << 16) | ((in.read() & 0xFF) << 8) | ((in.read() & 0xFF));
}
public int readChar() throws IOException {
return ((in.read() & 0xFF) << 8) | ((in.read() & 0xFF));
}
public long readLong() throws IOException {
return (((long) in.read()) << 56) | (((long) in.read()) << 48) | (((long) in.read()) << 40) | (((long) in.read()) << 32)
| (((long) in.read()) << 24) | (((long) in.read() & 0xFF) << 16) | (((long) in.read() & 0xFF) << 8) | (((long) in.read() & 0xFF));
}
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/**
* read bytes until next end of line
*
*/
public String readLine() throws IOException {
StringBuilder buf = new StringBuilder();
byte b = (byte) read();
while (b != '\n') {
buf.append((char) b);
b = (byte) in.read();
if (getPosition() >= length())
break;
}
return buf.toString();
}
public ByteByteInt readByteByteInt() throws IOException {
return new ByteByteInt((byte) in.read(), (byte) in.read(), readInt());
}
/**
* reads an archived string
*
* @return string
*/
public String readString() throws IOException {
int size = readInt();
if (Math.abs(size) > 100000000)
throw new IOException("Unreasonable string length: " + Math.abs(size));
byte[] bytes = new byte[Math.abs(size)];
int got = in.read(bytes, 0, Math.abs(size));
if (got != Math.abs(size))
throw new IOException("Bytes read: " + got + ", expected: " + Math.abs(size));
if (size < 0) // is zip compressed
{
try {
return compressor.inflateByteArray2String(-size, bytes);
} catch (DataFormatException e) {
throw new IOException(e.getMessage());
}
} else {
return Compressor.convertUncompressedByteArray2String(size, bytes);
}
}
/**
* reads an archived string
*
* @return string
*/
public int readString(byte[] tmp, byte[] target) throws IOException {
int size = readInt();
if (size > 0) {
if (size > target.length)
throw new IOException("Unreasonable string length: " + size);
return in.read(target, 0, size);
} else {
size = -size;
if (size > tmp.length)
throw new IOException("Unreasonable string length: " + size);
int got = in.read(tmp, 0, size);
if (got != size)
throw new IOException("Bytes read: " + got + ", expected: " + size);
try {
return compressor.inflateByteArray(size, tmp, target);
} catch (DataFormatException e) {
throw new IOException(e.getMessage());
}
}
}
/**
* skip some bytes
*
* @return number of bytes skipped
*/
public int skipBytes(int bytes) throws IOException {
return in.skipBytes(bytes);
}
public boolean supportsSeek() throws IOException {
return in.supportsSeek();
}
public void seek(long pos) throws IOException {
if (useAbsoluteFilePositions)
in.seek(pos);
else
in.seek(pos + start);
}
public long length() {
return length;
}
public int read() throws IOException {
return in.read();
}
public int read(byte[] bytes, int offset, int len) throws IOException {
return in.read(bytes, offset, len);
}
public long getPosition() throws IOException {
if (useAbsoluteFilePositions)
return in.getPosition();
else
return in.getPosition() - start;
}
public void close() throws IOException {
in.close();
}
public FileChannel getChannel() {
return channel;
}
public boolean isUseAbsoluteFilePositions() {
return useAbsoluteFilePositions;
}
}
| 7,506 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntMapPutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntMapPutter.java | /*
* IntMapPutter.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.io;
import jloda.util.Basic;
import jloda.util.FileLineIterator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* map based int putter
* Daniel Huson, 4.2015
*/
public class IntMapPutter implements IIntGetter, IIntPutter {
private final Map<Long, Integer> map;
private long limit;
private final File file;
private boolean mustWriteOnClose = false;
/**
* constructor
*
*/
public IntMapPutter(File file, boolean loadFileIfExists) throws IOException {
this.file = file;
map = new HashMap<>();
if (loadFileIfExists && file.exists()) {
final FileLineIterator it = new FileLineIterator(file.getPath());
while (it.hasNext()) {
String aLine = it.next().trim();
if (!aLine.startsWith("#")) {
int pos = aLine.indexOf('\t');
if (pos > 0) {
long index = Long.parseLong(aLine.substring(0, pos));
if (index + 1 >= limit)
limit = index + 1;
map.put(index, Integer.parseInt(aLine.substring(pos + 1)));
}
}
}
it.close();
}
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) {
Integer value = map.get(index);
return Objects.requireNonNullElse(value, 0);
}
/**
* puts value for given index
*
*/
@Override
public void put(long index, int value) {
if (index + 1 >= limit)
limit = index + 1;
map.put(index, value);
if (!mustWriteOnClose)
mustWriteOnClose = true;
}
/**
* length of array
* todo: limit can be incorrect if getMap() was used to change values
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
if (mustWriteOnClose) {
System.err.println("Writing file: " + file);
try (BufferedWriter w = new BufferedWriter(new FileWriter(file))) {
for (Long key : map.keySet()) {
w.write(key + "\t" + map.get(key) + "\n");
}
} catch (IOException ex) {
Basic.caught(ex);
}
}
}
}
| 3,418 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteByteInt.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/ByteByteInt.java | /*
* ByteByteInt.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.io;
import java.nio.charset.StandardCharsets;
/**
* two bytes and an integer, used for RefSeqs and similar accession numbers.
* E.g., XP_12345.1 will be coded as byte1=X, byte2=P and value=12345. The trailing stuff .1 is lost
* Daniel Huson, 1.2009
*/
public class ByteByteInt {
private byte byte1;
private byte byte2;
private int value;
public static final ByteByteInt ZERO = new ByteByteInt();
/**
* constructor
*/
public ByteByteInt() {
}
/**
* constructor
*
*/
public ByteByteInt(byte byte1, byte byte2, int value) {
this.byte1 = byte1;
this.byte2 = byte2;
this.value = value;
}
/**
* construct a ByteByteInt object from a string.
* E.g. XP_12345.1 will be parsed as byte1=X, byte2=P and value=12345
*
*/
public ByteByteInt(String string) {
if (string != null && string.length() >= 2) {
byte[] bytes = string.substring(0, 2).getBytes(StandardCharsets.UTF_8);
byte1 = bytes[0];
byte2 = bytes[1];
int a = 0;
int b = 0;
for (int pos = 2; pos < string.length(); pos++) {
if (a == 0) {
if (Character.isDigit(string.charAt(pos)))
a = pos;
} else {
if (!Character.isDigit(string.charAt(pos))) {
b = pos;
break;
}
}
}
if (a > 0) {
if (b == 0)
b = string.length();
try {
value = Integer.parseInt(string.substring(a, b));
} catch (NumberFormatException ex) {
// Basic.caught(ex);
}
}
}
}
public final byte getByte1() {
return byte1;
}
public final void setByte1(byte byte1) {
this.byte1 = byte1;
}
public final byte getByte2() {
return byte2;
}
public final void setByte2(byte byte2) {
this.byte2 = byte2;
}
public final int getValue() {
return value;
}
public final void setValue(int value) {
this.value = value;
}
public String toString() {
if (byte1 == 0)
return "";
else
return "" + (char) byte1 + (char) byte2 + "_" + value;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ByteByteInt that = (ByteByteInt) o;
if (byte1 != that.byte1) return false;
return byte2 == that.byte2 && value == that.value;
}
public int hashCode() {
int result;
result = byte1;
result = 31 * result + (int) byte2;
result = 31 * result + value;
return result;
}
/**
* get the RefSeq id in a string
*
* @param pos of current "ref|" tag
* @return refSeq id or null
*/
public static ByteByteInt getRefSeqId(String aLine, int pos) {
final int start = pos + 4;
int end = start;
while (end < aLine.length() && (Character.isLetterOrDigit(aLine.charAt(end)) || aLine.charAt(end) == '_'))
end++;
if (end > start)
return new ByteByteInt(aLine.substring(start, end));
else
return null;
}
}
| 4,268 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IIntGetter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IIntGetter.java | /*
* IIntGetter.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.io;
import java.io.IOException;
/**
* A readonly long-indexed array of ints
* Daniel Huson, 4.2015
*/
public interface IIntGetter extends AutoCloseable {
/**
* gets value for given index
*
* @return value or 0
*/
int get(long index) throws IOException;
/**
* length of array
*
* @return array length
*/
long limit();
/**
* close the array
*/
void close();
}
| 1,256 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IInputReaderOutputWriter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IInputReaderOutputWriter.java | /*
* IInputReaderOutputWriter.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.io;
import java.io.IOException;
/**
* interface for read-write access
* Daniel Huson, 6.2009
*/
public interface IInputReaderOutputWriter extends IInputOutput, IInputReader, IOutputWriter {
int read() throws IOException;
int read(byte[] bytes, int offset, int len) throws IOException;
void write(int a) throws IOException;
void write(byte[] bytes, int offset, int length) throws IOException;
int skipBytes(int bytes) throws IOException;
void setLength(long length) throws IOException;
}
| 1,355 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FileOutputStreamAdapter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/FileOutputStreamAdapter.java | /*
* FileOutputStreamAdapter.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.io;
import java.io.*;
/**
* file output wrapper
* Daniel Huson, 6.2009
*/
public class FileOutputStreamAdapter implements IOutput {
private static final int BUFFER_SIZE = 8192;
private final BufferedOutputStream outs;
private long position;
/**
* constructor
*
*/
public FileOutputStreamAdapter(File file) throws FileNotFoundException {
outs = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
position = 0;
}
/**
* constructor
*
*/
public FileOutputStreamAdapter(File file, boolean append) throws FileNotFoundException {
outs = new BufferedOutputStream(new FileOutputStream(file, append), BUFFER_SIZE);
if (append)
position = file.length();
}
/**
* get position in file
*
* @return position
*/
public long getPosition() {
return position;
}
/**
* get current length of file
*
* @return length
*/
public long length() {
return position;
}
/**
* seek, not supported
*
*/
public void seek(long pos) {
}
/**
* seek is not supported
*
* @return false
*/
public boolean supportsSeek() {
return false;
}
/**
* write a byte
*
*/
public void write(int a) throws IOException {
outs.write(a);
position++;
}
/**
* write bytes
*
*/
public void write(byte[] bytes, int offset, int length) throws IOException {
outs.write(bytes, offset, length);
position += length;
}
/**
* close this stream
*
*/
public void close() throws IOException {
outs.close();
}
/**
* flush the current stream
*
*/
public void flush() throws IOException {
outs.flush();
}
}
| 2,692 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IIntPutter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IIntPutter.java | /*
* IIntPutter.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.io;
/**
* A read and write long-indexed array of ints
* Daniel Huson, 4.2015
*/
public interface IIntPutter extends AutoCloseable {
/**
* gets value for given index
*
* @return value or 0
*/
int get(long index);
/**
* puts value for given index
*
* @param value return the putter
*/
void put(long index, int value);
/**
* length of array
*
* @return array length
*/
long limit();
/**
* close the array
*/
void close();
}
| 1,347 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Compressor.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/Compressor.java | /*
* Compressor.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.io;
//import jloda.util.Basic;
import jloda.util.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* compress and decompress strings
* Daniel Huson, 8.2008
*/
public class Compressor {
private final Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true);
private final Inflater inflater = new Inflater(true);
private byte[] buffer;
public static final int MIN_SIZE_FOR_DEFLATION = 90;
private boolean enabled = true;
/**
* default constructor
*/
public Compressor() {
this(1000000);
}
/**
* constructor
*
* @param maxStringLength - size of buffer
*/
public Compressor(int maxStringLength) {
buffer = new byte[maxStringLength];
}
/**
* gets a deflated string
*
* @return deflated string
*/
public byte[] deflateString2ByteArray(String inputString) {
int length = deflateString2ByteArray(inputString, buffer);
byte[] result = new byte[Math.abs(length)];
System.arraycopy(buffer, 0, result, 0, Math.abs(length));
return result;
}
/**
* compresses a string to an array of bytes
*
* @param bytes array to write bytes to
* @return number of bytes written (negative number, if bytes are not deflated)
*/
private int deflateString2ByteArray(String inputString, byte[] bytes) {
byte[] input;
input = inputString.getBytes(StandardCharsets.UTF_8);
return deflateString2ByteArray(input, 0, input.length, bytes);
}
/**
* compresses a string to an array of bytes
*
* @param bytes array to write bytes to
* @return number of bytes written (negative number, if bytes are not deflated)
*/
public int deflateString2ByteArray(byte[] input, int inputOffset, int inputLength, byte[] bytes) {
if (inputLength >= MIN_SIZE_FOR_DEFLATION) {
// Compress the bytes
deflater.setInput(input, inputOffset, inputLength);
deflater.finish();
int compressedDataLength = deflater.deflate(bytes);
deflater.reset();
return -compressedDataLength;
} else {
System.arraycopy(input, inputOffset, bytes, 0, inputLength);
return inputLength;
}
}
/**
* decompresses an array of bytes to a string
*
* @return decoded string
*/
public String inflateByteArray2String(int numberOfBytes, byte[] bytes) throws DataFormatException {
/*
StringBuilder buf = new StringBuilder();
for (byte aByte : input) buf.append((char) aByte);
return buf.toString();
*/
if (numberOfBytes == 0)
return "";
if (numberOfBytes < 0) // negative number means uncompressed!
{
return new String(bytes, 0, -numberOfBytes, StandardCharsets.UTF_8);
}
inflater.setInput(bytes, 0, numberOfBytes);
if (buffer.length < 100 * bytes.length) // try to make sure the result buffer is long enough
buffer = new byte[100 * bytes.length];
int resultLength = inflater.inflate(buffer);
String outputString;
outputString = new String(buffer, 0, resultLength, StandardCharsets.UTF_8);
inflater.reset();
return outputString;
}
/**
* decompresses an array of bytes to bytes
*
* @param numberOfBytes negative, if uncompressed, otherwise positive
* @param source input
* @param target output
* @return number of bytes
*/
public int inflateByteArray(int numberOfBytes, byte[] source, byte[] target) throws DataFormatException {
/*
StringBuilder buf = new StringBuilder();
for (byte aByte : input) buf.append((char) aByte);
return buf.toString();
*/
if (numberOfBytes == 0)
return 0;
if (numberOfBytes < 0) // negative number means uncompressed!
{
System.arraycopy(source, 0, target, 0, source.length);
return Math.abs(numberOfBytes);
}
inflater.setInput(source, 0, numberOfBytes);
int resultLength = inflater.inflate(target);
inflater.reset();
return resultLength;
}
/**
* interactively test deflation and inflation
*
*/
public static void main(String[] args) throws IOException, DataFormatException {
Compressor compression = new Compressor();
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
System.out.flush();
String inputString = "";
String aLine;
while ((aLine = r.readLine()) != null) {
if (aLine.length() > 0) {
if (aLine.equals(".")) {
// Encode a String into bytes
byte[] bytes = new byte[inputString.length() + 1000];
int numberOfBytes = compression.deflateString2ByteArray(inputString, bytes);
// Decode the bytes into a String
String outputString;
if (numberOfBytes < 0)
outputString = compression.inflateByteArray2String(-numberOfBytes, bytes);
else
outputString = Compressor.convertUncompressedByteArray2String(numberOfBytes, bytes);
System.err.println("=<" + outputString + ">");
System.err.println("= " + outputString);
System.err.println("uncompressed: " + inputString.length());
System.err.println("compressed: " + numberOfBytes);
System.err.println("decompressed: " + outputString.length());
{
byte[] target = new byte[10 * bytes.length];
compression.inflateByteArray(-numberOfBytes, bytes, target);
System.err.println("decompressed bytes: " + StringUtils.toString(target));
}
inputString = "";
System.out.print("> ");
} else {
inputString += aLine + "\n";
System.out.print("? ");
}
System.out.flush();
}
}
}
/**
* is enabled. Has no effect
*
* @return true, if enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* set enabled state. Has no effect
*
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* * convert an uncompressed array of bytes to a string
*
* @return string
*/
static public String convertUncompressedByteArray2String(int size, byte[] bytes) {
StringBuilder buf = new StringBuilder(size);
for (byte b : bytes) buf.append((char) b);
return buf.toString();
}
}
| 7,972 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteFileGetterMappedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/ByteFileGetterMappedMemory.java | /*
* ByteFileGetterMappedMemory.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.io;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Open and read file of bytes. File can be arbitrarily large, uses memory mapping. Also supports reading of ints
* <p/>
* Daniel Huson, 4.2015
*/
public class ByteFileGetterMappedMemory extends BaseFileGetterPutter implements IByteGetter {
/**
* constructor
*
*/
public ByteFileGetterMappedMemory(File file) throws IOException {
super(file); // need 4 overlap to allow reading of integers
}
/**
* gets value for given index
*
* @return integer
*/
public int get(long index) {
// note that index equals filePos and so no conversion from index to filePos necessary
if (index < limit()) {
return buffers[(int) (index >>> BITS)].get((int) (index & BIT_MASK)) & 0xFF;
} else
return 0;
}
/**
* bulk get
*
* @return number of bytes that we obtained
*/
@Override
public int get(long index, byte[] bytes, int offset, int len) {
// note that index equals filePos and so no conversion from index to filePos necessary
int whichBuffer = getWhichBuffer(index);
int indexInBuffer = getIndexInBuffer(index);
for (int i = 0; i < len; i++) {
bytes[offset++] = buffers[whichBuffer].get(indexInBuffer);
if (++indexInBuffer == BLOCK_SIZE) {
whichBuffer++;
if (whichBuffer == buffers.length)
return i;
indexInBuffer = 0;
}
}
return len;
}
/**
* gets integer represented by four bytes starting at given index
*
* @return integer
*/
@Override
public int getInt(long index) {
if (index < limit()) {
// note that index equals filePos and so no conversion from index to filePos necessary
int whichBuffer = getWhichBuffer(index);
int indexBuffer = getIndexInBuffer(index);
try {
final ByteBuffer buf = buffers[whichBuffer];
return buf.getInt(indexBuffer);
} catch (Exception ex) { // exception is thrown when int goes over buffer boundary. In this case, we need to grab each byte separately
int result = (buffers[whichBuffer].get(indexBuffer++) << 24);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += ((buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 16);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += ((buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 8);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += ((buffers[whichBuffer].get(indexBuffer) & 0xFF));
return result;
}
} else
return 0;
}
/**
* gets value for given index
*
* @return value or 0
*/
public long getLong(long index) {
if (index < limit()) {
// note that index equals filePos and so no conversion from index to filePos necessary
int whichBuffer = getWhichBuffer(index);
int indexBuffer = getIndexInBuffer(index);
try {
final ByteBuffer buf = buffers[whichBuffer];
return buf.getLong(indexBuffer);
} catch (Exception ex) { // exception is thrown when long goes over buffer boundary. In this case, we need to grab each byte separately
long result = ((long) buffers[whichBuffer].get(indexBuffer++) << 56);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 48);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 40);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 32);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 24);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 16);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer++) & 0xFF) << 8);
if (indexBuffer == BLOCK_SIZE) {
indexBuffer = 0;
whichBuffer++;
}
result += (((long) buffers[whichBuffer].get(indexBuffer) & 0xFF));
return result;
}
} else
return 0;
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return fileLength;
}
}
| 6,506 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IOutput.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IOutput.java | /*
* IOutput.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.io;
import java.io.IOException;
/**
* small file output stream
* Daniel Huson, 6.2009
*/
public interface IOutput extends IBaseIO {
void write(int a) throws IOException;
void write(byte[] bytes, int offset, int length) throws IOException;
}
| 1,073 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFileGetterRandomAccess.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/IntFileGetterRandomAccess.java | /*
* IntFileGetterRandomAccess.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.io;
import jloda.util.Basic;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* adapter from random-access read-only file
* Daniel Huson, 6.2009
*/
public class IntFileGetterRandomAccess extends RandomAccessFile implements IIntGetter {
/**
* constructor
*
*/
public IntFileGetterRandomAccess(File file) throws FileNotFoundException {
super(file, "r");
}
/**
* get an int from the given location
*
* @return int
*/
@Override
public int get(long index) {
try {
index <<= 2; // convert to file pos
if (index < length()) {
// synchronized (syncObject)
{
seek(index);
return readInt();
}
}
} catch (IOException e) {
Basic.caught(e);
}
return 0;
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
try {
return length() >>> 2;
} catch (IOException e) {
Basic.caught(e);
return 0;
}
}
public void close() {
try {
super.close();
} catch (IOException e) {
Basic.caught(e);
}
}
}
| 2,207 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FileRandomAccessReadOnlyAdapter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/FileRandomAccessReadOnlyAdapter.java | /*
* FileRandomAccessReadOnlyAdapter.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.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* adapter from random-access read-only file
* Daniel Huson, 6.2009
*/
public class FileRandomAccessReadOnlyAdapter extends RandomAccessFile implements IInput {
public FileRandomAccessReadOnlyAdapter(String fileName) throws FileNotFoundException {
super(fileName, "r");
}
public FileRandomAccessReadOnlyAdapter(File file) throws FileNotFoundException {
super(file, "r");
}
public long getPosition() throws IOException {
return getChannel().position();
}
public boolean supportsSeek() {
return true;
}
}
| 1,543 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FileInputStreamAdapter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/FileInputStreamAdapter.java | /*
* FileInputStreamAdapter.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.io;
import java.io.*;
/**
* File input adapter
* Daniel Huson, 6.2009
*/
public class FileInputStreamAdapter implements IInput {
private final BufferedInputStream bif;
private long position;
private final long length;
public FileInputStreamAdapter(String fileName) throws FileNotFoundException {
this(new File(fileName));
}
public FileInputStreamAdapter(File file) throws FileNotFoundException {
length = file.length();
bif = new BufferedInputStream(new FileInputStream(file));
position = 0;
}
public int read() throws IOException {
position++;
return bif.read();
}
public int read(byte[] bytes, int offset, int len) throws IOException {
int count = bif.read(bytes, offset, len);
position += count;
return count;
}
public void close() throws IOException {
bif.close();
}
public long getPosition() {
return position;
}
public long length() {
return length;
}
public void seek(long pos) throws IOException {
if (pos > position) {
long diff = (pos - position);
while (diff > 0) {
int moved = skipBytes((int) Math.min(Integer.MAX_VALUE >> 1, diff));
if (moved == 0)
throw new IOException("Failed to seek");
diff -= moved;
}
} else if (pos < position)
throw new IOException("Can't seek backward");
}
public boolean supportsSeek() {
return false;
}
/**
* skip n bytes
*
* @return number of bytes skipped
*/
public int skipBytes(int n) throws IOException {
int remaining = n;
while (remaining > 0) {
remaining -= (int) bif.skip(remaining);
}
position += n;
return n;
}
}
| 2,712 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ILongGetter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/ILongGetter.java | /*
* ILongGetter.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.io;
import java.io.IOException;
/**
* A readonly long-indexed array of longs
* Daniel Huson, 4.2015
*/
public interface ILongGetter extends AutoCloseable {
/**
* gets value for given index
*
* @return value or 0
*/
long get(long index) throws IOException;
/**
* length of array
*
* @return array length
*/
long limit();
/**
* close the array
*/
void close();
}
| 1,260 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LongFileGetterPagedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/experimental/LongFileGetterPagedMemory.java | /*
* LongFileGetterPagedMemory.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.io.experimental;
import jloda.util.Basic;
import megan.io.ILongGetter;
import megan.io.LongFileGetterMappedMemory;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;
/**
* long file getter in paged memory
* Daniel Huson, 5.2015
*/
public class LongFileGetterPagedMemory implements ILongGetter {
private final File file;
private final RandomAccessFile raf;
private final long[][] data;
private final long limit;
private final int length0;
private final int PAGE_BITS = 20; // 2^20=1048576
// private final int PAGE_BITS=10; // 2^10=1024
private int pages = 0;
/**
* long file getter in memory
*
*/
public LongFileGetterPagedMemory(File file) throws IOException {
this.file = file;
limit = file.length() / 8;
System.err.println("Opening file: " + file);
raf = new RandomAccessFile(file, "r");
data = new long[(int) ((limit >>> PAGE_BITS)) + 1][];
length0 = (int) (Math.min(limit, 1 << PAGE_BITS));
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public long get(long index) throws IOException {
int dIndex = dataIndex(index);
long[] array = data[dIndex];
if (array == null) {
synchronized (raf) {
if (data[dIndex] == null) {
pages++;
final int length;
if (dIndex == data.length - 1)
length = (int) (limit - (data.length - 1) * length0); // is the last chunk
else
length = length0;
array = new long[length];
long toSkip = (long) dIndex * (long) length0 * 8L;
raf.seek(toSkip);
for (int pos = 0; pos < array.length; pos++) {
array[pos] = (((long) (raf.read()) & 0xFF) << 56) + (((long) (raf.read()) & 0xFF) << 48) + (((long) (raf.read()) & 0xFF) << 40) + (((long) (raf.read()) & 0xFF) << 32)
+ (((long) (raf.read()) & 0xFF) << 24) + (((long) (raf.read()) & 0xFF) << 16) + (((long) (raf.read()) & 0xFF) << 8) + (((long) (raf.read()) & 0xFF));
}
data[dIndex] = array;
} else
array = data[dIndex];
}
}
return array[dataPos(index)];
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
try {
raf.close();
System.err.println("Closing file: " + file.getName() + " (" + pages + "/" + data.length + " pages)");
} catch (IOException e) {
Basic.caught(e);
}
}
private int dataIndex(long index) {
return (int) ((index >>> PAGE_BITS));
}
private int dataPos(long index) {
return (int) (index - (index >>> PAGE_BITS) * length0);
}
public static void main(String[] args) throws IOException {
File file = new File("/Users/huson/data/ma/protein/index-new/table0.idx");
final ILongGetter oldGetter = new LongFileGetterMappedMemory(file);
final ILongGetter newGetter = new LongFileGetterPagedMemory(file);
final Random random = new Random();
System.err.println("Limit: " + oldGetter.limit());
for (int i = 0; i < 100; i++) {
int r = random.nextInt((int) oldGetter.limit());
long oldValue = oldGetter.get(r);
long newValue = newGetter.get(r);
System.err.println(oldValue + (oldValue == newValue ? " == " : " != ") + newValue);
}
oldGetter.close();
newGetter.close();
}
}
| 4,736 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteFileGetterRandomAccess.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/experimental/ByteFileGetterRandomAccess.java | /*
* ByteFileGetterRandomAccess.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.io.experimental;
import jloda.util.Basic;
import megan.io.ByteFileGetterMappedMemory;
import megan.io.IByteGetter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;
/**
* byte file getter using paged memory
* Daniel Huson, 5.2015
*/
public class ByteFileGetterRandomAccess implements IByteGetter {
private final File file;
private final RandomAccessFile raf;
private final long limit;
/**
* constructor
*
*/
public ByteFileGetterRandomAccess(File file) throws IOException {
this.file = file;
limit = file.length();
System.err.println("Opening file: " + file);
raf = new RandomAccessFile(file, "r");
}
/**
* bulk get
*
*/
@Override
public int get(long index, byte[] bytes, int offset, int len) throws IOException {
synchronized (raf) {
raf.seek(index);
len = raf.read(bytes, offset, len);
}
return len;
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) throws IOException {
synchronized (raf) {
raf.seek(index);
return raf.read();
}
}
/**
* gets next four bytes as a single integer
*
* @return integer
*/
@Override
public int getInt(long index) throws IOException {
synchronized (raf) {
raf.seek(index);
return ((raf.read() & 0xFF) << 24) + ((raf.read() & 0xFF) << 16) + ((raf.read() & 0xFF) << 8) + (raf.read() & 0xFF);
}
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
try {
raf.close();
System.err.println("Closing file: " + file.getName());
} catch (IOException e) {
Basic.caught(e);
}
}
public static void main(String[] args) throws IOException {
File file = new File("/Users/huson/data/ma/protein/index-new/table0.idx");
final IByteGetter oldGetter = new ByteFileGetterMappedMemory(file);
final IByteGetter newGetter = new ByteFileGetterRandomAccess(file);
final Random random = new Random();
System.err.println("Limit: " + oldGetter.limit());
for (int i = 0; i < 100; i++) {
int r = random.nextInt((int) oldGetter.limit());
int oldValue = oldGetter.get(r);
int newValue = newGetter.get(r);
System.err.println(r + ": " + oldValue + (oldValue == newValue ? " == " : " != ") + newValue);
}
oldGetter.close();
newGetter.close();
}
}
| 3,656 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteFileStreamGetter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/experimental/ByteFileStreamGetter.java | /*
* ByteFileStreamGetter.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.io.experimental;
import jloda.util.Basic;
import megan.io.IByteGetter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* byte file getter input stream
* Daniel Huson, 2.2016
*/
public class ByteFileStreamGetter implements IByteGetter {
private final File file;
private final BufferedInputStream raf;
private final long limit;
private long currentIndex = 0;
/**
* constructor
*
*/
public ByteFileStreamGetter(File file) throws IOException {
this.file = file;
limit = file.length();
System.err.println("Opening file: " + file);
raf = new BufferedInputStream(new FileInputStream(file));
}
/**
* bulk get
*
*/
@Override
public int get(long index, byte[] bytes, int offset, int len) throws IOException {
synchronized (raf) {
if (index != currentIndex)
throw new IOException("seek(): not supported");
else {
len = raf.read(bytes, offset, len);
return len;
}
}
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) throws IOException {
synchronized (raf) {
if (index != currentIndex)
throw new IOException("seek(): not supported");
currentIndex++;
return raf.read();
}
}
/**
* gets next four bytes as a single integer
*
* @return integer
*/
@Override
public int getInt(long index) throws IOException {
synchronized (raf) {
if (index != currentIndex)
throw new IOException("seek(): not supported");
currentIndex += 4;
return ((raf.read() & 0xFF) << 24) + ((raf.read() & 0xFF) << 16) + ((raf.read() & 0xFF) << 8) + (raf.read() & 0xFF);
}
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
try {
raf.close();
System.err.println("Closing file: " + file.getName());
} catch (IOException e) {
Basic.caught(e);
}
}
public static void main(String[] args) throws IOException {
File file = new File("/Users/huson/data/ma/protein/index/table0.idx");
final IByteGetter getter = new ByteFileStreamGetter(file);
System.err.println("Limit: " + getter.limit());
for (int i = 0; i < 100; i++) {
int value = getter.get(i);
System.err.println(i + " -> " + value);
}
getter.close();
}
}
| 3,646 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IntFileGetterPagedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/experimental/IntFileGetterPagedMemory.java | /*
* IntFileGetterPagedMemory.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.io.experimental;
import jloda.util.Basic;
import megan.io.IIntGetter;
import megan.io.IntFileGetterMappedMemory;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;
/**
* int file getter in paged memory
* Daniel Huson, 5.2015
*/
public class IntFileGetterPagedMemory implements IIntGetter {
private final File file;
private final RandomAccessFile raf;
private final int[][] data;
private final long limit;
private final int length0;
private final int PAGE_BITS = 20; // 2^20=1048576
private int pages = 0;
/**
* long file getter in memory
*
*/
public IntFileGetterPagedMemory(File file) throws IOException {
this.file = file;
limit = file.length() / 4;
System.err.println("Opening file: " + file);
raf = new RandomAccessFile(file, "r");
data = new int[(int) ((limit >>> PAGE_BITS)) + 1][];
length0 = (int) (Math.min(limit, 1 << PAGE_BITS));
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) throws IOException {
int dIndex = dataIndex(index);
int[] array = data[dIndex];
if (array == null) {
synchronized (raf) {
if (data[dIndex] == null) {
pages++;
final int length;
if (dIndex == data.length - 1)
length = (int) (limit - (data.length - 1) * length0); // is the last chunk
else
length = length0;
array = new int[length];
long toSkip = (long) dIndex * (long) length0 * 4L;
raf.seek(toSkip);
for (int pos = 0; pos < array.length; pos++) {
array[pos] = ((raf.read() & 0xFF) << 24) + (((raf.read()) & 0xFF) << 16) + (((raf.read()) & 0xFF) << 8) + (raf.read() & 0xFF);
}
data[dIndex] = array;
} else
array = data[dIndex];
}
}
return array[dataPos(index)];
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
try {
raf.close();
System.err.println("Closing file: " + file.getName() + " (" + pages + "/" + data.length + " pages)");
} catch (IOException e) {
Basic.caught(e);
}
}
private int dataIndex(long index) {
return (int) ((index >>> PAGE_BITS));
}
private int dataPos(long index) {
return (int) (index - (index >>> PAGE_BITS) * length0);
}
public static void main(String[] args) throws IOException {
File file = new File("/Users/huson/data/ma/protein/index-new/table0.db");
final IIntGetter oldGetter = new IntFileGetterMappedMemory(file);
final IIntGetter newGetter = new IntFileGetterPagedMemory(file);
final Random random = new Random();
System.err.println("Limit: " + oldGetter.limit());
for (int i = 0; i < 100; i++) {
int r = random.nextInt((int) oldGetter.limit());
int oldValue = oldGetter.get(r);
int newValue = newGetter.get(r);
System.err.println(oldValue + (oldValue == newValue ? " == " : " != ") + newValue);
}
oldGetter.close();
newGetter.close();
}
}
| 4,445 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ByteFileGetterPagedMemory.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/io/experimental/ByteFileGetterPagedMemory.java | /*
* ByteFileGetterPagedMemory.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.io.experimental;
import jloda.util.Basic;
import megan.io.IByteGetter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* byte file getter using paged memory
* Daniel Huson, 5.2015
*/
public class ByteFileGetterPagedMemory implements IByteGetter {
private final File file;
private final RandomAccessFile raf;
private final byte[][] data;
private final long limit;
private final int length0;
private final int PAGE_BITS = 20; // 2^20=1048576
private int pages = 0;
/**
* constructor
*
*/
public ByteFileGetterPagedMemory(File file) throws IOException {
this.file = file;
limit = file.length();
System.err.println("Opening file: " + file);
raf = new RandomAccessFile(file, "r");
data = new byte[(int) ((limit >>> PAGE_BITS)) + 1][];
length0 = (int) (Math.min(limit, 1 << PAGE_BITS));
}
/**
* bulk get
*
*/
@Override
public int get(long index, byte[] bytes, int offset, int len) throws IOException {
synchronized (raf) {
raf.seek(index);
len = raf.read(bytes, offset, len);
}
return len;
}
/**
* gets value for given index
*
* @return value or 0
*/
@Override
public int get(long index) throws IOException {
int dIndex = dataIndex(index);
byte[] array = data[dIndex];
if (array == null) {
synchronized (raf) {
if (data[dIndex] == null) {
pages++;
final int length;
if (dIndex == data.length - 1)
length = (int) (limit - (data.length - 1) * length0); // is the last chunk
else
length = length0;
array = new byte[length];
long toSkip = (long) dIndex * (long) length0;
raf.seek(toSkip);
raf.read(array, 0, array.length);
data[dIndex] = array;
} else
array = data[dIndex];
}
}
return array[dataPos(index)];
}
/**
* gets next four bytes as a single integer
*
* @return integer
*/
@Override
public int getInt(long index) throws IOException {
return ((get(index++) & 0xFF) << 24) + ((get(index++) & 0xFF) << 16) + ((get(index++) & 0xFF) << 8) + ((get(index) & 0xFF));
}
/**
* length of array
*
* @return array length
*/
@Override
public long limit() {
return limit;
}
/**
* close the array
*/
@Override
public void close() {
try {
raf.close();
System.err.println("Closing file: " + file.getName() + " (" + pages + "/" + data.length + " pages)");
} catch (IOException e) {
Basic.caught(e);
}
}
private int dataIndex(long index) {
return (int) ((index >>> PAGE_BITS));
}
private int dataPos(long index) {
return (int) (index - (index >>> PAGE_BITS) * length0);
}
}
| 4,002 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CommandManagerFX.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/CommandManagerFX.java | /*
* CommandManagerFX.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.fx;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.director.IDirector;
import jloda.swing.util.ResourceManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.*;
/**
* manages commands in context of FX
* Daniel Huson, 2.2016
*/
public class CommandManagerFX extends CommandManager {
private final Map<MenuItem, ICommand> menuItem2CommandFX = new HashMap<>();
private final Map<javafx.scene.control.ButtonBase, ICommand> button2CommandFX = new HashMap<>();
private final static ActionEvent ACTION_EVENT_FROM_FX = new ActionEvent("CommandManagerWithFX", 0, null);
/**
* construct a parser
*
*/
public CommandManagerFX(IDirector dir, List<ICommand> commands) {
super(dir, commands);
}
/**
* construct a parser and load all commands found for the given path
*/
public CommandManagerFX(IDirector dir, IDirectableViewer viewer, String commandsPath) {
this(dir, viewer, new String[]{commandsPath}, false);
}
/**
* construct a parser and load all commands found for the given paths
*
* @param viewer usually an IDirectableViewer, but sometimes a JDialog
*/
public CommandManagerFX(IDirector dir, Object viewer, String[] commandsPaths) {
this(dir, viewer, commandsPaths, false);
}
/**
* construct a parser and load all commands found for the given path
*/
public CommandManagerFX(IDirector dir, IDirectableViewer viewer, String commandsPath, boolean returnOnCommandNotFound) {
this(dir, viewer, new String[]{commandsPath}, returnOnCommandNotFound);
}
/**
* construct a parser and load all commands found for the given paths
*
* @param viewer usually an IDirectableViewer, but sometimes a JDialog
*/
public CommandManagerFX(IDirector dir, Object viewer, String[] commandsPaths, boolean returnOnCommandNotFound) {
super(dir, viewer, commandsPaths, returnOnCommandNotFound);
}
/**
* update the enable state
*/
public void updateEnableState() {
if (SwingUtilities.isEventDispatchThread())
super.updateEnableState();
for (MenuItem menuItem : menuItem2CommandFX.keySet()) {
ICommand command = menuItem2CommandFX.get(menuItem);
menuItem.setDisable(!command.isApplicable());
if (command instanceof ICheckBoxCommand) {
((CheckMenuItem) menuItem).setSelected(((ICheckBoxCommand) command).isSelected());
}
}
}
/**
* update the enable state for only the FX menu items
*/
public void updateEnableStateFXItems() {
for (MenuItem menuItem : menuItem2CommandFX.keySet()) {
ICommand command = menuItem2CommandFX.get(menuItem);
menuItem.setDisable(!command.isApplicable());
if (command instanceof ICheckBoxCommand) {
((CheckMenuItem) menuItem).setSelected(((ICheckBoxCommand) command).isSelected());
}
}
}
/**
* update the enable state for only the Swing menu items
*/
public void updateEnableStateSwingItems() {
if (SwingUtilities.isEventDispatchThread())
super.updateEnableState();
}
/**
* update the enable state
*/
public void updateEnableState(String commandName) {
if (SwingUtilities.isEventDispatchThread())
super.updateEnableState(commandName);
for (MenuItem menuItem : menuItem2CommandFX.keySet()) {
ICommand command = menuItem2CommandFX.get(menuItem);
if (command.getName().equals(commandName)) {
menuItem.setDisable(!command.isApplicable());
if (command instanceof ICheckBoxCommand) {
((CheckMenuItem) menuItem).setSelected(((ICheckBoxCommand) command).isSelected());
}
}
}
}
/**
* get a menu item for the named command
*
* @return menu item
*/
public MenuItem getMenuItemFX(String commandName) {
ICommand command = getCommand(commandName);
MenuItem item = getMenuItemFX(command);
if (item != null && command != null)
item.setDisable(!command.isApplicable());
return item;
}
/**
* get a menu item for the named command
*
* @return menu item
*/
public MenuItem getMenuItemFX(String commandName, boolean enabled) {
ICommand command = getCommand(commandName);
MenuItem item = getMenuItemFX(command);
if (item != null)
item.setDisable(!enabled || !command.isApplicable());
return item;
}
/**
* creates a menu item for the given command
*
* @return menu item
*/
public MenuItem getMenuItemFX(final ICommand command) {
if (command == null) {
MenuItem nullItem = new MenuItem("Null");
nullItem.setDisable(true);
return nullItem;
}
if (command instanceof ICheckBoxCommand) {
final ICheckBoxCommand checkBoxCommand = (ICheckBoxCommand) command;
final CheckMenuItem menuItem = new CheckMenuItem(command.getName());
menuItem.setOnAction(event -> {
checkBoxCommand.setSelected(menuItem.isSelected());
if (command.getAutoRepeatInterval() > 0)
command.actionPerformedAutoRepeat(ACTION_EVENT_FROM_FX);
else
command.actionPerformed(ACTION_EVENT_FROM_FX);
});
if (command.getDescription() != null) {
menuItem.setUserData(command.getDescription());
}
if (command.getIcon() != null)
menuItem.setGraphic(asImageViewFX(command.getIcon()));
else
menuItem.setGraphic((asImageViewFX(Objects.requireNonNull(ResourceManager.getIcon("Empty16.gif")))));
if (command.getDescription() != null && menuItem.getGraphic() != null) {
Tooltip.install(menuItem.getGraphic(), new Tooltip(command.getDescription()));
}
if (command.getAcceleratorKey() != null)
menuItem.setAccelerator(translateAccelerator(command.getAcceleratorKey()));
menuItem.setSelected(checkBoxCommand.isSelected());
menuItem2CommandFX.put(menuItem, checkBoxCommand);
return menuItem;
} else {
final MenuItem menuItem = new MenuItem(command.getName());
menuItem.setOnAction(event -> SwingUtilities.invokeLater(() -> {
if (command.getAutoRepeatInterval() > 0)
command.actionPerformedAutoRepeat(ACTION_EVENT_FROM_FX);
else
command.actionPerformed(ACTION_EVENT_FROM_FX);
}));
if (command.getDescription() != null)
menuItem.setUserData(command.getDescription());
if (command.getIcon() != null)
menuItem.setGraphic(asImageViewFX(command.getIcon()));
else
menuItem.setGraphic((asImageViewFX(Objects.requireNonNull(ResourceManager.getIcon("Empty16.gif")))));
if (command.getDescription() != null && menuItem.getGraphic() != null) {
Tooltip.install(menuItem.getGraphic(), new Tooltip(command.getDescription()));
}
if (command.getAcceleratorKey() != null)
menuItem.setAccelerator(translateAccelerator(command.getAcceleratorKey()));
menuItem2CommandFX.put(menuItem, command);
return menuItem;
}
}
/**
* creates a button for the command
*
* @return button
*/
public javafx.scene.control.ButtonBase getButtonFX(String commandName) {
return getButtonFX(commandName, true);
}
private static boolean warned = false;
/**
* creates a button for the command
*
* @return button
*/
private javafx.scene.control.ButtonBase getButtonFX(String commandName, boolean enabled) {
javafx.scene.control.ButtonBase button = getButtonFX(getCommand(commandName));
button.setDisable(!enabled);
if (button.getText() != null && button.getText().equals("Null")) {
System.err.println("Failed to create button for command '" + commandName + "'");
if (!warned) {
warned = true;
System.err.println("Table of known commands:");
for (String name : name2Command.keySet()) {
System.err.print(" '" + name + "'");
}
System.err.println();
}
}
return button;
}
/**
* creates a button for the command
*
* @return button
*/
private javafx.scene.control.ButtonBase getButtonFX(final ICommand command) {
if (command == null) {
javafx.scene.control.Button nullButton = new javafx.scene.control.Button("Null");
nullButton.setDisable(true);
return nullButton;
}
if (command instanceof ICheckBoxCommand) {
final ICheckBoxCommand checkBoxCommand = (ICheckBoxCommand) command;
final CheckBox cbox = new CheckBox(command.getName());
cbox.setOnAction(event -> {
checkBoxCommand.setSelected(cbox.isSelected());
if (command.getAutoRepeatInterval() > 0)
command.actionPerformedAutoRepeat(ACTION_EVENT_FROM_FX);
else
command.actionPerformed(ACTION_EVENT_FROM_FX);
});
if (command.getDescription() != null) {
cbox.setUserData(command.getDescription());
Tooltip.install(cbox, new Tooltip(command.getDescription()));
}
if (command.getIcon() != null) {
cbox.setGraphic(asImageViewFX(command.getIcon()));
}
cbox.setSelected(checkBoxCommand.isSelected());
button2CommandFX.put(cbox, checkBoxCommand);
return cbox;
} else {
final Button button = new Button(command.getName());
button.setOnAction(event -> {
if (command.getAutoRepeatInterval() > 0)
command.actionPerformedAutoRepeat(ACTION_EVENT_FROM_FX);
else
command.actionPerformed(ACTION_EVENT_FROM_FX);
});
if (command.getDescription() != null) {
button.setUserData(command.getDescription());
Tooltip.install(button, new Tooltip(command.getDescription()));
}
if (command.getIcon() != null) {
button.setGraphic(asImageViewFX(command.getIcon()));
}
button2CommandFX.put(button, command);
return button;
}
}
/**
* creates a button for the command
*
* @return button
*/
public javafx.scene.control.RadioButton getRadioButtonFX(final ICommand command) {
if (command == null) {
RadioButton nullButton = new RadioButton("Null");
nullButton.setDisable(true);
return nullButton;
}
if (command instanceof ICheckBoxCommand) {
final ICheckBoxCommand checkBoxCommand = (ICheckBoxCommand) command;
final RadioButton button = new RadioButton(command.getName());
button.setOnAction(event -> {
checkBoxCommand.setSelected(button.isSelected());
if (command.getAutoRepeatInterval() > 0)
command.actionPerformedAutoRepeat(ACTION_EVENT_FROM_FX);
else
command.actionPerformed(ACTION_EVENT_FROM_FX);
});
if (command.getDescription() != null) {
button.setUserData(command.getDescription());
Tooltip.install(button, new Tooltip(command.getDescription()));
}
if (command.getIcon() != null) {
button.setGraphic(asImageViewFX(command.getIcon()));
}
button.setSelected(checkBoxCommand.isSelected());
button2CommandFX.put(button, checkBoxCommand);
return button;
} else
return null;
}
/**
* get the director
*
*/
public IDirector getDir() {
return dir;
}
/**
* convert AWT imageIcon to JavaFX image
*
* @return javaFX image
*/
public static ImageView asImageViewFX(ImageIcon imageIcon) {
java.awt.Image awtImage = imageIcon.getImage();
if (awtImage != null) {
final BufferedImage bImg;
if (awtImage instanceof BufferedImage) {
bImg = (BufferedImage) awtImage;
} else {
bImg = new BufferedImage(awtImage.getWidth(null), awtImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = bImg.createGraphics();
graphics.drawImage(awtImage, 0, 0, null);
graphics.dispose();
}
return new ImageView(SwingFXUtils.toFXImage(bImg, null));
} else
return null;
}
/**
* converts a swing accelerator key to a JavaFX key combination
*
* @return key combination
*/
private static KeyCombination translateAccelerator(KeyStroke acceleratorKey) {
final List<KeyCombination.Modifier> modifiers = new ArrayList<>();
if ((acceleratorKey.getModifiers() & java.awt.event.InputEvent.SHIFT_DOWN_MASK) != 0)
modifiers.add(KeyCombination.SHIFT_DOWN);
if ((acceleratorKey.getModifiers() & java.awt.event.InputEvent.CTRL_DOWN_MASK) != 0)
modifiers.add(KeyCombination.CONTROL_DOWN);
if ((acceleratorKey.getModifiers() & java.awt.event.InputEvent.ALT_DOWN_MASK) != 0)
modifiers.add(KeyCombination.ALT_DOWN);
if ((acceleratorKey.getModifiers() & InputEvent.META_DOWN_MASK) != 0)
modifiers.add(KeyCombination.META_DOWN);
KeyCode keyCode = KeyCodeUtils.convert(acceleratorKey.getKeyCode());
return new KeyCodeCombination(keyCode, modifiers.toArray(new KeyCombination.Modifier[0]));
}
}
| 15,688 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FXUtilities.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/FXUtilities.java | /*
* FXUtilities.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.fx;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.ScrollBar;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import jloda.util.Single;
import java.util.Set;
/**
* some helpful JavaFX stuff
* Created by huson on 2/18/17.
*/
public class FXUtilities {
/**
* bidirectionally bind scroll bars of two nodes
*
*/
public static void bidirectionallyBindScrollBars(final Node node1, final Node node2, Orientation orientation) {
final ScrollBar scrollBar1 = findScrollBar(node1, orientation);
final ScrollBar scrollBar2 = findScrollBar(node2, orientation);
if (scrollBar1 != null && scrollBar2 != null) {
final Single<Boolean> inChange = new Single<>(false);
scrollBar1.valueProperty().addListener(observable -> {
if (!inChange.get()) {
try {
inChange.set(true);
scrollBar2.setValue(scrollBar1.getValue() * (scrollBar2.getMax() - scrollBar2.getMin()) / (scrollBar1.getMax() - scrollBar1.getMin()));
} finally {
inChange.set(false);
}
}
});
scrollBar2.valueProperty().addListener(observable -> {
if (!inChange.get()) {
try {
inChange.set(true);
scrollBar1.setValue(scrollBar2.getValue() * (scrollBar1.getMax() - scrollBar1.getMin()) / (scrollBar2.getMax() - scrollBar2.getMin()));
} finally {
inChange.set(false);
}
}
});
}
}
/**
* Find the scrollbar of the given table.
*
*/
public static ScrollBar findScrollBar(Node node, Orientation orientation) {
Set<Node> below = node.lookupAll(".scroll-bar");
for (final Node nodeBelow : below) {
if (nodeBelow instanceof ScrollBar) {
ScrollBar sb = (ScrollBar) nodeBelow;
if (sb.getOrientation() == orientation) {
return sb;
}
}
}
return null;
}
/**
* changes opacity, if paint is a color
*
* @return paint
*/
public static Paint changeOpacity(Paint paint, double opacity) {
if (paint instanceof Color) {
Color color = (Color) paint;
return new Color(color.getRed(), color.getGreen(), color.getBlue(), opacity);
} else
return paint;
}
}
| 3,437 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SwingPanel4FX.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/SwingPanel4FX.java | /*
* SwingPanel4FX.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.fx;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import jloda.fx.util.ExtendedFXMLLoader;
import jloda.util.Basic;
import jloda.util.Single;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
* A JavaFX panel that can be used in swing and is setup from an fxml file
* Daniel Huson, 2.2017
*/
public class SwingPanel4FX<C> {
private final Class viewerClass;
private JFXPanel jFXPanel;
private final Single<Boolean> initialized = new Single<>(false);
private C controller;
private final List<Runnable> toRunLaterInSwing = new ArrayList<>();
private final ReentrantLock lock = new ReentrantLock();
/**
* constructor
*
* @param viewerClass there must exist a file with the same name and path with suffix .fxml
*/
public SwingPanel4FX(final Class viewerClass) {
this.viewerClass = viewerClass;
//System.err.println("SwingPanel4FX");
if (SwingUtilities.isEventDispatchThread())
initSwingLater();
else {
SwingUtilities.invokeLater(this::initSwingLater);
}
}
/**
* get the panel
*
* @return panel
*/
public JFXPanel getPanel() {
return jFXPanel;
}
/**
* initialize swing
*/
private void initSwingLater() {
// System.err.println("initSwingLater");
try {
jFXPanel = new JFXPanel();
Platform.runLater(this::initFxLater);
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* initialize JavaFX
*/
private void initFxLater() {
// System.err.println("initFxLater");
lock.lock();
try {
if (!initialized.get()) {
try {
final ExtendedFXMLLoader<C> extendedFXMLLoader = new ExtendedFXMLLoader<>(viewerClass);
controller = extendedFXMLLoader.getController();
jFXPanel.setScene(new Scene(extendedFXMLLoader.getRoot()));
} catch (Exception ex) {
Basic.caught(ex);
} finally {
initialized.set(true);
//System.err.println("running to run later");
for (Runnable runnable : toRunLaterInSwing) {
SwingUtilities.invokeLater(runnable);
}
}
}
} finally {
lock.unlock();
}
}
/**
* schedule to be run in swing thread once initialization is complete
*
*/
public void runLaterInSwing(Runnable runnable) {
lock.lock();
try {
if (!initialized.get()) {
//System.err.println("setting to run later");
toRunLaterInSwing.add(runnable);
} else
SwingUtilities.invokeLater(runnable);
} finally {
lock.unlock();
}
}
/**
* gets the controller
*
* @return controller
*/
public C getController() {
return controller;
}
}
| 4,019 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Dialogs.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/Dialogs.java | /*
* Dialogs.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.fx;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextInputDialog;
import jloda.util.Basic;
import jloda.util.Single;
import javax.swing.*;
import java.awt.*;
import java.util.Optional;
/**
* shows a confirmation dialog in either swing thread or fx thread
*/
public class Dialogs {
/**
* show a confirmation dialog
*
*/
public static boolean showConfirmation(final Component swingParent, final String title, final String message) {
final Single<Boolean> confirmed = new Single<>(false);
if (Platform.isFxApplicationThread()) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(title);
alert.setContentText(message);
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && (result.get() == ButtonType.OK))
confirmed.set(true);
} else if (javax.swing.SwingUtilities.isEventDispatchThread()) {
int result = JOptionPane.showConfirmDialog(swingParent, message);
if (result == JOptionPane.YES_OPTION)
confirmed.set(true);
} else {
try {
SwingUtilities.invokeAndWait(() -> confirmed.set(showConfirmation(swingParent, title, message)));
} catch (Exception e) {
Basic.caught(e);
}
}
return confirmed.get();
}
/**
* show an input dialog
*
*/
private static String showInput(final Component swingParent, final String title, final String message, final String initialValue) {
final Single<String> input = new Single<>(null);
if (Platform.isFxApplicationThread()) {
final TextInputDialog dialog = new TextInputDialog(initialValue != null ? initialValue : "");
dialog.setTitle(title);
dialog.setHeaderText(message);
final Optional<String> result = dialog.showAndWait();
result.ifPresent(input::set);
} else if (javax.swing.SwingUtilities.isEventDispatchThread()) {
input.set(JOptionPane.showInputDialog(swingParent, message, initialValue));
} else {
try {
SwingUtilities.invokeAndWait(() -> input.set(showInput(swingParent, title, message, initialValue)));
} catch (Exception e) {
Basic.caught(e);
}
}
return input.get();
}
}
| 3,345 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PopupMenuFX.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/PopupMenuFX.java | /*
* PopupMenuFX.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.fx;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICommand;
import jloda.swing.commands.TeXGenerator;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import java.util.Objects;
/**
* popup menu
* Daniel Huson, 11.2010
*/
public class PopupMenuFX extends ContextMenu {
/**
* constructor
*
*/
public PopupMenuFX(String configuration, CommandManagerFX commandManager) {
this(configuration, commandManager, false);
}
/**
* constructor
*
*/
public PopupMenuFX(String configuration, CommandManagerFX commandManager, boolean showApplicableOnly) {
super();
if (configuration != null && configuration.length() > 0) {
String[] tokens = configuration.split(";");
for (String token : tokens) {
if (token.equals("|")) {
getItems().add(new SeparatorMenuItem());
} else {
MenuItem menuItem;
ICommand command = commandManager.getCommand(token);
if (command == null) {
if (showApplicableOnly)
continue;
menuItem = new MenuItem(token + "#");
menuItem.setDisable(true);
getItems().add(menuItem);
} else {
if (CommandManager.getCommandsToIgnore().contains(command.getName()))
continue;
if (showApplicableOnly && !command.isApplicable())
continue;
menuItem = commandManager.getMenuItemFX(command);
menuItem.setAccelerator(null);
getItems().add(menuItem);
}
if (menuItem.getGraphic() == null)
menuItem.setGraphic(CommandManagerFX.asImageViewFX(Objects.requireNonNull(ResourceManager.getIcon("Empty16.gif"))));
}
}
}
if (ProgramProperties.get("showtex", false)) {
System.out.println(TeXGenerator.getPopupMenuLaTeX(configuration, commandManager));
}
try {
commandManager.updateEnableState();
} catch (Exception ignored) {
}
}
}
| 3,312 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
KeyCodeUtils.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/KeyCodeUtils.java | /*
* KeyCodeUtils.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.fx;
import javafx.scene.input.KeyCode;
/**
* utility to convert AWT key codes into Swing key codes
*/
public class KeyCodeUtils {
/**
* convert awt key code to KeyCode
*
* @return KeyCode
*/
public static KeyCode convert(int awtKeyCode) {
return switch (awtKeyCode) {
case java.awt.event.KeyEvent.VK_A -> KeyCode.A;
case java.awt.event.KeyEvent.VK_ACCEPT -> KeyCode.ACCEPT;
case java.awt.event.KeyEvent.VK_ADD -> KeyCode.ADD;
case java.awt.event.KeyEvent.VK_AGAIN -> KeyCode.AGAIN;
case java.awt.event.KeyEvent.VK_ALL_CANDIDATES -> KeyCode.ALL_CANDIDATES;
case java.awt.event.KeyEvent.VK_ALPHANUMERIC -> KeyCode.ALPHANUMERIC;
case java.awt.event.KeyEvent.VK_ALT -> KeyCode.ALT;
case java.awt.event.KeyEvent.VK_ALT_GRAPH -> KeyCode.ALT_GRAPH;
case java.awt.event.KeyEvent.VK_AMPERSAND -> KeyCode.AMPERSAND;
case java.awt.event.KeyEvent.VK_ASTERISK -> KeyCode.ASTERISK;
case java.awt.event.KeyEvent.VK_AT -> KeyCode.AT;
case java.awt.event.KeyEvent.VK_B -> KeyCode.B;
case java.awt.event.KeyEvent.VK_BACK_QUOTE -> KeyCode.BACK_QUOTE;
case java.awt.event.KeyEvent.VK_BACK_SLASH -> KeyCode.BACK_SLASH;
case java.awt.event.KeyEvent.VK_BACK_SPACE -> KeyCode.BACK_SPACE;
case java.awt.event.KeyEvent.VK_BEGIN -> KeyCode.BEGIN;
case java.awt.event.KeyEvent.VK_BRACELEFT -> KeyCode.BRACELEFT;
case java.awt.event.KeyEvent.VK_BRACERIGHT -> KeyCode.BRACERIGHT;
case java.awt.event.KeyEvent.VK_C -> KeyCode.C;
case java.awt.event.KeyEvent.VK_CANCEL -> KeyCode.CANCEL;
case java.awt.event.KeyEvent.VK_CAPS_LOCK -> KeyCode.CAPS;
case java.awt.event.KeyEvent.VK_CIRCUMFLEX -> KeyCode.CIRCUMFLEX;
case java.awt.event.KeyEvent.VK_CLEAR -> KeyCode.CLEAR;
case java.awt.event.KeyEvent.VK_CLOSE_BRACKET -> KeyCode.CLOSE_BRACKET;
case java.awt.event.KeyEvent.VK_CODE_INPUT -> KeyCode.CODE_INPUT;
case java.awt.event.KeyEvent.VK_COLON -> KeyCode.COLON;
case java.awt.event.KeyEvent.VK_COMMA -> KeyCode.COMMA;
case java.awt.event.KeyEvent.VK_COMPOSE -> KeyCode.COMPOSE;
case java.awt.event.KeyEvent.VK_CONTEXT_MENU -> KeyCode.CONTEXT_MENU;
case java.awt.event.KeyEvent.VK_CONTROL -> KeyCode.CONTROL;
case java.awt.event.KeyEvent.VK_CONVERT -> KeyCode.CONVERT;
case java.awt.event.KeyEvent.VK_COPY -> KeyCode.COPY;
case java.awt.event.KeyEvent.VK_CUT -> KeyCode.CUT;
case java.awt.event.KeyEvent.VK_D -> KeyCode.D;
case java.awt.event.KeyEvent.VK_DEAD_ABOVEDOT -> KeyCode.DEAD_ABOVEDOT;
case java.awt.event.KeyEvent.VK_DEAD_ABOVERING -> KeyCode.DEAD_ABOVERING;
case java.awt.event.KeyEvent.VK_DEAD_ACUTE -> KeyCode.DEAD_ACUTE;
case java.awt.event.KeyEvent.VK_DEAD_BREVE -> KeyCode.DEAD_BREVE;
case java.awt.event.KeyEvent.VK_DEAD_CARON -> KeyCode.DEAD_CARON;
case java.awt.event.KeyEvent.VK_DEAD_CEDILLA -> KeyCode.DEAD_CEDILLA;
case java.awt.event.KeyEvent.VK_DEAD_CIRCUMFLEX -> KeyCode.DEAD_CIRCUMFLEX;
case java.awt.event.KeyEvent.VK_DEAD_DIAERESIS -> KeyCode.DEAD_DIAERESIS;
case java.awt.event.KeyEvent.VK_DEAD_DOUBLEACUTE -> KeyCode.DEAD_DOUBLEACUTE;
case java.awt.event.KeyEvent.VK_DEAD_GRAVE -> KeyCode.DEAD_GRAVE;
case java.awt.event.KeyEvent.VK_DEAD_IOTA -> KeyCode.DEAD_IOTA;
case java.awt.event.KeyEvent.VK_DEAD_MACRON -> KeyCode.DEAD_MACRON;
case java.awt.event.KeyEvent.VK_DEAD_OGONEK -> KeyCode.DEAD_OGONEK;
case java.awt.event.KeyEvent.VK_DEAD_SEMIVOICED_SOUND -> KeyCode.DEAD_SEMIVOICED_SOUND;
case java.awt.event.KeyEvent.VK_DEAD_TILDE -> KeyCode.DEAD_TILDE;
case java.awt.event.KeyEvent.VK_DEAD_VOICED_SOUND -> KeyCode.DEAD_VOICED_SOUND;
case java.awt.event.KeyEvent.VK_DECIMAL -> KeyCode.DECIMAL;
case java.awt.event.KeyEvent.VK_DELETE -> KeyCode.DELETE;
case java.awt.event.KeyEvent.VK_0 -> KeyCode.DIGIT0;
case java.awt.event.KeyEvent.VK_1 -> KeyCode.DIGIT1;
case java.awt.event.KeyEvent.VK_2 -> KeyCode.DIGIT2;
case java.awt.event.KeyEvent.VK_3 -> KeyCode.DIGIT3;
case java.awt.event.KeyEvent.VK_4 -> KeyCode.DIGIT4;
case java.awt.event.KeyEvent.VK_5 -> KeyCode.DIGIT5;
case java.awt.event.KeyEvent.VK_6 -> KeyCode.DIGIT6;
case java.awt.event.KeyEvent.VK_7 -> KeyCode.DIGIT7;
case java.awt.event.KeyEvent.VK_8 -> KeyCode.DIGIT8;
case java.awt.event.KeyEvent.VK_9 -> KeyCode.DIGIT9;
case java.awt.event.KeyEvent.VK_DIVIDE -> KeyCode.DIVIDE;
case java.awt.event.KeyEvent.VK_DOLLAR -> KeyCode.DOLLAR;
case java.awt.event.KeyEvent.VK_DOWN -> KeyCode.DOWN;
case java.awt.event.KeyEvent.VK_E -> KeyCode.E;
case java.awt.event.KeyEvent.VK_END -> KeyCode.END;
case java.awt.event.KeyEvent.VK_ENTER -> KeyCode.ENTER;
case java.awt.event.KeyEvent.VK_EQUALS -> KeyCode.EQUALS;
case java.awt.event.KeyEvent.VK_ESCAPE -> KeyCode.ESCAPE;
case java.awt.event.KeyEvent.VK_EURO_SIGN -> KeyCode.EURO_SIGN;
case java.awt.event.KeyEvent.VK_EXCLAMATION_MARK -> KeyCode.EXCLAMATION_MARK;
case java.awt.event.KeyEvent.VK_F -> KeyCode.F;
case java.awt.event.KeyEvent.VK_F1 -> KeyCode.F1;
case java.awt.event.KeyEvent.VK_F10 -> KeyCode.F10;
case java.awt.event.KeyEvent.VK_F11 -> KeyCode.F11;
case java.awt.event.KeyEvent.VK_F12 -> KeyCode.F12;
case java.awt.event.KeyEvent.VK_F13 -> KeyCode.F13;
case java.awt.event.KeyEvent.VK_F14 -> KeyCode.F14;
case java.awt.event.KeyEvent.VK_F15 -> KeyCode.F15;
case java.awt.event.KeyEvent.VK_F16 -> KeyCode.F16;
case java.awt.event.KeyEvent.VK_F17 -> KeyCode.F17;
case java.awt.event.KeyEvent.VK_F18 -> KeyCode.F18;
case java.awt.event.KeyEvent.VK_F19 -> KeyCode.F19;
case java.awt.event.KeyEvent.VK_F2 -> KeyCode.F2;
case java.awt.event.KeyEvent.VK_F20 -> KeyCode.F20;
case java.awt.event.KeyEvent.VK_F21 -> KeyCode.F21;
case java.awt.event.KeyEvent.VK_F22 -> KeyCode.F22;
case java.awt.event.KeyEvent.VK_F23 -> KeyCode.F23;
case java.awt.event.KeyEvent.VK_F24 -> KeyCode.F24;
case java.awt.event.KeyEvent.VK_F3 -> KeyCode.F3;
case java.awt.event.KeyEvent.VK_F4 -> KeyCode.F4;
case java.awt.event.KeyEvent.VK_F5 -> KeyCode.F5;
case java.awt.event.KeyEvent.VK_F6 -> KeyCode.F6;
case java.awt.event.KeyEvent.VK_F7 -> KeyCode.F7;
case java.awt.event.KeyEvent.VK_F8 -> KeyCode.F8;
case java.awt.event.KeyEvent.VK_F9 -> KeyCode.F9;
case java.awt.event.KeyEvent.VK_FINAL -> KeyCode.FINAL;
case java.awt.event.KeyEvent.VK_FIND -> KeyCode.FIND;
case java.awt.event.KeyEvent.VK_FULL_WIDTH -> KeyCode.FULL_WIDTH;
case java.awt.event.KeyEvent.VK_G -> KeyCode.G;
case java.awt.event.KeyEvent.VK_GREATER -> KeyCode.GREATER;
case java.awt.event.KeyEvent.VK_H -> KeyCode.H;
case java.awt.event.KeyEvent.VK_HALF_WIDTH -> KeyCode.HALF_WIDTH;
case java.awt.event.KeyEvent.VK_HELP -> KeyCode.HELP;
case java.awt.event.KeyEvent.VK_HIRAGANA -> KeyCode.HIRAGANA;
case java.awt.event.KeyEvent.VK_HOME -> KeyCode.HOME;
case java.awt.event.KeyEvent.VK_I -> KeyCode.I;
case java.awt.event.KeyEvent.VK_INPUT_METHOD_ON_OFF -> KeyCode.INPUT_METHOD_ON_OFF;
case java.awt.event.KeyEvent.VK_INSERT -> KeyCode.INSERT;
case java.awt.event.KeyEvent.VK_J -> KeyCode.J;
case java.awt.event.KeyEvent.VK_JAPANESE_HIRAGANA -> KeyCode.JAPANESE_HIRAGANA;
case java.awt.event.KeyEvent.VK_JAPANESE_KATAKANA -> KeyCode.JAPANESE_KATAKANA;
case java.awt.event.KeyEvent.VK_JAPANESE_ROMAN -> KeyCode.JAPANESE_ROMAN;
case java.awt.event.KeyEvent.VK_K -> KeyCode.K;
case java.awt.event.KeyEvent.VK_KANA -> KeyCode.KANA;
case java.awt.event.KeyEvent.VK_KANA_LOCK -> KeyCode.KANA_LOCK;
case java.awt.event.KeyEvent.VK_KANJI -> KeyCode.KANJI;
case java.awt.event.KeyEvent.VK_KATAKANA -> KeyCode.KATAKANA;
case java.awt.event.KeyEvent.VK_KP_DOWN -> KeyCode.KP_DOWN;
case java.awt.event.KeyEvent.VK_KP_LEFT -> KeyCode.KP_LEFT;
case java.awt.event.KeyEvent.VK_KP_RIGHT -> KeyCode.KP_RIGHT;
case java.awt.event.KeyEvent.VK_KP_UP -> KeyCode.KP_UP;
case java.awt.event.KeyEvent.VK_L -> KeyCode.L;
case java.awt.event.KeyEvent.VK_LEFT -> KeyCode.LEFT;
case java.awt.event.KeyEvent.VK_LEFT_PARENTHESIS -> KeyCode.LEFT_PARENTHESIS;
case java.awt.event.KeyEvent.VK_LESS -> KeyCode.LESS;
case java.awt.event.KeyEvent.VK_M -> KeyCode.M;
case java.awt.event.KeyEvent.VK_META -> KeyCode.META;
case java.awt.event.KeyEvent.VK_MINUS -> KeyCode.MINUS;
case java.awt.event.KeyEvent.VK_MODECHANGE -> KeyCode.MODECHANGE;
case java.awt.event.KeyEvent.VK_MULTIPLY -> KeyCode.MULTIPLY;
case java.awt.event.KeyEvent.VK_N -> KeyCode.N;
case java.awt.event.KeyEvent.VK_NONCONVERT -> KeyCode.NONCONVERT;
case java.awt.event.KeyEvent.VK_NUMBER_SIGN -> KeyCode.NUMBER_SIGN;
case java.awt.event.KeyEvent.VK_NUMPAD0 -> KeyCode.NUMPAD0;
case java.awt.event.KeyEvent.VK_NUMPAD1 -> KeyCode.NUMPAD1;
case java.awt.event.KeyEvent.VK_NUMPAD2 -> KeyCode.NUMPAD2;
case java.awt.event.KeyEvent.VK_NUMPAD3 -> KeyCode.NUMPAD3;
case java.awt.event.KeyEvent.VK_NUMPAD4 -> KeyCode.NUMPAD4;
case java.awt.event.KeyEvent.VK_NUMPAD5 -> KeyCode.NUMPAD5;
case java.awt.event.KeyEvent.VK_NUMPAD6 -> KeyCode.NUMPAD6;
case java.awt.event.KeyEvent.VK_NUMPAD7 -> KeyCode.NUMPAD7;
case java.awt.event.KeyEvent.VK_NUMPAD8 -> KeyCode.NUMPAD8;
case java.awt.event.KeyEvent.VK_NUMPAD9 -> KeyCode.NUMPAD9;
case java.awt.event.KeyEvent.VK_NUM_LOCK -> KeyCode.NUM_LOCK;
case java.awt.event.KeyEvent.VK_O -> KeyCode.O;
case java.awt.event.KeyEvent.VK_OPEN_BRACKET -> KeyCode.OPEN_BRACKET;
case java.awt.event.KeyEvent.VK_P -> KeyCode.P;
case java.awt.event.KeyEvent.VK_PAGE_DOWN -> KeyCode.PAGE_DOWN;
case java.awt.event.KeyEvent.VK_PAGE_UP -> KeyCode.PAGE_UP;
case java.awt.event.KeyEvent.VK_PASTE -> KeyCode.PASTE;
case java.awt.event.KeyEvent.VK_PAUSE -> KeyCode.PAUSE;
case java.awt.event.KeyEvent.VK_PERIOD -> KeyCode.PERIOD;
case java.awt.event.KeyEvent.VK_PLUS -> KeyCode.PLUS;
case java.awt.event.KeyEvent.VK_PREVIOUS_CANDIDATE -> KeyCode.PREVIOUS_CANDIDATE;
case java.awt.event.KeyEvent.VK_PRINTSCREEN -> KeyCode.PRINTSCREEN;
case java.awt.event.KeyEvent.VK_PROPS -> KeyCode.PROPS;
case java.awt.event.KeyEvent.VK_Q -> KeyCode.Q;
case java.awt.event.KeyEvent.VK_QUOTE -> KeyCode.QUOTE;
case java.awt.event.KeyEvent.VK_QUOTEDBL -> KeyCode.QUOTEDBL;
case java.awt.event.KeyEvent.VK_R -> KeyCode.R;
case java.awt.event.KeyEvent.VK_RIGHT -> KeyCode.RIGHT;
case java.awt.event.KeyEvent.VK_RIGHT_PARENTHESIS -> KeyCode.RIGHT_PARENTHESIS;
case java.awt.event.KeyEvent.VK_ROMAN_CHARACTERS -> KeyCode.ROMAN_CHARACTERS;
case java.awt.event.KeyEvent.VK_S -> KeyCode.S;
case java.awt.event.KeyEvent.VK_SCROLL_LOCK -> KeyCode.SCROLL_LOCK;
case java.awt.event.KeyEvent.VK_SEMICOLON -> KeyCode.SEMICOLON;
case java.awt.event.KeyEvent.VK_SEPARATOR -> KeyCode.SEPARATOR;
case java.awt.event.KeyEvent.VK_SHIFT -> KeyCode.SHIFT;
case java.awt.event.KeyEvent.VK_SLASH -> KeyCode.SLASH;
case java.awt.event.KeyEvent.VK_STOP -> KeyCode.STOP;
case java.awt.event.KeyEvent.VK_SUBTRACT -> KeyCode.SUBTRACT;
case java.awt.event.KeyEvent.VK_T -> KeyCode.T;
case java.awt.event.KeyEvent.VK_TAB -> KeyCode.TAB;
case java.awt.event.KeyEvent.VK_U -> KeyCode.U;
case java.awt.event.KeyEvent.VK_UNDERSCORE -> KeyCode.UNDERSCORE;
case java.awt.event.KeyEvent.VK_UNDO -> KeyCode.UNDO;
case java.awt.event.KeyEvent.VK_UP -> KeyCode.UP;
case java.awt.event.KeyEvent.VK_V -> KeyCode.V;
case java.awt.event.KeyEvent.VK_W -> KeyCode.W;
case java.awt.event.KeyEvent.VK_WINDOWS -> KeyCode.WINDOWS;
case java.awt.event.KeyEvent.VK_X -> KeyCode.X;
case java.awt.event.KeyEvent.VK_Y -> KeyCode.Y;
case java.awt.event.KeyEvent.VK_Z -> KeyCode.Z;
default -> KeyCode.UNDEFINED;
};
}
}
| 14,251 | 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/fx/dialogs/decontam/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.fx.dialogs.decontam;
import jloda.swing.window.MenuConfiguration;
import megan.chart.data.ChartCommandHelper;
import megan.classification.data.ClassificationCommandHelper;
/**
* configuration for menu and toolbar
* Daniel Huson, 2.2017
*/
class GUIConfiguration {
/**
* get the menu configuration
*
* @return menu configuration
*/
public static MenuConfiguration getMenuConfiguration() {
MenuConfiguration menuConfig = new MenuConfiguration();
menuConfig.defineMenuBar("File;Edit;Attributes;Samples;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;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;|;Colors...;");
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...;|;Colors...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;";
}
}
| 2,731 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ControlBindings.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/dialogs/decontam/ControlBindings.java | /*
* ControlBindings.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.fx.dialogs.decontam;
import jloda.swing.util.ToolBar;
public class ControlBindings {
public static void setup(final DecontamDialogController controller, final DecontamDialog viewer, ToolBar toolBar) {
controller.getCloseButton().setOnAction(e -> viewer.getDir().execute("close;", viewer.getCommandManager()));
}
/**
* update the scene
*
*/
public static void updateScene(final DecontamDialogController controller, DecontamDialog viewer) {
}
}
| 1,314 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DecontamDialogController.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/dialogs/decontam/DecontamDialogController.java | /*
* DecontamDialogController.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.fx.dialogs.decontam;
import javafx.fxml.FXML;
import javafx.scene.chart.ScatterChart;
import javafx.scene.control.*;
import java.net.URL;
import java.util.ResourceBundle;
public class DecontamDialogController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Tab setupTab;
@FXML
private ChoiceBox<String> taxonomicRankCBox;
@FXML
private CheckBox projectCheckBox;
@FXML
private RadioButton frequencyMethodRadioButton;
@FXML
private ChoiceBox<String> concentrationAttributeCBox;
@FXML
private RadioButton prevelanceMethodRadioButton;
@FXML
private ChoiceBox<String> negativeControlCBox;
@FXML
private TextField negativeControlTextField;
@FXML
private RadioButton combinedRadioButton;
@FXML
private RadioButton minimumRadioButton;
@FXML
private RadioButton eitherRadioButton;
@FXML
private RadioButton bothRadioButton;
@FXML
private CheckBox batchesCheckBox;
@FXML
private ChoiceBox<String> batchesCBox;
@FXML
private ChoiceBox<?> batchedCombineCBox;
@FXML
private TextField thresholdTextField;
@FXML
private Tab frequencyTab;
@FXML
private ChoiceBox<String> frequencyPlotTaxonCBox;
@FXML
private ScatterChart<Double, Double> frequencyScatterPlot;
@FXML
private Button addFrequencyTabButton;
@FXML
private Tab prevalenceTab;
@FXML
private ChoiceBox<String> prevalencePlotTaxonCBox;
@FXML
private ScatterChart<Double, Double> prevalenceScatterPlot;
@FXML
private Button addPrevalenceTabButton;
@FXML
private Tab saveTab;
@FXML
private CheckBox saveToFileCheckBox;
@FXML
private TextField outputFileTextField;
@FXML
private Button outputFileBrowseButton;
@FXML
private CheckBox saveReportCheckBox;
@FXML
private TextField reportFileTextField;
@FXML
private Button reportFileBrowseButton;
@FXML
private CheckBox previewCheckBox;
@FXML
private Button closeButton;
@FXML
private Button saveButton;
@FXML
private Button applyButton;
@FXML
void initialize() {
System.err.println("INIT!");
}
public Tab getSetupTab() {
return setupTab;
}
public ChoiceBox<String> getTaxonomicRankCBox() {
return taxonomicRankCBox;
}
public CheckBox getProjectCheckBox() {
return projectCheckBox;
}
public RadioButton getFrequencyMethodRadioButton() {
return frequencyMethodRadioButton;
}
public ChoiceBox<String> getConcentrationAttributeCBox() {
return concentrationAttributeCBox;
}
public RadioButton getPrevelanceMethodRadioButton() {
return prevelanceMethodRadioButton;
}
public ChoiceBox<String> getNegativeControlCBox() {
return negativeControlCBox;
}
public TextField getNegativeControlTextField() {
return negativeControlTextField;
}
public RadioButton getCombinedRadioButton() {
return combinedRadioButton;
}
public RadioButton getMinimumRadioButton() {
return minimumRadioButton;
}
public RadioButton getEitherRadioButton() {
return eitherRadioButton;
}
public RadioButton getBothRadioButton() {
return bothRadioButton;
}
public CheckBox getBatchesCheckBox() {
return batchesCheckBox;
}
public ChoiceBox<String> getBatchesCBox() {
return batchesCBox;
}
public ChoiceBox<?> getBatchedCombineCBox() {
return batchedCombineCBox;
}
public TextField getThresholdTextField() {
return thresholdTextField;
}
public Tab getFrequencyTab() {
return frequencyTab;
}
public ChoiceBox<String> getFrequencyPlotTaxonCBox() {
return frequencyPlotTaxonCBox;
}
public ScatterChart<Double, Double> getFrequencyScatterPlot() {
return frequencyScatterPlot;
}
public Button getAddFrequencyTabButton() {
return addFrequencyTabButton;
}
public Tab getPrevalenceTab() {
return prevalenceTab;
}
public ChoiceBox<String> getPrevalencePlotTaxonCBox() {
return prevalencePlotTaxonCBox;
}
public ScatterChart<Double, Double> getPrevalenceScatterPlot() {
return prevalenceScatterPlot;
}
public Button getAddPrevalenceTabButton() {
return addPrevalenceTabButton;
}
public Tab getSaveTab() {
return saveTab;
}
public CheckBox getSaveToFileCheckBox() {
return saveToFileCheckBox;
}
public TextField getOutputFileTextField() {
return outputFileTextField;
}
public Button getOutputFileBrowseButton() {
return outputFileBrowseButton;
}
public CheckBox getSaveReportCheckBox() {
return saveReportCheckBox;
}
public TextField getReportFileTextField() {
return reportFileTextField;
}
public Button getReportFileBrowseButton() {
return reportFileBrowseButton;
}
public CheckBox getPreviewCheckBox() {
return previewCheckBox;
}
public Button getCloseButton() {
return closeButton;
}
public Button getSaveButton() {
return saveButton;
}
public Button getApplyButton() {
return applyButton;
}
}
| 6,255 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DecontamDialog.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/fx/dialogs/decontam/DecontamDialog.java | /*
* DecontamDialog.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.fx.dialogs.decontam;
import javafx.application.Platform;
import jloda.swing.commands.CommandManager;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.director.IViewerWithFindToolBar;
import jloda.swing.director.ProjectManager;
import jloda.swing.find.CompositeObjectSearcher;
import jloda.swing.find.FindToolBar;
import jloda.swing.find.SearchManager;
import jloda.swing.util.IViewerWithJComponent;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ToolBar;
import jloda.swing.window.MenuBar;
import megan.core.Director;
import megan.dialogs.input.InputDialog;
import megan.fx.SwingPanel4FX;
import megan.main.MeganProperties;
import megan.samplesviewer.commands.PasteCommand;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class DecontamDialog extends JFrame implements IDirectableViewer, IViewerWithJComponent, IViewerWithFindToolBar {
private final Director dir;
private boolean uptoDate = true;
private boolean locked = false;
private final MenuBar menuBar;
private final CommandManager commandManager;
private final JPanel mainPanel;
private final ToolBar toolBar;
private final SwingPanel4FX<DecontamDialogController> swingPanel4FX;
private boolean showFindToolBar = false;
private final SearchManager searchManager;
private final CompositeObjectSearcher searcher;
private final JFrame frame;
private Runnable runOnDestroy;
/**
* constructor
*
*/
public DecontamDialog(JFrame parent, final Director dir) {
this.dir = dir;
this.frame = this;
commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan6u.dialogs.parallelcoords.commands"}, !ProgramProperties.isUseGUI());
setTitle();
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setIconImages(ProgramProperties.getProgramIconImages());
menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), commandManager);
setJMenuBar(menuBar);
MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu());
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel);
toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager);
frame.add(toolBar, BorderLayout.NORTH);
searcher = new CompositeObjectSearcher("Columns", frame);
searchManager = new SearchManager(dir, this, searcher, false, true);
searchManager.getFindDialogAsToolBar().setEnabled(false);
commandManager.updateEnableState();
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, DecontamDialog.this);
}
}
});
frame.setLocationRelativeTo(parent);
setSize(650, 450);
frame.setVisible(true);
commandManager.updateEnableState();
swingPanel4FX = new SwingPanel4FX<>(this.getClass());
swingPanel4FX.runLaterInSwing(() -> {
mainPanel.add(swingPanel4FX.getPanel(), BorderLayout.CENTER); // add panel once initialization complete
mainPanel.validate();
Platform.runLater(() -> ControlBindings.setup(swingPanel4FX.getController(), DecontamDialog.this, toolBar));
Platform.runLater(() -> ControlBindings.updateScene(swingPanel4FX.getController(), DecontamDialog.this));
});
}
public boolean isUptoDate() {
return uptoDate;
}
public JFrame getFrame() {
return frame;
}
public void updateView(String what) {
uptoDate = false;
setTitle();
FindToolBar findToolBar = searchManager.getFindDialogAsToolBar();
if (findToolBar.isClosing()) {
showFindToolBar = false;
findToolBar.setClosing(false);
}
if (!findToolBar.isEnabled() && showFindToolBar) {
mainPanel.add(findToolBar, BorderLayout.NORTH);
findToolBar.setEnabled(true);
frame.getContentPane().validate();
getCommandManager().updateEnableState();
} else if (findToolBar.isEnabled() && !showFindToolBar) {
mainPanel.remove(findToolBar);
findToolBar.setEnabled(false);
frame.getContentPane().validate();
getCommandManager().updateEnableState();
}
if (findToolBar.isEnabled())
findToolBar.clearMessage();
uptoDate = true;
}
public void lockUserInput() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
searchManager.getFindDialogAsToolBar().setEnableCritical(false);
locked = true;
commandManager.setEnableCritical(false);
menuBar.setEnableRecentFileMenuItems(false);
}
public void unlockUserInput() {
setCursor(Cursor.getDefaultCursor());
searchManager.getFindDialogAsToolBar().setEnableCritical(true);
commandManager.setEnableCritical(true);
menuBar.setEnableRecentFileMenuItems(true);
locked = false;
}
/**
* is viewer currently locked?
*
* @return true, if locked
*/
public boolean isLocked() {
return locked;
}
public void destroyView() {
if (runOnDestroy != null)
runOnDestroy.run();
MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener());
dir.removeViewer(this);
searchManager.getFindDialogAsToolBar().close();
dispose();
}
public void setUptoDate(boolean flag) {
uptoDate = flag;
}
/**
* set the title of the window
*/
private void setTitle() {
String newTitle = "Decontam - " + dir.getDocument().getTitle();
/*
if (dir.getDocument().isDirty())
newTitle += "*";
*/
if (dir.getID() == 1)
newTitle += " - " + ProgramProperties.getProgramVersion();
else
newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion();
if (!frame.getTitle().equals(newTitle)) {
frame.setTitle(newTitle);
ProjectManager.updateWindowMenus();
}
}
public CommandManager getCommandManager() {
return commandManager;
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "DecontamDialog";
}
public Director getDir() {
return dir;
}
@Override
public boolean isShowFindToolBar() {
return showFindToolBar;
}
@Override
public void setShowFindToolBar(boolean show) {
this.showFindToolBar = show;
}
@Override
public SearchManager getSearchManager() {
return searchManager;
}
@Override
public JComponent getComponent() {
return swingPanel4FX.getPanel();
}
public SwingPanel4FX<DecontamDialogController> getSwingPanel4FX() {
return swingPanel4FX;
}
}
| 8,524 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CDS.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/genes/CDS.java | /*
* CDS.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.genes;
import jloda.util.CanceledException;
import jloda.util.FileLineIterator;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.progress.ProgressListener;
import jloda.util.progress.ProgressPercentage;
import megan.classification.util.TaggedValueIterator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* simple CDS annotation of a segment of DNA
* Daniel Huson, 12.2017
*/
public class CDS {
private String dnaId;
private int start;
private int end;
private boolean reverse;
private String proteinId;
private static final String[] tags = {"protein_id=", "name=", "sequence:RefSeq:"};
/**
* constructor
*/
public CDS() {
}
private void setDnaId(String dnaId) {
this.dnaId = dnaId;
}
private void setStart(int start) {
this.start = start;
}
private void setEnd(int end) {
this.end = end;
}
private void setReverse(boolean reverse) {
this.reverse = reverse;
}
private void setProteinId(String proteinId) {
this.proteinId = proteinId;
}
public String getDnaId() {
return dnaId;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public boolean isReverse() {
return reverse;
}
public String getProteinId() {
return proteinId;
}
/**
* parse GFF files to extract CDS
*
* @return list of CDS items
* @throws IOException, CanceledException
*/
public static Collection<CDS> parseGFFforCDS(Collection<String> inputFiles, ProgressListener progress) throws IOException, CanceledException {
progress.setMaximum(inputFiles.size());
progress.setProgress(0);
final ArrayList<CDS> list = new ArrayList<>();
for (String fileName : inputFiles) {
progress.setTasks("Processing GFF files", fileName);
try (FileLineIterator it = new FileLineIterator(fileName)) {
if (it.hasNext()) {
{
final String aLine = it.next();
if (aLine.startsWith(">")) {
final TaggedValueIterator vit = new TaggedValueIterator(false, true, "ref|");
vit.restart(aLine);
if (!vit.hasNext())
throw new IOException("Can't find reference accession in file: '" + fileName + "', header line: '" + aLine + "'");
final String dnaAccession = vit.getFirst();
list.addAll(parseSimpleGFFforCDS(it, dnaAccession));
} else if (aLine.startsWith("##gff-version 3")) {
list.addAll(parseGFF3forCDS(it));
}
}
}
}
progress.incrementProgress();
}
if (progress instanceof ProgressPercentage)
progress.reportTaskCompleted();
return list;
}
/**
* parse one line GFF3 format
*
* @return annotations
*/
private static Collection<CDS> parseGFF3forCDS(Iterator<String> iterator) {
final TaggedValueIterator dnaAccessionIterator = new TaggedValueIterator(true, true);
final ArrayList<CDS> list = new ArrayList<>(100000);
while (iterator.hasNext()) {
final String aLine = iterator.next();
final String[] tokens = StringUtils.split(aLine, '\t');
if (tokens.length >= 9 && tokens[2].equals("CDS")) {
final CDS cds = new CDS();
dnaAccessionIterator.restart(tokens[0]);
if (dnaAccessionIterator.hasNext()) {
cds.setDnaId(dnaAccessionIterator.getFirst());
cds.setStart(Integer.parseInt(tokens[3]));
cds.setEnd(Integer.parseInt(tokens[4]));
cds.setReverse(tokens[6].equals("-"));
if (!"+-".contains(tokens[6]))
System.err.println("Expected + or - in line: " + aLine);
final String accession = getFirstTaggedAccession(tokens[8], tags);
if (accession != null) {
cds.setProteinId(accession);
list.add(cds);
} // else System.err.println("No protein id found for line: " + aLine);
}
}
}
return list;
}
/**
* parse multi-line simple GFF format
*
* @return annotations
*/
private static Collection<CDS> parseSimpleGFFforCDS(Iterator<String> it, String dnaAccession) {
final TaggedValueIterator proteinAccessionIterator = new TaggedValueIterator(false, true, "ref|");
final ArrayList<CDS> list = new ArrayList<>(100000);
if (it.hasNext()) {
String aLine = it.next();
if (aLine.length() > 0 && Character.isDigit(aLine.charAt(0))) { // coordinates
while (it.hasNext()) { // only makes sense to process if there are more lines to be read, even if aLine!=null
final String[] tokens = StringUtils.split(aLine, '\t');
if (tokens.length == 3 && tokens[2].endsWith("CDS")) {
int a = NumberUtils.parseInt(tokens[0]);
int b = NumberUtils.parseInt(tokens[1]);
String proteinId = null;
while (it.hasNext()) {
aLine = it.next();
if (aLine.length() > 0 && Character.isDigit(aLine.charAt(0)))
break; // this is start of next feature
else if (aLine.contains("protein_id")) {
proteinAccessionIterator.restart(aLine);
if (proteinAccessionIterator.hasNext()) {
proteinId = proteinAccessionIterator.next();
}
}
}
if (proteinId != null) {
CDS cds = new CDS();
cds.setDnaId(dnaAccession);
cds.setStart(Math.min(a, b));
cds.setEnd(Math.max(a, b));
cds.setReverse(a > b);
cds.setProteinId(proteinId);
list.add(cds);
}
} else
aLine = it.next();
}
}
}
return list;
}
/**
* gets the first tagged accession
*
* @return first tagged accession
*/
private static String getFirstTaggedAccession(String reference, String... tags) {
for (String tag : tags) {
int pos = reference.indexOf(tag);
while (pos != -1) {
final int a = pos + tag.length();
int b = a;
while (b < reference.length() && (Character.isLetterOrDigit(reference.charAt(b)) || reference.charAt(b) == '_'))
b++;
if (b > a)
return reference.substring(a, b);
pos = reference.indexOf(tag, a);
}
}
return null;
}
}
| 8,306 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GeneItemCreator.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/genes/GeneItemCreator.java | /*
* GeneItemCreator.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.genes;
import megan.accessiondb.AccessAccessionMappingDatabase;
import megan.classification.Classification;
import megan.classification.IdMapper;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* class for creating gene items
* Daniel Huson, 6.2018
*/
public class GeneItemCreator {
private final String[] cNames;
private final Map<String, Integer> rank;
private final IdMapper[] idMappers;
private final AccessAccessionMappingDatabase database;
private final String[] shortTags;
/**
* constructor
*
*/
public GeneItemCreator(String[] cNames, IdMapper[] idMappers) {
this.cNames = cNames.clone();
this.idMappers = idMappers;
this.database = null;
rank = new HashMap<>();
for (int i = 0; i < this.cNames.length; i++) {
rank.put(this.cNames[i], i);
}
this.shortTags = new String[this.cNames.length];
for (int i = 0; i < cNames.length; i++) {
shortTags[i] = Classification.createShortTag(cNames[i]);
}
}
/**
* constructor
*
*/
public GeneItemCreator(String[] cNames, AccessAccessionMappingDatabase database) {
this.cNames = cNames.clone();
this.database = database;
this.idMappers = null;
rank = new HashMap<>();
for (int i = 0; i < this.cNames.length; i++) {
rank.put(this.cNames[i], i);
}
this.shortTags = new String[this.cNames.length];
for (int i = 0; i < cNames.length; i++) {
shortTags[i] = Classification.createShortTag(cNames[i]);
}
}
public GeneItem createGeneItem() {
return new GeneItem(this);
}
public Integer rank(String classificationName) {
return rank.get(classificationName);
}
public String classification(int rank) {
return cNames[rank];
}
public int numberOfClassifications() {
return cNames.length;
}
public Iterable<String> cNames() {
return () -> Arrays.asList(cNames).iterator();
}
/**
* map the given accession to ids using the id mappers
*
*/
public void map(String accession, int[] ids) throws IOException, SQLException {
if (idMappers != null)
for (int i = 0; i < idMappers.length; i++) {
ids[i] = idMappers[i].getAccessionMap().get(accession);
}
else {
for (int i = 0; i < cNames.length; i++) {
ids[i] = database.getValue(cNames[i], accession);
}
}
}
public String getShortTag(int i) {
return shortTags[i];
}
}
| 3,552 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GeneItem.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/genes/GeneItem.java | /*
* GeneItem.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.genes;
import jloda.util.StringUtils;
import jloda.util.interval.Interval;
import megan.io.InputReader;
import megan.io.OutputWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.SQLException;
/**
* a gene item
* Daniel Huson, 11.2017
*/
public class GeneItem {
private byte[] proteinId;
private final GeneItemCreator creator;
private boolean reverse;
private final int[] ids;
GeneItem(GeneItemCreator creator) {
this.creator = creator;
ids = new int[creator.numberOfClassifications()];
}
private byte[] getProteinId() {
return proteinId;
}
public void setProteinId(byte[] proteinId) throws IOException {
this.proteinId = proteinId;
try {
creator.map(StringUtils.toString(proteinId), ids);
} catch (SQLException ignored) {
}
}
public int getId(String classificationName) {
return getId(creator.rank(classificationName));
}
private int getId(Integer rank) {
return rank == null ? 0 : ids[rank];
}
public void setId(String classificationName, int id) {
ids[creator.rank(classificationName)] = id;
}
public void setId(int rank, int id) {
ids[rank] = id;
}
private boolean isReverse() {
return reverse;
}
public void setReverse(boolean reverse) {
this.reverse = reverse;
}
public String toString() {
final StringBuilder buf = new StringBuilder("proteinId=" + (proteinId == null ? "null" : StringUtils.toString(proteinId)));
for (int i = 0; i < creator.numberOfClassifications(); i++) {
buf.append(", ").append(creator.classification(i)).append("=").append(ids[i]);
}
buf.append(", reverse=").append(reverse);
return buf.toString();
}
/**
* write
*
*/
public void write(OutputWriter outs) throws IOException {
if (proteinId == null || proteinId.length == 0)
outs.writeInt(0);
else {
outs.writeInt(proteinId.length);
outs.write(proteinId);
}
for (int i = 0; i < creator.numberOfClassifications(); i++) {
outs.writeInt(ids[i]);
}
outs.write(reverse ? 1 : 0);
}
/**
* read
*
*/
public void read(RandomAccessFile ins) throws IOException {
int length = ins.readInt();
if (length == 0)
proteinId = null;
else {
proteinId = new byte[length];
if (ins.read(proteinId, 0, length) != length)
throw new IOException("read failed");
}
for (int i = 0; i < creator.numberOfClassifications(); i++) {
ids[i] = ins.readInt();
}
reverse = (ins.read() == 1);
}
/**
* read
*
*/
public void read(InputReader ins) throws IOException {
int length = ins.readInt();
if (length == 0)
proteinId = null;
else {
proteinId = new byte[length];
if (ins.read(proteinId, 0, length) != length)
throw new IOException("read failed");
}
for (int i = 0; i < creator.numberOfClassifications(); i++) {
ids[i] = ins.readInt();
}
reverse = (ins.read() == 1);
}
/**
* get the annotation string
*
* @return annotation string
*/
public String getAnnotation(Interval<GeneItem> refInterval) {
final StringBuilder buf = new StringBuilder();
buf.append("pos|").append(isReverse() ? refInterval.getEnd() + ".." + refInterval.getStart() : refInterval.getStart() + ".." + refInterval.getEnd());
buf.append("|ref|").append(StringUtils.toString(getProteinId()));
for (int i = 0; i < creator.numberOfClassifications(); i++) {
if (getId(i) > 0)
buf.append("|").append(creator.getShortTag(i)).append(getId(i));
}
return buf.toString();
}
}
| 4,800 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GeneItemAccessor.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/genes/GeneItemAccessor.java | /*
* GeneItemAccessor.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.genes;
import jloda.util.Basic;
import jloda.util.StringUtils;
import jloda.util.interval.Interval;
import jloda.util.interval.IntervalTree;
import jloda.util.progress.ProgressPercentage;
import megan.classification.IdMapper;
import megan.io.InputReader;
import megan.tools.AAdderBuild;
import megan.tools.AAdderRun;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* class used to access gene items
* Daniel Huson, 6.2018
*/
public class GeneItemAccessor {
private final int size;
private final long[] refIndex2FilePos;
private final IntervalTree<GeneItem>[] refIndex2Intervals;
private final String[] index2ref;
private final RandomAccessFile dbRaf;
private final GeneItemCreator creator;
private final int syncBits = 1023;
private final Object[] syncObjects = new Object[syncBits + 1]; // use lots of objects to synchronize on so that threads don't in each others way
/**
* construct the gene table from the gene-table index file
*
*/
public GeneItemAccessor(File indexFile, File dbFile) throws IOException {
// create the synchronization objects
for (int i = 0; i < (syncBits + 1); i++) {
syncObjects[i] = new Object();
}
try (InputReader ins = new InputReader(indexFile); ProgressPercentage progress = new ProgressPercentage("Reading file: " + indexFile)) {
AAdderRun.readAndVerifyMagicNumber(ins, AAdderBuild.MAGIC_NUMBER_IDX);
final String creator = ins.readString();
if (!creator.equals("MALT"))
throw new IOException("Gene Item index not created by MALT");
size = ins.readInt();
progress.setMaximum(size);
refIndex2FilePos = new long[size];
index2ref = new String[size];
for (int i = 0; i < size; i++) {
index2ref[i] = ins.readString();
final long pos = ins.readLong();
refIndex2FilePos[i] = pos;
progress.incrementProgress();
}
}
refIndex2Intervals = (IntervalTree<GeneItem>[]) new IntervalTree[size];
try (InputReader dbxIns = new InputReader(dbFile)) {
AAdderRun.readAndVerifyMagicNumber(dbxIns, AAdderBuild.MAGIC_NUMBER_DBX);
final String[] cNames = new String[dbxIns.readInt()];
for (int i = 0; i < cNames.length; i++) {
cNames[i] = dbxIns.readString();
System.err.println(cNames[i]);
}
creator = new GeneItemCreator(cNames, new IdMapper[0]);
}
dbRaf = new RandomAccessFile(dbFile, "r");
}
private int warned = 0;
/**
* get intervals for a given ref index
*
* @return intervals or null
*/
private IntervalTree<GeneItem> getIntervals(int refIndex) {
synchronized (syncObjects[refIndex & syncBits]) {
if (refIndex < refIndex2Intervals.length && refIndex2Intervals[refIndex] == null && refIndex2FilePos[refIndex] != 0) {
synchronized (dbRaf) {
try {
final long pos = refIndex2FilePos[refIndex];
dbRaf.seek(pos);
int intervalsLength = dbRaf.readInt();
if (intervalsLength > 0) {
IntervalTree<GeneItem> intervals = new IntervalTree<>();
for (int i = 0; i < intervalsLength; i++) {
int start = dbRaf.readInt();
int end = dbRaf.readInt();
GeneItem geneItem = new GeneItem(creator);
geneItem.read(dbRaf);
intervals.add(start, end, geneItem);
//System.err.println(refIndex+"("+start+"-"+end+") -> "+geneItem);
}
refIndex2Intervals[refIndex] = intervals;
}
} catch (IOException ex) {
if (warned < 10) {
Basic.caught(ex);
if (++warned == 0) {
System.err.println("Suppressing all further such exceptions");
}
}
}
}
}
return refIndex2Intervals[refIndex];
}
}
/**
* adds annotations to reference header
*
* @return annotated reference header
*/
public String annotateRefString(String referenceHeader, Integer refIndex, int alignStart, int alignEnd) {
final IntervalTree<GeneItem> tree = getIntervals(refIndex);
if (tree != null) {
final Interval<Object> alignInterval = new Interval<>(alignStart, alignEnd, null);
final Interval<GeneItem> refInterval = tree.getBestInterval(alignInterval, 0.9);
if (refInterval != null) {
final GeneItem geneItem = refInterval.getData();
return StringUtils.swallowLeadingGreaterSign(StringUtils.getFirstWord(referenceHeader)) + "|" + geneItem.getAnnotation(refInterval);
}
}
return referenceHeader;
}
private String getIndex2ref(int i) {
return index2ref[i];
}
private int size() {
return size;
}
}
| 6,265 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MergeFiles.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/tools/MergeFiles.java | /*
* CompareFiles.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.tools;
import jloda.swing.util.ArgsOptions;
import jloda.swing.util.ResourceManager;
import jloda.util.*;
import megan.core.*;
import megan.data.merge.MergeConnector;
import megan.main.MeganProperties;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
/**
* computes a merged view of multiple files
* Daniel Huson, 5.2022
*/
public class MergeFiles {
/**
* merge files
*/
public static void main(String[] args) {
try {
ResourceManager.insertResourceRoot(megan.resources.Resources.class);
ProgramProperties.setProgramName("MergeFiles");
ProgramProperties.setProgramVersion(megan.main.Version.SHORT_DESCRIPTION);
PeakMemoryUsageMonitor.start();
(new MergeFiles()).run(args);
System.err.println("Total time: " + PeakMemoryUsageMonitor.getSecondsSinceStartString());
System.err.println("Peak memory: " + PeakMemoryUsageMonitor.getPeakUsageString());
System.exit(0);
} catch (Exception ex) {
Basic.caught(ex);
System.exit(1);
}
}
/**
* run
*/
public void run(String[] args) throws Exception {
final ArgsOptions options = new ArgsOptions(args, this, "Computes the comparison of multiple megan, RMA or meganized DAA files");
options.setVersion(ProgramProperties.getProgramVersion());
options.setLicense("Copyright (C) 2024. This program comes with ABSOLUTELY NO WARRANTY.");
options.setAuthors("Daniel H. Huson");
options.comment("Input and Output:");
final ArrayList<String> inputFiles = new ArrayList<>(Arrays.asList(options.getOptionMandatory("-i", "in", "Input RMA and/or meganized DAA files (single directory ok)", new String[0])));
final String meganFileName = options.getOption("-o", "out", "Output file", "merged.megan");
final String metadataFile = options.getOption("-mdf", "metaDataFile", "Metadata file", "");
final var propertiesFile = options.getOption("-P", "propertiesFile", "Properties file",megan.main.Megan6.getDefaultPropertiesFile());
options.done();
MeganProperties.initializeProperties(propertiesFile);
if (inputFiles.size() == 1 && FileUtils.isDirectory(inputFiles.get(0))) {
final String directory = inputFiles.get(0);
inputFiles.clear();
inputFiles.addAll(FileUtils.getAllFilesInDirectory(directory, true, ".megan", ".megan.gz", ".daa", ".rma", ".rma6"));
}
for (var fileName : inputFiles) {
if (!FileUtils.fileExistsAndIsNonEmpty(fileName))
throw new IOException("No such file or file empty: " + fileName);
}
if (inputFiles.size() == 0)
throw new UsageException("No input file");
String parameters = null;
for (var fileName : inputFiles) {
final var file = new MeganFile();
file.setFileFromExistingFile(fileName, false);
if (!file.isOkToRead() || file.getConnector() == null)
throw new IOException("Can't process file (unreadable, or not meganized-DAA or RMA6): " + fileName);
System.err.println("Input file: " + fileName);
System.err.printf("\t\t%,d reads%n", file.getConnector().getNumberOfReads());
if (parameters == null) {
var table = new DataTable();
var label2data = file.getConnector().getAuxiliaryData();
SyncArchiveAndDataTable.syncAux2Summary(fileName, label2data.get(SampleAttributeTable.USER_STATE), table);
parameters = table.getParameters();
}
}
var doc = new Document();
if (parameters != null)
doc.parseParameterString(parameters);
var meganFile = new MeganFile();
meganFile.setFile(meganFileName, MeganFile.Type.MEGAN_SUMMARY_FILE);
var connector = new MergeConnector(meganFileName, inputFiles);
SyncArchiveAndDataTable.syncArchive2Summary(null, meganFileName, connector, doc.getDataTable(), doc.getSampleAttributeTable());
doc.getDataTable().setMergedFiles(FileUtils.getFileNameWithoutPathOrSuffix(meganFileName), inputFiles);
meganFile.setMergedFiles(Arrays.asList(doc.getDataTable().getMergedFiles()));
doc.getDataTable().clearCollapsed();
try (var writer = new FileWriter(meganFileName)) {
doc.getDataTable().write(writer);
doc.getSampleAttributeTable().write(writer, false, true);
}
if (StringUtils.notBlank(metadataFile)) {
try (var r = new BufferedReader(new InputStreamReader(FileUtils.getInputStreamPossiblyZIPorGZIP(metadataFile)))) {
System.err.print("Processing Metadata: " + metadataFile);
doc.getSampleAttributeTable().read(r, doc.getSampleNames(), true);
System.err.println(", attributes: " + doc.getSampleAttributeTable().getNumberOfUnhiddenAttributes());
}
}
System.err.println("Output file: " + meganFileName);
System.err.printf("\t\t%,d reads%n", meganFile.getConnector().getNumberOfReads());
}
}
| 5,539 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AAdderBuild.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/tools/AAdderBuild.java | /*
* AAdderBuild.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.tools;
import jloda.swing.util.ArgsOptions;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.GFF3FileFilter;
import jloda.swing.util.ResourceManager;
import jloda.util.*;
import jloda.util.interval.Interval;
import jloda.util.progress.ProgressListener;
import jloda.util.progress.ProgressPercentage;
import megan.accessiondb.AccessAccessionMappingDatabase;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.IdMapper;
import megan.genes.CDS;
import megan.genes.GeneItem;
import megan.genes.GeneItemCreator;
import megan.io.OutputWriter;
import megan.main.MeganProperties;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
/**
* build the aadder index
* Daniel Huson, 5.2018
*/
public class AAdderBuild {
final public static byte[] MAGIC_NUMBER_IDX = "AAddIdxV0.1.".getBytes();
final public static byte[] MAGIC_NUMBER_DBX = "AAddDbxV0.1.".getBytes();
private final static String INDEX_CREATOR = "AADD";
/**
* add functional annotations to DNA alignments
*/
public static void main(String[] args) {
try {
ResourceManager.insertResourceRoot(megan.resources.Resources.class);
ProgramProperties.setProgramName("AAdderBuild");
ProgramProperties.setProgramVersion(megan.main.Version.SHORT_DESCRIPTION);
PeakMemoryUsageMonitor.start();
(new AAdderBuild()).run(args);
System.err.println("Total time: " + PeakMemoryUsageMonitor.getSecondsSinceStartString());
System.err.println("Peak memory: " + PeakMemoryUsageMonitor.getPeakUsageString());
System.exit(0);
} catch (Exception ex) {
Basic.caught(ex);
System.exit(1);
}
}
/**
* run the program
*/
private void run(String[] args) throws CanceledException, IOException, UsageException, SQLException {
final ArgsOptions options = new ArgsOptions(args, this, "Build the index for AAdd");
options.setVersion(ProgramProperties.getProgramVersion());
options.setLicense("Copyright (C) 2024. This program comes with ABSOLUTELY NO WARRANTY.");
options.setAuthors("Daniel H. Huson");
options.comment("Input Output");
final List<String> gffFiles = options.getOptionMandatory("-igff", "inputGFF", "Input GFF3 files or directory (.gz ok)", new LinkedList<>());
final String indexDirectory = options.getOptionMandatory("-d", "index", "Index directory", "");
options.comment("Classification mapping:");
final String mapDBFile = options.getOption("-mdb", "mapDB", "MEGAN mapping db (file megan-map.db)", "");
options.comment("Deprecated classification mapping options:");
final HashMap<String, String> class2AccessionFile = new HashMap<>();
final String acc2TaxaFile = options.getOption("-a2t", "acc2taxa", "Accession-to-Taxonomy mapping file", "");
for (String cName : ClassificationManager.getAllSupportedClassificationsExcludingNCBITaxonomy()) {
class2AccessionFile.put(cName, options.getOption("-a2" + cName.toLowerCase(), "acc2" + cName.toLowerCase(), "Accession-to-" + cName + " mapping file", ""));
}
options.comment(ArgsOptions.OTHER);
final boolean lookInside = options.getOption("-ex", "extraStrict", "When given an input directory, look inside every input file to check that it is indeed in GFF3 format", false);
final var propertiesFile = options.getOption("-P", "propertiesFile", "Properties file",megan.main.Megan6.getDefaultPropertiesFile());
options.done();
MeganProperties.initializeProperties(propertiesFile);
final Collection<String> mapDBClassifications = AccessAccessionMappingDatabase.getContainedClassificationsIfDBExists(mapDBFile);
if (!mapDBClassifications.isEmpty() && StringUtils.hasPositiveLengthValue(class2AccessionFile))
throw new UsageException("Illegal to use both --mapDB and ---acc2... options");
if (!mapDBClassifications.isEmpty())
ClassificationManager.setMeganMapDBFile(mapDBFile);
// setup the gff file:
setupGFFFiles(gffFiles, lookInside);
// setup gene item creator, in particular accession mapping
final GeneItemCreator creator;
if (!mapDBFile.isEmpty())
creator = setupCreator(mapDBFile);
else
creator = setupCreator(acc2TaxaFile, class2AccessionFile);
// obtains the gene annotations:
Map<String, ArrayList<Interval<GeneItem>>> dnaId2list = computeAnnotations(creator, gffFiles);
saveIndex(INDEX_CREATOR, creator, indexDirectory, dnaId2list, dnaId2list.keySet());
}
/**
* setup the GFF files
*
*/
public static void setupGFFFiles(List<String> gffFiles, boolean lookInside) throws IOException {
if (gffFiles.size() == 1) {
final File file = new File(gffFiles.get(0));
if (file.isDirectory()) {
System.err.println("Looking for GFF3 files in directory: " + file);
gffFiles.clear();
for (File aFile : BasicSwing.getAllFilesInDirectory(file, new GFF3FileFilter(true, lookInside), true)) {
gffFiles.add(aFile.getPath());
}
if (gffFiles.isEmpty())
throw new IOException("No GFF files found in directory: " + file);
else
System.err.printf("Found: %,d%n", gffFiles.size());
}
}
}
public static GeneItemCreator setupCreator(String mapDBFile) throws IOException, SQLException {
final AccessAccessionMappingDatabase database = new AccessAccessionMappingDatabase(mapDBFile);
final ArrayList<String> classificationNames = new ArrayList<>();
for (String cName : ClassificationManager.getAllSupportedClassifications()) {
if (database.getSize(cName) > 0)
classificationNames.add(cName);
}
return new GeneItemCreator(classificationNames.toArray(new String[0]), database);
}
/**
* setup the gene item creator
*
* @return gene item creator
*/
public static GeneItemCreator setupCreator(String acc2TaxaFile, Map<String, String> class2AccessionFile) throws IOException {
final String[] cNames;
{
final ArrayList<String> list = new ArrayList<>();
if (acc2TaxaFile != null && !acc2TaxaFile.isEmpty())
list.add(Classification.Taxonomy);
for (String cName : class2AccessionFile.keySet())
if (!class2AccessionFile.get(cName).isEmpty() && !list.contains(cName))
list.add(cName);
cNames = list.toArray(new String[0]);
}
final IdMapper[] idMappers = new IdMapper[cNames.length];
for (int i = 0; i < cNames.length; i++) {
final String cName = cNames[i];
idMappers[i] = ClassificationManager.get(cName, true).getIdMapper();
if (cName.equals(Classification.Taxonomy) && acc2TaxaFile != null && !acc2TaxaFile.isEmpty())
idMappers[i].loadMappingFile(acc2TaxaFile, IdMapper.MapType.Accession, false, new ProgressPercentage());
else
idMappers[i].loadMappingFile(class2AccessionFile.get(cName), IdMapper.MapType.Accession, false, new ProgressPercentage());
}
return new GeneItemCreator(cNames, idMappers);
}
/**
* compute annotations
*
*/
public static Map<String, ArrayList<Interval<GeneItem>>> computeAnnotations(GeneItemCreator creator, Collection<String> gffFiles) throws IOException, CanceledException {
Map<String, ArrayList<Interval<GeneItem>>> dnaId2list = new HashMap<>();
final Collection<CDS> annotations = CDS.parseGFFforCDS(gffFiles, new ProgressPercentage("Processing GFF files"));
try (ProgressListener progress = new ProgressPercentage("Building annotation list", annotations.size())) {
for (CDS cds : annotations) {
ArrayList<Interval<GeneItem>> list = dnaId2list.computeIfAbsent(cds.getDnaId(), k -> new ArrayList<>());
final GeneItem geneItem = creator.createGeneItem();
final String accession = cds.getProteinId();
geneItem.setProteinId(accession.getBytes());
geneItem.setReverse(cds.isReverse());
list.add(new Interval<>(cds.getStart(), cds.getEnd(), geneItem));
progress.incrementProgress();
}
}
return dnaId2list;
}
/**
* save the index
*
*/
public static void saveIndex(String indexCreator, GeneItemCreator creator, String indexDirectory, Map<String, ArrayList<Interval<GeneItem>>> dnaId2list, Iterable<String> dnaIdOrder) throws IOException {
// writes the index file:
long totalRefWithAGene = 0;
final File indexFile = new File(indexDirectory, "aadd.idx");
final File dbFile = new File(indexDirectory, "aadd.dbx");
try (OutputWriter idxWriter = new OutputWriter(indexFile); OutputWriter dbxWriter = new OutputWriter(dbFile);
ProgressPercentage progress = new ProgressPercentage("Writing files: " + indexFile + "\n " + dbFile, dnaId2list.size())) {
idxWriter.write(MAGIC_NUMBER_IDX);
idxWriter.writeString(indexCreator);
idxWriter.writeInt(dnaId2list.size());
dbxWriter.write(MAGIC_NUMBER_DBX);
// write the list of classifications:
dbxWriter.writeInt(creator.numberOfClassifications());
for (String cName : creator.cNames()) {
dbxWriter.writeString(cName);
}
for (String dnaId : dnaIdOrder) {
idxWriter.writeString(dnaId);
final ArrayList<Interval<GeneItem>> list = dnaId2list.get(dnaId);
if (list == null) {
idxWriter.writeLong(0); // no intervals
} else {
idxWriter.writeLong(dbxWriter.getPosition()); // position of intervals in DB file
dbxWriter.writeInt(list.size());
for (Interval<GeneItem> interval : CollectionUtils.randomize(list, 666)) { // need to save in random order
dbxWriter.writeInt(interval.getStart());
dbxWriter.writeInt(interval.getEnd());
interval.getData().write(dbxWriter);
}
totalRefWithAGene++;
}
progress.incrementProgress();
}
}
System.err.printf("Reference sequences with at least one annotation: %,d of %,d%n", totalRefWithAGene, dnaId2list.size());
}
}
| 11,732 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AAdderRun.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/tools/AAdderRun.java | /*
* AAdderRun.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.tools;
import jloda.swing.util.ArgsOptions;
import jloda.swing.util.ResourceManager;
import jloda.util.*;
import jloda.util.interval.Interval;
import jloda.util.interval.IntervalTree;
import jloda.util.progress.ProgressPercentage;
import megan.classification.IdMapper;
import megan.genes.GeneItem;
import megan.genes.GeneItemCreator;
import megan.io.IInputReader;
import megan.io.InputReader;
import megan.main.MeganProperties;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
/**
* add functional annotations to DNA alignments
* Daniel Huson, 5.2018
*/
public class AAdderRun {
/**
* add functional annotations to DNA alignments
*/
public static void main(String[] args) {
try {
ResourceManager.insertResourceRoot(megan.resources.Resources.class);
ProgramProperties.setProgramName("AAdderRun");
ProgramProperties.setProgramVersion(megan.main.Version.SHORT_DESCRIPTION);
PeakMemoryUsageMonitor.start();
(new AAdderRun()).run(args);
System.err.println("Total time: " + PeakMemoryUsageMonitor.getSecondsSinceStartString());
System.err.println("Peak memory: " + PeakMemoryUsageMonitor.getPeakUsageString());
System.exit(0);
} catch (Exception ex) {
Basic.caught(ex);
System.exit(1);
}
}
/**
* run the program
*/
private void run(String[] args) throws CanceledException, IOException, UsageException {
final ArgsOptions options = new ArgsOptions(args, this, "Adds functional accessions to DNA alignments");
options.setVersion(ProgramProperties.getProgramVersion());
options.setLicense("Copyright (C) 2024. This program comes with ABSOLUTELY NO WARRANTY.");
options.setAuthors("Daniel H. Huson");
options.comment("Input Output");
final String[] inputFiles = options.getOptionMandatory("-i", "input", "Input SAM file(s) (.gz ok)", new String[0]);
final String indexDirectory = options.getOptionMandatory("-d", "index", "AAdd index directory", "");
final String[] outputFiles = options.getOptionMandatory("-o", "output", "Output file(s) (.gz ok) or directory", new String[0]);
options.comment(ArgsOptions.OTHER);
final double minCoverageProportion = options.getOption("-c", "percentToCover", "Percent of alignment that must be covered by protein", 90.00) / 100.0;
final boolean reportUnmappedAccessions = options.getOption("-rnf", "reportNotFound", "Report the names of DNA references for which no functional accession is available", false);
final var propertiesFile = options.getOption("-P", "propertiesFile", "Properties file",megan.main.Megan6.getDefaultPropertiesFile());
options.done();
MeganProperties.initializeProperties(propertiesFile);
final File outputDir;
if (outputFiles.length == 1 && ((new File(outputFiles[0])).isDirectory())) {
outputDir = new File(outputFiles[0]);
} else {
outputDir = null;
if (inputFiles.length != outputFiles.length)
throw new UsageException("Number of output files doesn't match number of input files");
}
final Map<String, Pair<Long, IntervalTree<GeneItem>>> ref2PosAndTree;
final File indexFile = new File(indexDirectory, "aadd.idx");
try (InputReader ins = new InputReader(indexFile); ProgressPercentage progress = new ProgressPercentage("Reading file: " + indexFile)) {
readAndVerifyMagicNumber(ins, AAdderBuild.MAGIC_NUMBER_IDX);
final String creator = ins.readString();
System.err.println("Index created by: " + creator);
final int entries = ins.readInt();
progress.setMaximum(entries);
ref2PosAndTree = new HashMap<>(2 * entries);
for (int t = 0; t < entries; t++) {
final String dnaId = ins.readString();
final long pos = ins.readLong();
ref2PosAndTree.put(dnaId, new Pair<>(pos, null));
progress.incrementProgress();
}
}
final IntervalTree<GeneItem> emptyTree = new IntervalTree<>();
final File dbFile = new File(indexDirectory, "aadd.dbx");
try (InputReader dbxIns = new InputReader(dbFile)) {
System.err.println("Opening file: " + dbFile);
readAndVerifyMagicNumber(dbxIns, AAdderBuild.MAGIC_NUMBER_DBX);
final String[] cNames = new String[dbxIns.readInt()];
for (int i = 0; i < cNames.length; i++) {
cNames[i] = dbxIns.readString();
}
final GeneItemCreator creator = new GeneItemCreator(cNames, new IdMapper[0]);
for (int i = 0; i < inputFiles.length; i++) {
File inputFile = new File(inputFiles[i]);
final File outputFile;
if (outputDir != null) {
outputFile = new File(outputDir, inputFile.getName() + ".out");
} else
outputFile = new File(outputFiles[i]);
if (inputFile.equals(outputFile))
throw new IOException("Input file equals output file: " + inputFile);
final boolean gzipOutput = outputFile.getName().toLowerCase().endsWith(".gz");
long countLines = 0;
long countAlignments = 0;
long countAnnotated = 0;
long countReferencesLoaded = 0;
final Set<String> refNotFound = new HashSet<>();
try (final FileLineIterator it = new FileLineIterator(inputFile, true);
final BufferedWriter w = new BufferedWriter(new OutputStreamWriter(gzipOutput ? new GZIPOutputStream(new FileOutputStream(outputFile)) : new FileOutputStream(outputFile)))) {
System.err.println("Writing file: " + outputFile);
while (it.hasNext()) {
final String aLine = it.next();
if (aLine.startsWith("@"))
w.write(aLine);
else {
final String[] tokens = StringUtils.split(aLine, '\t');
if (tokens.length < 2 || tokens[2].equals("*")) {
w.write(aLine);
} else {
final IntervalTree<GeneItem> tree;
{
final int pos = tokens[2].indexOf(".");
final String ref = (pos > 0 ? tokens[2].substring(0, pos) : tokens[2]);
final Pair<Long, IntervalTree<GeneItem>> pair = ref2PosAndTree.get(ref);
if (pair != null) {
if (pair.getSecond() == null && pair.getFirst() != 0) {
dbxIns.seek(pair.getFirst());
int intervalsLength = dbxIns.readInt();
if (intervalsLength > 0) {
tree = new IntervalTree<>();
for (int t = 0; t < intervalsLength; t++) {
final int start = dbxIns.readInt();
final int end = dbxIns.readInt();
final GeneItem geneItem = creator.createGeneItem();
geneItem.read(dbxIns);
tree.add(start, end, geneItem);
//System.err.println(refIndex+"("+start+"-"+end+") -> "+geneItem);
}
countReferencesLoaded++;
} else {
tree = emptyTree;
}
pair.setSecond(tree);
} else {
tree = pair.getSecond();
}
} else {
if (!refNotFound.contains(ref)) {
refNotFound.add(ref);
if (reportUnmappedAccessions)
System.err.println("Reference not found: " + ref);
}
continue;
}
}
final int startSubject = NumberUtils.parseInt(tokens[3]);
final int endSubject = startSubject + getRefLength(tokens[5]) - 1;
final Interval<GeneItem> refInterval = tree.getBestInterval(new Interval<GeneItem>(startSubject, endSubject, null), minCoverageProportion);
String annotatedRef = tokens[2];
if (refInterval != null) {
final GeneItem geneItem = refInterval.getData();
final String remainder;
final int len = annotatedRef.indexOf(' ');
if (len >= 0 && len < annotatedRef.length()) {
remainder = annotatedRef.substring(len); // keep space...
annotatedRef = annotatedRef.substring(0, len);
} else
remainder = "";
annotatedRef += (annotatedRef.endsWith("|") ? "" : "|") + geneItem.getAnnotation(refInterval) + remainder;
}
for (int t = 0; t < tokens.length; t++) {
if (t > 0)
w.write('\t');
if (t == 2 && !annotatedRef.equals(tokens[2])) {
w.write(annotatedRef);
countAnnotated++;
} else
w.write(tokens[t]);
}
}
countAlignments++;
}
w.write("\n");
countLines++;
}
}
System.err.printf("Lines: %,11d%n", countLines);
System.err.printf("Alignments:%,11d%n", countAlignments);
System.err.printf("Annotated: %,11d%n", countAnnotated);
System.err.printf("(Loaded refs:%,9d)%n", countReferencesLoaded);
if (refNotFound.size() > 0)
System.err.printf("(Missing refs:%,8d)%n", refNotFound.size());
}
}
}
private static final Pattern pattern = Pattern.compile("[0-9]+[MDN]+");
private static int getRefLength(String cigar) {
final Matcher matcher = pattern.matcher(cigar);
final ArrayList<String> pairs = new ArrayList<>();
while (matcher.find())
pairs.add(matcher.group());
int length = 0;
for (String p : pairs) {
int num = Integer.parseInt(p.substring(0, p.length() - 1));
length += num;
}
return length;
}
/**
* read and verify a magic number from a stream
*
*/
public static void readAndVerifyMagicNumber(IInputReader ins, byte[] expectedMagicNumber) throws IOException {
byte[] magicNumber = new byte[expectedMagicNumber.length];
if (ins.read(magicNumber, 0, magicNumber.length) != expectedMagicNumber.length || !Basic.equal(magicNumber, expectedMagicNumber)) {
System.err.println("Expected: " + StringUtils.toString(expectedMagicNumber));
System.err.println("Got: " + StringUtils.toString(magicNumber));
throw new IOException("Index is too old or incorrect file (wrong magic number). Please recompute index.");
}
}
}
| 13,490 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.