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
SetColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetColorCommand.java
/* * SetColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * set color * Daniel Huson, 4.2011 */ public class SetColorCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Color"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the color of selected nodes and edges"; } public ImageIcon getIcon() { return ResourceManager.getIcon("YellowSquare16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it * */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set color="); Color color = null; if (np.peekMatchIgnoreCase("null")) np.matchIgnoreCase("null"); else color = ColorUtilsSwing.convert(np.getColor()); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Node v : viewer.getSelectedNodes()) { viewer.setColor(v, color); changed = true; } for (Edge edge : viewer.getSelectedEdges()) { viewer.setColor(edge, color); changed = true; } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose color", null); if (color != null) execute("set color=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set color={<color>|null};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && (((GraphView) getViewer()).getSelectedNodes().size() > 0 || ((GraphView) getViewer()).getSelectedEdges().size() > 0); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,245
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawNoneCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DrawNoneCommand.java
/* * DrawNoneCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw selected nodes as nothing * Daniel Huson, 3.2013 */ public class DrawNoneCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((Director) getDir()).getDocument().getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "None"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "No node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set nodeShape=none;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
2,864
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawDiamondsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DrawDiamondsCommand.java
/* * DrawDiamondsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw selected nodes as diamonds * Daniel Huson, 3.2013 */ public class DrawDiamondsCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((Director) getDir()).getDocument().getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Diamond"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Diamond node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueDiamond16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set nodeShape=diamond;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
2,965
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawCirclesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DrawCirclesCommand.java
/* * DrawCirclesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw selected nodes as circles * Daniel Huson, 3.2013 */ public class DrawCirclesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((Director) getDir()).getDocument().getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Circle"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Circle node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueCircle16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set nodeShape=circle;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
2,972
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetFillColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetFillColorCommand.java
/* * SetFillColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * set color * Daniel Huson, 4.2011 */ public class SetFillColorCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Fill Color"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the fill color of selected nodes"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set fillColor="); Color color = null; if (np.peekMatchIgnoreCase("null")) np.matchIgnoreCase("null"); else color = ColorUtilsSwing.convert(np.getColor()); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Node v : viewer.getSelectedNodes()) { viewer.setBackgroundColor(v, color); changed = true; } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { final Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose fill color", ProgramProperties.get("NodeFillColor", Color.WHITE)); if (color != null) { execute("set fillColor=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + ";"); ProgramProperties.put("NodeFillColor", color); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set fillColor={<color>|null}"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && ((GraphView) getViewer()).getSelectedNodes().size() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,187
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UngroupNodesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/UngroupNodesCommand.java
/* * UngroupNodesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.clusteranalysis.ClusterViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * do not join nodes in PCoA plot * Daniel Huson, 7.2014 */ public class UngroupNodesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { if (getViewer() instanceof ClusterViewer) { final ClusterViewer clusterViewer = (ClusterViewer) getViewer(); return clusterViewer.isPCoATab() && clusterViewer.getGraphView().getSelectedNodes().size() >= 1; } else return true; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Ungroup All"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Ungroup nodes in PCoA plot"; } public ImageIcon getIcon() { return ResourceManager.getIcon("UnJoinNodes16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set groupNodes=none;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,110
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GroupNodesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/GroupNodesCommand.java
/* * GroupNodesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.util.ResourceManager; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import megan.clusteranalysis.ClusterViewer; import megan.clusteranalysis.gui.PCoATab; import megan.core.Director; import megan.core.Document; import megan.groups.GroupsViewer; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Collection; /** * group nodes in PCoA plot * Daniel Huson, 7.2014 */ public class GroupNodesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set groupNodes="); final String choice = np.getWordMatchesIgnoringCase("none selected"); np.matchIgnoreCase(";"); final Document doc = ((Director) getDir()).getDocument(); if (choice.equalsIgnoreCase("none")) { for (String sample : doc.getSampleNames()) { doc.getSampleAttributeTable().putGroupId(sample, null); } } else if (choice.equalsIgnoreCase("selected")) { Collection<String> selectedSamples; if (getViewer() instanceof SamplesViewer) { SamplesViewer samplesViewer = (SamplesViewer) getViewer(); selectedSamples = samplesViewer.getSamplesTableView().getSelectedSamples(); } else { selectedSamples = doc.getSampleSelection().getAll(); } int nextId = 1; for (String sample : doc.getSampleNames()) { if (NumberUtils.isInteger(doc.getSampleAttributeTable().getGroupId(sample))) { int joinId = NumberUtils.parseInt(doc.getSampleAttributeTable().getGroupId(sample)); if (joinId != 0 && nextId <= joinId) nextId = joinId + 1; } } for (String sample : selectedSamples) { doc.getSampleAttributeTable().putGroupId(sample, "" + nextId); } } final GroupsViewer groupViewer = (GroupsViewer) getDir().getViewerByClass(GroupsViewer.class); if (groupViewer != null) groupViewer.updateView(IDirector.ALL); for (IDirectableViewer viewer : ((Director) getDir()).getViewers()) { if (viewer instanceof ClusterViewer) { if (choice.equalsIgnoreCase("selected")) { final PCoATab pcoaTab = ((ClusterViewer) viewer).getPcoaTab(); if (!pcoaTab.isShowGroupsAsEllipses() && !pcoaTab.isShowGroupsAsConvexHulls()) { pcoaTab.setShowGroupsAsEllipses(true); } } viewer.updateView(Director.ALL); } } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set groupNodes={none|selected};"; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { if (getViewer() instanceof ClusterViewer) { final ClusterViewer clusterViewer = (ClusterViewer) getViewer(); return clusterViewer.isPCoATab() && clusterViewer.getGraphView().getSelectedNodes().size() >= 1; } else if (getViewer() instanceof SamplesViewer) { final SamplesViewer samplesViewer = (SamplesViewer) getViewer(); return samplesViewer.getSamplesTableView().getCountSelectedSamples() > 0; } else return ((Director) getDir()).getDocument().getSampleSelection().size() >= 1; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Group Nodes"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Group selected nodes in PCoA plot"; } public ImageIcon getIcon() { return ResourceManager.getIcon("JoinNodes16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("show window=groups;set groupNodes=selected;"); } }
5,700
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetFontCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetFontCommand.java
/* * SetFontCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.HashSet; import java.util.Set; /** * set size * Daniel Huson, 4.2011 */ public class SetFontCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Font"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set font nodes or edges, e.g. arial-italic-12"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set font="); String fontName = np.getWordRespectCase(); np.matchIgnoreCase(";"); Font font = Font.decode(fontName); boolean changed = false; ViewerBase viewer = (ViewerBase) getViewer(); Set<Node> nodes = new HashSet<>(); if (viewer.getSelectedNodes().size() == 0 && viewer.getSelectedEdges().size() == 0) { for (Node v = viewer.getGraph().getFirstNode(); v != null; v = v.getNext()) nodes.add(v); } else nodes.addAll(viewer.getSelectedNodes()); for (Node v : nodes) { viewer.setFont(v, font); changed = true; } for (Edge e : viewer.getSelectedEdges()) { viewer.setFont(e, font); changed = true; } if (changed) viewer.repaint(); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { String fontName = ProgramProperties.get("Font", "Arial-PLAIN-12"); fontName = JOptionPane.showInputDialog("Enter font", fontName); if (fontName != null) { execute("set font='" + fontName + "';"); ProgramProperties.put("Font", fontName); } } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set font=<name-style-size>;"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((ViewerBase) getViewer()).getGraph().getNumberOfNodes() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,261
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetNodeSizeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetNodeSizeCommand.java
/* * SetNodeSizeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * set size * Daniel Huson, 4.2011 */ public class SetNodeSizeCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Node Size"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the size of selected nodes"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set nodeSize="); int width = np.getInt(0, 1000); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Node v : viewer.getSelectedNodes()) { viewer.setHeight(v, width); viewer.setWidth(v, width); changed = true; } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Integer[] choices = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 40}; Integer result = (Integer) JOptionPane.showInputDialog(getViewer().getFrame(), "Set node size", "Set node size", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choices[1]); if (result != null) execute("set nodeSize=" + result + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set nodeSize=<integer>;"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && ((GraphView) getViewer()).getSelectedNodes().size() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,967
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GroupSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/GroupSamplesByCommand.java
/* * GroupSamplesByCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; 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.core.Director; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Optional; /** * * group by command * * Daniel Huson, 9.2105 */ public class GroupSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return "groupBy attribute=<name>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("groupBy attribute="); final String attribute = np.getWordRespectCase(); np.matchIgnoreCase(";"); final Document doc = ((Director) getDir()).getDocument(); java.util.Collection<String> samples; if (getViewer() instanceof SamplesViewer) { samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples(); } else samples = doc.getSampleAttributeTable().getSampleSet(); ProgramProperties.put("SetByAttribute", attribute); for (String sample : samples) { Object value = doc.getSampleAttributeTable().get(sample, attribute); if (value == null || value.equals("NA")) doc.getSampleAttributeTable().putGroupId(sample, null); else { doc.getSampleAttributeTable().putGroupId(sample, attribute + "=" + value); doc.setDirty(true); } } } public void actionPerformed(ActionEvent event) { final Document doc = ((Director) getDir()).getDocument(); final java.util.List<String> attributes = doc.getSampleAttributeTable().getUnhiddenAttributes(); if (attributes.size() > 0) { final JFrame frame = getViewer().getFrame(); Platform.runLater(() -> { String defaultChoice = ProgramProperties.get("SetByAttribute", ""); if (!attributes.contains(defaultChoice)) defaultChoice = attributes.get(0); ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, attributes); dialog.setTitle("MEGAN6 " + getViewer().getClassName() + " choice"); dialog.setHeaderText("Select attribute to group by"); dialog.setContentText("Choose attribute:"); if (frame != null) { dialog.setX(frame.getX() + (frame.getWidth() - 200) / 2); dialog.setY(frame.getY() + (frame.getHeight() - 200) / 2); } final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String choice = result.get(); SwingUtilities.invokeLater(() -> execute("groupBy attribute='" + choice + "';show window=groups;")); } }); } } public boolean isApplicable() { Document doc = ((Director) getDir()).getDocument(); return doc.getSampleAttributeTable().getNumberOfUnhiddenAttributes() > 0; } public String getName() { return "Group Samples By Attribute"; } public String getDescription() { return "Group samples by selected attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("JoinNodes16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
4,584
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetSampleColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetSampleColorCommand.java
/* * SetSampleColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.LinkedList; /** * * selection command * * Daniel Huson, 11.2010 */ public class SetSampleColorCommand extends CommandBase implements ICommand { public String getSyntax() { return "set nodeColor=<color> [sample=<name ...>];"; } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set nodeColor="); final Color color = ColorUtilsSwing.convert(np.getColor()); final java.util.List<String> samples = new LinkedList<>(); if (np.peekMatchIgnoreCase("sample=")) { np.matchIgnoreCase("sample="); while (!np.peekMatchIgnoreCase(";")) { samples.add(np.getWordRespectCase()); } } np.matchIgnoreCase(";"); final Document doc = ((Director) getDir()).getDocument(); if (samples.size() == 0) samples.addAll(doc.getSampleSelection().getAll()); if (samples.size() > 0) { for (String sample : samples) { doc.getSampleAttributeTable().putSampleColor(sample, color); } doc.setDirty(true); } } public void actionPerformed(ActionEvent event) { final Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose sample color", ProgramProperties.get("NodeFillColor", Color.WHITE)); if (color != null) { execute("set nodeColor=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + ";"); ProgramProperties.put("NodeFillColor", color); } } public boolean isApplicable() { final Document doc = ((Director) getDir()).getDocument(); return doc.getSampleSelection().size() > 0; } public String getName() { return "Set Color..."; } public String getDescription() { return "Set node color"; } public ImageIcon getIcon() { return ResourceManager.getIcon("YellowSquare16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
3,465
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetEdgeShapeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetEdgeShapeCommand.java
/* * SetEdgeShapeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.EdgeView; import jloda.swing.graphview.GraphView; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * set shape * Daniel Huson, 4.2011 */ public class SetEdgeShapeCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Edge Shape"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the shape of selected edges"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set edgeShape="); String shapeName = np.getWordMatchesIgnoringCase("angular straight curved none"); np.matchIgnoreCase(";"); byte shape; if (shapeName.equalsIgnoreCase("angular")) shape = EdgeView.ARC_LINE_EDGE; else if (shapeName.equalsIgnoreCase("straight")) shape = EdgeView.STRAIGHT_EDGE; else if (shapeName.equalsIgnoreCase("curved")) shape = EdgeView.QUAD_EDGE; else shape = 0; if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Edge e : viewer.getSelectedEdges()) { viewer.setShape(e, shape); changed = true; } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { String[] choices = new String[]{"angular", "straight", "curved", "none"}; String result = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Set edge shape", "Set edge shape", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choices[0]); if (result != null) execute("set edgeShape=" + result + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set edgeShape={angular|straight|curved};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && ((GraphView) getViewer()).getSelectedEdges().size() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,381
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IncreaseFontCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/IncreaseFontCommand.java
/* * IncreaseFontCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ProgramProperties; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import megan.clusteranalysis.ClusterViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * set size * Daniel Huson, 4.2011 */ public class IncreaseFontCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Increase Font Size"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the font size"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set fontSize="); String input = np.getWordRespectCase(); np.matchIgnoreCase(";"); int newSize = 0; boolean increase = false; boolean decrease = false; if (NumberUtils.isInteger(input) && Integer.parseInt(input) >= 0) newSize = Integer.parseInt(input); else if (input.equalsIgnoreCase("increase")) increase = true; else if (input.equalsIgnoreCase("decrease")) decrease = true; else throw new IOException("Illegal font size: " + input); boolean changed = false; final GraphView viewer; if (getViewer() instanceof ClusterViewer) viewer = ((ClusterViewer) getViewer()).getGraphView(); else if (getViewer() instanceof GraphView) viewer = (GraphView) getViewer(); else return; final Set<Node> nodes = new HashSet<>(); if (viewer.getSelectedNodes().size() == 0 && viewer.getSelectedEdges().size() == 0) { for (Node v = viewer.getGraph().getFirstNode(); v != null; v = v.getNext()) nodes.add(v); } else nodes.addAll(viewer.getSelectedNodes()); for (Node v : nodes) { if (viewer.getLabel(v) != null) { Font font = viewer.getFont(v); int size = font.getSize(); if (increase) { size = Math.max(size + 1, (int) (size * 1.1)); } else if (decrease) { if (size >= 2) size = Math.max(1, Math.min(size - 1, (int) (size / 1.1))); } else { size = newSize; } if (size != font.getSize()) { font = new Font(font.getFamily(), font.getStyle(), size); viewer.setFont(v, font); ProgramProperties.put(ProgramProperties.DEFAULT_FONT, font.getFamily(), font.getStyle(), size > 0 ? size : 6); changed = true; } } } for (Edge e : viewer.getSelectedEdges()) { if (viewer.getLabel(e) != null) { Font font = viewer.getFont(e); int size = font.getSize(); if (increase) { size = Math.max(size + 1, (int) (size * 1.2)); } else if (decrease) { if (size >= 2) size = Math.max(1, Math.min(size - 1, (int) (size / 1.1))); } else { size = newSize; } if (size != font.getSize()) { font = new Font(font.getFamily(), font.getStyle(), size); viewer.setFont(e, font); ProgramProperties.put(ProgramProperties.DEFAULT_FONT, font.getFamily(), font.getStyle(), size > 0 ? size : 6); changed = true; } } } if (changed) viewer.repaint(); } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set fontSize=increase;"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set fontSize={<number>|increase|decrease};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { if (getViewer() instanceof ViewerBase) return ((ViewerBase) getViewer()).getGraph().getNumberOfNodes() > 0; else return getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getGraphView() != null && ((ClusterViewer) getViewer()).getGraphView().getGraph().getNumberOfNodes() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
6,728
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawTrianglesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DrawTrianglesCommand.java
/* * DrawTrianglesCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw selected nodes as triangles * Daniel Huson, 3.2013 */ public class DrawTrianglesCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((Director) getDir()).getDocument().getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Triangle"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Triangle node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueTriangle16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set nodeShape=triangle;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
2,972
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LabelSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/LabelSamplesByCommand.java
/* * LabelSamplesByCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; 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.core.Director; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Optional; /** * * label by command * * Daniel Huson, 9.2105 */ public class LabelSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return "labelBy attribute=<name> [samples={selected|all}];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("labelBy attribute="); final String attribute = np.getWordRespectCase(); final boolean selected; if (np.peekMatchIgnoreCase("samples")) { np.matchIgnoreCase("samples="); selected = np.getWordMatchesIgnoringCase("selected all").equalsIgnoreCase("selected"); } else selected = true; np.matchIgnoreCase(";"); final Document doc = ((Director) getDir()).getDocument(); java.util.Collection<String> samples; if (selected && getViewer() instanceof SamplesViewer) { samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples(); } else samples = doc.getSampleAttributeTable().getSampleSet(); ProgramProperties.put("SetByAttribute", attribute); for (String sample : samples) { Object value = doc.getSampleAttributeTable().get(sample, attribute); if (value != null) { doc.getSampleAttributeTable().putSampleLabel(sample, value.toString()); doc.setDirty(true); } } } public void actionPerformed(ActionEvent event) { final Document doc = ((Director) getDir()).getDocument(); final java.util.List<String> attributes = doc.getSampleAttributeTable().getUnhiddenAttributes(); if (attributes.size() > 0) { final JFrame frame = getViewer().getFrame(); Platform.runLater(() -> { String defaultChoice = ProgramProperties.get("SetByAttribute", ""); if (!attributes.contains(defaultChoice)) defaultChoice = attributes.get(0); ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, attributes); dialog.setTitle("MEGAN6 " + getViewer().getClassName() + " choice"); dialog.setHeaderText("Select attribute to label by"); dialog.setContentText("Choose attribute:"); if (frame != null) { dialog.setX(frame.getX() + (frame.getWidth() - 200) / 2); dialog.setY(frame.getY() + (frame.getHeight() - 200) / 2); } final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String choice = result.get(); SwingUtilities.invokeLater(() -> execute("labelBy attribute='" + choice + "';")); } }); } } public boolean isApplicable() { Document doc = ((Director) getDir()).getDocument(); return doc.getSampleAttributeTable().getNumberOfUnhiddenAttributes() > 0; } public String getName() { return "Label Samples By Attribute"; } public String getDescription() { return "Label samples by selected attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Labels16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
4,752
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DecreaseFontCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DecreaseFontCommand.java
/* * DecreaseFontCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.clusteranalysis.ClusterViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * set size * Daniel Huson, 4.2011 */ public class DecreaseFontCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Decrease Font Size"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Decrease the font size"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * parses the given command and executes it */ public void apply(NexusStreamParser np) { } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set fontSize=decrease;"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return null; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { if (getViewer() instanceof ViewerBase) return ((ViewerBase) getViewer()).getGraph().getNumberOfNodes() > 0; else return getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getGraphView() != null && ((ClusterViewer) getViewer()).getGraphView().getGraph().getNumberOfNodes() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,371
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShapeSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/ShapeSamplesByCommand.java
/* * ShapeSamplesByCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.NodeShape; import jloda.util.Pair; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * * shape by command * * Daniel Huson, 9.2105 */ public class ShapeSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return "shapeBy attribute=<name>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("shapeBy attribute="); String attribute = np.getWordRespectCase(); Document doc = ((Director) getDir()).getDocument(); java.util.Collection<String> samples; if (getViewer() instanceof SamplesViewer) { samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples(); } else samples = doc.getSampleAttributeTable().getSampleSet(); ProgramProperties.put("SetByAttribute", attribute); Map<String, Integer> value2Count = new HashMap<>(); for (String sample : samples) { Object value = doc.getSampleAttributeTable().get(sample, attribute); if (value != null) { value2Count.merge(value.toString(), 1, Integer::sum); } } Pair<Integer, String>[] pairs = new Pair[value2Count.size()]; int i = 0; for (String value : value2Count.keySet()) { pairs[i++] = new Pair<>(value2Count.get(value), value); } Arrays.sort(pairs, (p1, p2) -> -p1.compareTo(p2)); Map<String, NodeShape> value2shape = new HashMap<>(); int count = 0; for (Pair<Integer, String> pair : pairs) { value2shape.put(pair.getSecond(), NodeShape.values()[Math.min(++count, NodeShape.values().length - 1)]); } StringBuilder buf = new StringBuilder(); for (String value : value2shape.keySet()) { boolean first = true; for (String sample : samples) { Object aValue = doc.getSampleAttributeTable().get(sample, attribute); if (aValue != null && aValue.toString().equals(value)) { if (first) { buf.append("set nodeShape=").append(value2shape.get(value)).append(" sample="); first = false; } buf.append(" '").append(sample).append("'"); } } if (!first) buf.append(";"); } executeImmediately(buf.toString()); } public void actionPerformed(ActionEvent event) { final Document doc = ((Director) getDir()).getDocument(); final java.util.List<String> attributes = doc.getSampleAttributeTable().getUnhiddenAttributes(); if (attributes.size() > 0) { final JFrame frame = getViewer().getFrame(); Platform.runLater(() -> { String defaultChoice = ProgramProperties.get("SetByAttribute", ""); if (!attributes.contains(defaultChoice)) defaultChoice = attributes.get(0); ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, attributes); dialog.setTitle("MEGAN6 " + getViewer().getClassName() + " choice"); dialog.setHeaderText("Select attribute to shape by"); dialog.setContentText("Choose attribute:"); if (frame != null) { dialog.setX(frame.getX() + (frame.getWidth() - 200) / 2); dialog.setY(frame.getY() + (frame.getHeight() - 200) / 2); } final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String choice = result.get(); SwingUtilities.invokeLater(() -> execute("shapeBy attribute='" + choice + "';")); } }); } } public boolean isApplicable() { Document doc = ((Director) getDir()).getDocument(); return doc.getSampleAttributeTable().getNumberOfUnhiddenAttributes() > 0; } public String getName() { return "Shape Samples By Attribute"; } public String getDescription() { return "Shape samples by selected attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Circle16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
5,822
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetEdgeWidthCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetEdgeWidthCommand.java
/* * SetEdgeWidthCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.event.ActionEvent; /** * set shape * Daniel Huson, 4.2011 */ public class SetEdgeWidthCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Edge Width"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the width of selected edges"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set edgeWidth="); int width = np.getInt(0, 1000); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Edge e : viewer.getSelectedEdges()) { viewer.setLineWidth(e, width); changed = true; } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Integer[] choices = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 40}; Integer result = (Integer) JOptionPane.showInputDialog(getViewer().getFrame(), "Set edge width", "Set edge width", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choices[1]); if (result != null) execute("set edgeWidth=" + result + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set edgeWidth=<integer>;"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && ((GraphView) getViewer()).getSelectedEdges().size() > 0; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
3,938
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetLabelFillColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetLabelFillColorCommand.java
/* * SetLabelFillColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * set color * Daniel Huson, 4.2011 */ public class SetLabelFillColorCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Label Fill Color"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the label color of selected nodes and edges"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set labelFillColor="); Color color = null; if (np.peekMatchIgnoreCase("null")) np.matchIgnoreCase("null"); else color = ColorUtilsSwing.convert(np.getColor()); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Node v : viewer.getSelectedNodes()) { if (viewer.isLabelVisible(v)) { viewer.setLabelBackgroundColor(v, color); changed = true; } } for (Edge edge : viewer.getSelectedEdges()) { if (viewer.isLabelVisible(edge)) { viewer.setLabelBackgroundColor(edge, color); changed = true; } } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose label fill color", null); if (color != null) execute("set labelFillColor=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set labelFillColor={<color>|null};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && (((GraphView) getViewer()).getSelectedNodes().size() > 0 || ((GraphView) getViewer()).getSelectedEdges().size() > 0); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,502
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DrawSquaresCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/DrawSquaresCommand.java
/* * DrawSquaresCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import javax.swing.*; import java.awt.event.ActionEvent; /** * draw selected nodes as squares * Daniel Huson, 3.2013 */ public class DrawSquaresCommand extends CommandBase implements ICommand { /** * apply */ public void apply(NexusStreamParser np) { } /** * get command-line usage description * * @return usage */ public String getSyntax() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return ((Director) getDir()).getDocument().getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Square"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Square node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueSquare16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { execute("set nodeShape=square;"); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
2,958
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetLabelColorCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetLabelColorCommand.java
/* * SetLabelColorCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.graph.Edge; import jloda.graph.Node; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.GraphView; import jloda.swing.util.ChooseColorDialog; import jloda.swing.util.ColorUtilsSwing; import jloda.util.parse.NexusStreamParser; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * set color * Daniel Huson, 4.2011 */ public class SetLabelColorCommand extends CommandBase implements ICommand { /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Label Color"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the label color of selected nodes and edges"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set labelColor="); Color color = null; if (np.peekMatchIgnoreCase("null")) np.matchIgnoreCase("null"); else color = ColorUtilsSwing.convert(np.getColor()); np.matchIgnoreCase(";"); if (getViewer() instanceof GraphView) { boolean changed = false; GraphView viewer = (GraphView) getViewer(); for (Node v : viewer.getSelectedNodes()) { if (viewer.isLabelVisible(v)) { viewer.setLabelColor(v, color); changed = true; } } for (Edge edge : viewer.getSelectedEdges()) { if (viewer.isLabelVisible(edge)) { viewer.setLabelColor(edge, color); changed = true; } } if (changed) { viewer.repaint(); } } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { Color color = ChooseColorDialog.showChooseColorDialog(getViewer().getFrame(), "Choose label color", null); if (color != null) execute("set labelColor=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + ";"); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set labelColor={<color>|null};"; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return getViewer() instanceof GraphView && (((GraphView) getViewer()).getSelectedNodes().size() > 0 || ((GraphView) getViewer()).getSelectedEdges().size() > 0); } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,452
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSamplesByCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/ColorSamplesByCommand.java
/* * ColorSamplesByCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import javafx.application.Platform; import javafx.scene.control.ChoiceDialog; 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.core.Director; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.samplesviewer.SamplesViewer; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Optional; /** * * color by command * * Daniel Huson, 9.2105 */ public class ColorSamplesByCommand extends CommandBase implements ICommand { public String getSyntax() { return "colorBy attribute=<name>;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("colorBy attribute="); final String attribute = np.getWordRespectCase(); final Document doc = ((Director) getDir()).getDocument(); final java.util.Collection<String> samples; if (getViewer() instanceof SamplesViewer) { samples = ((SamplesViewer) getViewer()).getSamplesTableView().getSelectedSamples(); } else samples = doc.getSampleAttributeTable().getSampleSet(); ProgramProperties.put("SetByAttribute", attribute); if (doc.getChartColorManager().isColorByPosition()) { final ArrayList<String> states = new ArrayList<>(); for (String sample : samples) { final Object value = doc.getSampleAttributeTable().get(sample, attribute); if (value != null && !value.equals("NA")) states.add(value.toString()); } doc.getChartColorManager().setAttributeStateColorPositions(attribute, states); } if (attribute.equals(SampleAttributeTable.SAMPLE_ID)) { for (String sample : samples) { doc.getSampleAttributeTable().putSampleColor(sample, null); } } else { for (String sample : samples) { final Object value = doc.getSampleAttributeTable().get(sample, attribute); final Color color = (value != null ? doc.getChartColorManager().getAttributeStateColor(attribute, value.toString()) : Color.WHITE); doc.getSampleAttributeTable().putSampleColor(sample, color); } } doc.getChartColorManager().setColorByPosition(false); doc.setDirty(true); } public void actionPerformed(ActionEvent event) { final Document doc = ((Director) getDir()).getDocument(); final java.util.List<String> attributes = doc.getSampleAttributeTable().getUnhiddenAttributes(); if (attributes.size() > 0) { final JFrame frame = getViewer().getFrame(); Platform.runLater(() -> { String defaultChoice = ProgramProperties.get("SetByAttribute", ""); if (!attributes.contains(defaultChoice)) defaultChoice = attributes.get(0); final ChoiceDialog<String> dialog = new ChoiceDialog<>(defaultChoice, attributes); dialog.setTitle("MEGAN6 " + getViewer().getClassName() + " choice"); dialog.setHeaderText("Select attribute to color by"); dialog.setContentText("Choose attribute:"); if (frame != null) { dialog.setX(frame.getX() + (frame.getWidth() - 200) / 2); dialog.setY(frame.getY() + (frame.getHeight() - 200) / 2); } final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String choice = result.get(); SwingUtilities.invokeLater(() -> execute("colorBy attribute='" + choice + "';")); } }); } } public boolean isApplicable() { Document doc = ((Director) getDir()).getDocument(); return doc.getSampleAttributeTable().getNumberOfUnhiddenAttributes() > 0; } private static final String NAME = "Color Samples By Attribute"; public String getName() { return NAME; } public String getDescription() { return "Color samples by selected attribute"; } public ImageIcon getIcon() { return ResourceManager.getIcon("YellowSquare16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
5,436
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetNodeShapeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/format/SetNodeShapeCommand.java
/* * SetNodeShapeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.format; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.graphview.NodeShapeIcon; import jloda.swing.util.ResourceManager; import jloda.util.NodeShape; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.core.Document; import megan.util.CallBack; import megan.util.PopupChoice; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.LinkedList; import java.util.List; /** * draw selected nodes as circles * Daniel Huson, 3.2013 */ public class SetNodeShapeCommand extends CommandBase implements ICommand { /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set nodeShape={" + StringUtils.toString(NodeShape.values(), "|") + "} sample=<name name...>;"; } /** * apply */ public void apply(NexusStreamParser np) throws Exception { final Document doc = ((Director) getDir()).getDocument(); np.matchIgnoreCase("set nodeShape="); String shape = np.getWordMatchesIgnoringCase(StringUtils.toString(NodeShape.values(), " ")); final List<String> samples = new LinkedList<>(); if (np.peekMatchIgnoreCase("sample=")) { np.matchIgnoreCase("sample="); while (!np.peekMatchIgnoreCase(";")) { samples.add(np.getWordRespectCase()); } } np.matchIgnoreCase(";"); if (samples.size() == 0) samples.addAll(doc.getSampleSelection().getAll()); if (samples.size() > 0) { for (String sample : samples) { doc.getSampleAttributeTable().putSampleShape(sample, shape); } ((Director) getDir()).getDocument().setDirty(true); } } /** * action to be performed * */ public void actionPerformed(ActionEvent ev) { final Icon[] icons = new Icon[NodeShape.values().length]; for (int i = 0; i < NodeShape.values().length; i++) { icons[i] = new NodeShapeIcon(NodeShape.values()[i], 12, new Color(0, 174, 238)); } PopupChoice<NodeShape> popupChoice = new PopupChoice<>(NodeShape.values(), null, icons, new CallBack<>() { @Override public void call(NodeShape choice) { execute("set nodeShape=" + choice.toString() + ";"); } }); popupChoice.showAtCurrentMouseLocation(getViewer().getFrame()); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } public boolean isApplicable() { final Document doc = ((Director) getDir()).getDocument(); return doc.getSampleSelection().size() > 0; } /** * get the name to be used as a menu label * * @return name */ public String getName() { return "Set Node Shape..."; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the node shape"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("BlueTriangle16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * gets the command needed to undo this command * * @return undo command */ public String getUndo() { return null; } }
4,644
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ListDisabledCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/mapping/ListDisabledCommand.java
/* * ListDisabledCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.mapping; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Set; public class ListDisabledCommand extends CommandBase implements ICommand { public String getSyntax() { return "list taxa=disabled;"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final Set<Integer> disabledTopLevelTaxa = TaxonomyData.getDisabledInternalTaxa(); System.out.printf("Total disabled taxa:%,12d%n", TaxonomyData.getDisabledTaxa().size()); System.out.printf("Disabled top-level taxa:%,8d%n", TaxonomyData.getDisabledInternalTaxa().size()); for (Integer taxId : disabledTopLevelTaxa) { String taxName = TaxonomyData.getName2IdMap().get(taxId); System.out.println("[" + taxId + "] " + taxName); } } public void actionPerformed(ActionEvent event) { executeImmediately("show window=message;"); execute(getSyntax()); } public boolean isApplicable() { return getViewer() instanceof MainViewer; } public String getName() { return "List Disabled..."; } public String getDescription() { return "List all disabled taxa"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
2,385
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
EnableAllTaxaCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/mapping/EnableAllTaxaCommand.java
/* * EnableAllTaxaCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.mapping; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.event.ActionEvent; public class EnableAllTaxaCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("enable taxa=all;"); } public boolean isApplicable() { return getViewer() instanceof MainViewer && !getDoc().getMeganFile().isReadOnly(); } public String getName() { return "Enable All"; } public String getDescription() { return "Enable taxa"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
1,741
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
EnableTaxaCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/mapping/EnableTaxaCommand.java
/* * EnableTaxaCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.mapping; import jloda.graph.Node; import jloda.graph.NodeSet; import jloda.swing.commands.ICommand; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; public class EnableTaxaCommand extends CommandBase implements ICommand { public String getSyntax() { return "enable taxa={selected|all|<name,...>};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("enable taxa="); String name = np.getWordRespectCase(); final MainViewer viewer = (MainViewer) getViewer(); if (name.equalsIgnoreCase("selected")) { np.matchIgnoreCase(";"); NodeSet selected = viewer.getSelectedNodes(); for (Node v : selected) { int taxId = (Integer) v.getInfo(); if (taxId > 0) { TaxonomyData.getDisabledInternalTaxa().remove(taxId); } } TaxonomyData.getDisabledTaxa().clear(); TaxonomyData.setDisabledInternalTaxa(TaxonomyData.getDisabledInternalTaxa()); } else if (name.equalsIgnoreCase("all")) { np.matchIgnoreCase(";"); TaxonomyData.getDisabledTaxa().clear(); TaxonomyData.getDisabledInternalTaxa().clear(); } else { while (!name.equals(";")) { int taxonId = NumberUtils.isInteger(name) ? Integer.parseInt(name) : TaxonomyData.getName2IdMap().get(name); if (taxonId > 0) TaxonomyData.getDisabledTaxa().remove(taxonId); if (np.peekMatchIgnoreCase(",")) { np.matchIgnoreCase(","); } name = np.getWordRespectCase(); } } System.err.println("Disabled taxa: " + TaxonomyData.getDisabledTaxa().size()); viewer.setDoReInduce(true); } public void actionPerformed(ActionEvent event) { final MainViewer viewer = (MainViewer) getViewer(); if (viewer.getSelectedNodes().size() > 0) { execute("enable taxa=selected;"); } else { String input = JOptionPane.showInputDialog(viewer.getFrame(), "Enter names or IDs of taxa to enable"); if (input != null) { StringBuilder buffer = new StringBuilder(); String[] names = input.split(","); boolean first = true; for (String name : names) { name = name.trim(); int taxonId = NumberUtils.isInteger(name) ? Integer.parseInt(name) : TaxonomyData.getName2IdMap().get(name); if (taxonId <= 0) { NotificationsInSwing.showError(viewer.getFrame(), "Unknown taxon: " + name); return; } if (first) first = false; else buffer.append(", "); buffer.append("'").append(name).append("'"); } execute("enable taxa=" + buffer + ";"); } } } public boolean isApplicable() { return getViewer() instanceof MainViewer && !getDoc().getMeganFile().isReadOnly(); } public String getName() { return "Enable..."; } public String getDescription() { return "Enable all selected taxa or all named ones"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
4,592
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DisableTaxaCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/mapping/DisableTaxaCommand.java
/* * DisableTaxaCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.mapping; import jloda.graph.Node; import jloda.graph.NodeSet; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.main.MeganProperties; import megan.viewer.MainViewer; import megan.viewer.TaxonomyData; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Set; public class DisableTaxaCommand extends CommandBase implements ICommand { public String getSyntax() { return "disable taxa={default|selected|<name,...>};"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("disable taxa="); final MainViewer viewer = getDir().getMainViewer(); final Set<Integer> disabledInternalIds = TaxonomyData.getDisabledInternalTaxa(); String name = np.getWordRespectCase(); if (name.equalsIgnoreCase("default")) { TaxonomyData.getDisabledTaxa().clear(); for (int t : MeganProperties.DISABLED_TAXA_DEFAULT) { disabledInternalIds.add(t); } np.matchIgnoreCase(";"); } else if (name.equalsIgnoreCase("selected")) { NodeSet selected = viewer.getSelectedNodes(); for (Node v : selected) { int taxId = (Integer) v.getInfo(); if (taxId > 0) disabledInternalIds.add(taxId); } np.matchIgnoreCase(";"); } else { while (!name.equals(";")) { int taxonId = NumberUtils.isInteger(name) ? Integer.parseInt(name) : TaxonomyData.getName2IdMap().get(name); if (taxonId > 0) disabledInternalIds.add(taxonId); if (np.peekMatchIgnoreCase(",")) { np.matchIgnoreCase(","); } name = np.getWordRespectCase(); } } TaxonomyData.getDisabledTaxa().clear(); TaxonomyData.setDisabledInternalTaxa(disabledInternalIds); ProgramProperties.put(MeganProperties.DISABLED_TAXA, StringUtils.toString(TaxonomyData.getDisabledInternalTaxa(), " ")); System.err.println("Total disabled taxa: " + TaxonomyData.getDisabledTaxa().size()); viewer.setDoReInduce(true); } public void actionPerformed(ActionEvent event) { final MainViewer viewer = (MainViewer) getViewer(); if (viewer.getSelectedNodes().size() > 0) { execute("disable taxa=selected;"); } else { if (viewer.getSelectedNodes().size() == 0) { String input = JOptionPane.showInputDialog(viewer.getFrame(), "Enter names or IDs of taxa to disable"); if (input != null) { StringBuilder buffer = new StringBuilder(); String[] names = input.split(","); boolean first = true; for (String name : names) { name = name.trim(); int taxonId = NumberUtils.isInteger(name) ? Integer.parseInt(name) : TaxonomyData.getName2IdMap().get(name); if (taxonId <= 0) { NotificationsInSwing.showWarning(viewer.getFrame(), "Unknown taxon: " + name); continue; } if (first) first = false; else buffer.append(", "); buffer.append("'").append(name).append("'"); } execute("disable taxa=" + buffer + ";"); } } } } public boolean isApplicable() { return getViewer() instanceof MainViewer && !getDoc().getMeganFile().isReadOnly(); } public String getName() { return "Disable..."; } public String getDescription() { return "Disable all selected taxa or all named ones"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
5,098
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DisableDefaultTaxaCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/commands/mapping/DisableDefaultTaxaCommand.java
/* * DisableDefaultTaxaCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.commands.mapping; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.event.ActionEvent; public class DisableDefaultTaxaCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("show window=message;disable taxa=default;list taxa=disabled;"); } public boolean isApplicable() { return getViewer() instanceof MainViewer && !getDoc().getMeganFile().isReadOnly(); } public String getName() { return "Disable Default"; } public String getDescription() { return "Reset disabling to default value, ignoring a lot of unclassified taxa"; } public ImageIcon getIcon() { return null; } public boolean isCritical() { return true; } }
1,858
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6Connector.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6Connector.java
/* * RMA6Connector.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.CanceledException; import jloda.util.ListOfLongs; import jloda.util.Single; import jloda.util.progress.ProgressListener; import megan.data.*; import java.io.File; import java.io.IOException; import java.util.*; /** * RMA6 connector * Created by huson on 2.2015 */ public class RMA6Connector implements IConnector { private String fileName; public static boolean reuseReadBlockInGetter=true; /** * constructor * */ public RMA6Connector(String fileName) throws IOException { setFile(fileName); } @Override public String getFilename() { return fileName; } @Override public void setFile(String file) { this.fileName = file; } @Override public boolean isReadOnly() { return fileName != null && ((new File(fileName)).canWrite()); } @Override public long getUId() throws IOException { try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { return rma6File.getHeaderSectionRMA6().getCreationDate(); } } @Override public IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { final RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY); return new AllReadsIteratorRMA6(wantReadSequence, wantMatches, rma6File, minScore, maxExpected); } @Override public IReadBlockIterator getReadsIterator(String classification, int classId, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return getReadsIteratorForListOfClassIds(classification, Collections.singletonList(classId), minScore, maxExpected, wantReadSequence, wantMatches); } @Override public IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { try (final RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { final ClassificationBlockRMA6 block = new ClassificationBlockRMA6(classification); final long start = rma6File.getFooterSectionRMA6().getStartClassification(classification); block.read(start, rma6File.getReader()); final ListOfLongs list = new ListOfLongs(); for (Integer classId : classIds) { if (block.getSum(classId) > 0) { block.readLocations(start, rma6File.getReader(), classId, list); } } return new ReadBlockIterator(list.iterator(), list.size(), getReadBlockGetter(minScore, maxExpected, wantReadSequence, wantMatches)); } } @Override public IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { final RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY); return new ReadBlockGetterRMA6(rma6File, wantReadSequence, wantMatches, minScore, maxExpected, false, reuseReadBlockInGetter); } @Override public String[] getAllClassificationNames() throws IOException { try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { return rma6File.getHeaderSectionRMA6().getMatchClassNames(); } } @Override public int getClassificationSize(String classificationName) throws IOException { IClassificationBlock classificationBlock = getClassificationBlock(classificationName); return classificationBlock.getKeySet().size(); } @Override public int getClassSize(String classificationName, int classId) throws IOException { IClassificationBlock classificationBlock = getClassificationBlock(classificationName); return classificationBlock.getSum(classId); } @Override public IClassificationBlock getClassificationBlock(String classificationName) throws IOException { try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { final Long location = rma6File.getFooterSectionRMA6().getStartClassification(classificationName); if (location != null) { ClassificationBlockRMA6 classificationBlockRMA6 = new ClassificationBlockRMA6(classificationName); classificationBlockRMA6.read(location, rma6File.getReader()); return classificationBlockRMA6; } } return null; } /** * rescan classifications after running the data processor * */ @Override public void updateClassifications(String[] cNames, List<UpdateItem> updateItemList, ProgressListener progressListener) throws IOException, CanceledException { final UpdateItemList updateItems = (UpdateItemList) updateItemList; long maxProgress = 0; for (int i = 0; i < cNames.length; i++) { maxProgress += updateItems.getClassIds(i).size(); } progressListener.setMaximum(maxProgress); final Map<Integer, ListOfLongs>[] fName2ClassId2Location = new HashMap[cNames.length]; final Map<Integer, Float>[] fName2ClassId2Weight = new HashMap[cNames.length]; final Map<Integer, Integer>[] fName2ClassId2Count = new HashMap[cNames.length]; for (int i = 0; i < cNames.length; i++) { fName2ClassId2Location[i] = new HashMap<>(10000); fName2ClassId2Weight[i] = new HashMap<>(10000); fName2ClassId2Weight[i] = new HashMap<>(10000); } for (int i = 0; i < cNames.length; i++) { final Map<Integer, ListOfLongs> classId2Location = fName2ClassId2Location[i]; final Map<Integer, Float> classId2weight = fName2ClassId2Weight[i]; for (Integer classId : updateItems.getClassIds(i)) { float weight = updateItems.getWeight(i, classId); classId2weight.put(classId, weight); final ListOfLongs positions = new ListOfLongs(); classId2Location.put(classId, positions); if (updateItems.getWeight(i, classId) > 0) { for (UpdateItem item = updateItems.getFirst(i, classId); item != null; item = item.getNextInClassification(i)) { positions.add(item.getReadUId()); } } progressListener.incrementProgress(); } } try (RMA6FileModifier rma6Modifier = new RMA6FileModifier(fileName)) { rma6Modifier.updateClassifications(cNames, fName2ClassId2Location, fName2ClassId2Weight); } } @Override public IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException { return new FindAllReadsIterator(regEx, findSelection, getAllReadsIterator(0, 10, true, true), canceled); } @Override public int getNumberOfReads() throws IOException { try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { return (int) Math.min(Integer.MAX_VALUE, rma6File.getFooterSectionRMA6().getNumberOfReads()); } } @Override public int getNumberOfMatches() throws IOException { try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { return (int) Math.min(Integer.MAX_VALUE, rma6File.getFooterSectionRMA6().getNumberOfMatches()); } } @Override public void setNumberOfReads(int numberOfReads) { } @Override public void putAuxiliaryData(Map<String, byte[]> label2data) throws IOException { try (RMA6FileModifier rma6Modifier = new RMA6FileModifier(fileName)) { rma6Modifier.saveAuxData(label2data); } } @Override public Map<String, byte[]> getAuxiliaryData() throws IOException { final Map<String, byte[]> label2data; try (RMA6File rma6File = new RMA6File(fileName, RMA6File.READ_ONLY)) { label2data = new HashMap<>(rma6File.readAuxBlocks()); } return label2data; } }
9,032
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6FromBlastCreator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6FromBlastCreator.java
/* * RMA6FromBlastCreator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.seq.BlastMode; import jloda.util.*; 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.IdParser; import megan.core.Document; import megan.core.MeganFile; import megan.core.SyncArchiveAndDataTable; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import megan.io.InputOutputReaderWriter; import megan.parsers.blast.BlastFileFormat; import megan.parsers.blast.ISAMIterator; import megan.parsers.blast.IteratorManager; import java.io.IOException; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Creates a new RMA6 file by parsing a blast file * <p> * Daniel Huson, 6.2015 */ public class RMA6FromBlastCreator { private final BlastFileFormat format; private final BlastMode blastMode; private final String[] blastFiles; private final String[] readsFiles; private final String rma6File; private final Document doc; private final int maxMatchesPerRead; private final int taxonMapperIndex; private final IdParser[] parsers; private final String[] cNames; private final boolean pairedReads; private final boolean longReads; private final int pairedReadSuffixLength; private final RMA6FileCreator rma6FileCreator; /** * construct a new creator to create an RMA6 file from a set of BLAST files * */ public RMA6FromBlastCreator(String creator, BlastFileFormat format, BlastMode blastMode, String[] blastFiles, String[] readsFiles, String rma6File, boolean useCompression, Document doc, int maxMatchesPerRead) throws IOException { this.format = format; this.blastMode = blastMode; this.blastFiles = blastFiles; this.readsFiles = readsFiles; this.rma6File = rma6File; this.maxMatchesPerRead = maxMatchesPerRead; this.doc = doc; doc.getMeganFile().setFile(rma6File, MeganFile.Type.RMA6_FILE); if (doc.getActiveViewers().size() > 0) cNames = doc.getActiveViewers().toArray(new String[0]); else cNames = new String[]{Classification.Taxonomy}; this.parsers = new IdParser[cNames.length]; int taxonMapperIndex = -1; System.err.println("Classifications: " + StringUtils.toString(cNames, ", ")); for (int i = 0; i < cNames.length; i++) { parsers[i] = ClassificationManager.get(cNames[i], true).getIdMapper().createIdParser(); if (cNames[i].equals(Classification.Taxonomy)) { taxonMapperIndex = i; } } if (taxonMapperIndex == -1) throw new IOException("Internal error: taxonMapperIndex=-1"); else this.taxonMapperIndex = taxonMapperIndex; this.longReads = doc.isLongReads(); this.pairedReads = doc.isPairedReads(); this.pairedReadSuffixLength = doc.getPairedReadSuffixLength(); // setup the file creator and write the header: rma6FileCreator = new RMA6FileCreator(rma6File, useCompression); final String[] matchClassificationNames = new String[parsers.length]; for (int i = 0; i < parsers.length; i++) matchClassificationNames[i] = parsers[i].getCName(); rma6FileCreator.writeHeader(creator, blastMode, matchClassificationNames, doc.isPairedReads()); } /** * parse the files * */ public void parseFiles(final ProgressListener progress) throws IOException, CanceledException, SQLException { progress.setTasks("Generating RMA6 file", "Parsing matches"); final HashMap<String, Long> read2PairedReadLocation; if (pairedReads) read2PairedReadLocation = new HashMap<>(1000000); else read2PairedReadLocation = null; final byte[] queryName = new byte[100000]; final Single<byte[]> fastAText = new Single<>(new byte[1000]); MatchLineRMA6[] matchLineRMA6s = new MatchLineRMA6[maxMatchesPerRead]; for (int i = 0; i < matchLineRMA6s.length; i++) { matchLineRMA6s[i] = new MatchLineRMA6(cNames.length, taxonMapperIndex); } int[][] match2classification2id = new int[maxMatchesPerRead][cNames.length]; rma6FileCreator.startAddingQueries(); long totalNumberOfReads = 0; long totalNumberOfMatches = 0; // setup use of accession mapping database, if provided final AccessAccessionMappingDatabase accessAccessionMappingDatabase; final int[] mapClassificationId2DatabaseRank; if (ClassificationManager.canUseMeganMapDBFile()) { System.err.println("Annotating RMA6 file using FAST mode (accession database and first accession per line)"); accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(ClassificationManager.getMeganMapDBFile()); mapClassificationId2DatabaseRank = accessAccessionMappingDatabase.setupMapClassificationId2DatabaseRank(cNames); } else { System.err.println("Annotating RMA6 file using EXTENDED mode"); accessAccessionMappingDatabase = null; mapClassificationId2DatabaseRank = null; } try { for (int fileNumber = 0; fileNumber < blastFiles.length; fileNumber++) { int missingReadWarnings = 0; final String blastFile = blastFiles[fileNumber]; progress.setTasks("Parsing file", FileUtils.getFileNameWithoutPath(blastFile)); System.err.println("Parsing file: " + blastFile); final ISAMIterator iterator = IteratorManager.getIterator(blastFile, format, blastMode, maxMatchesPerRead, longReads); progress.setProgress(0); progress.setMaximum(iterator.getMaximumProgress()); final FileLineBytesIterator fastaIterator; final boolean isFasta; if (readsFiles != null && readsFiles.length > fileNumber && FileUtils.fileExistsAndIsNonEmpty(readsFiles[fileNumber])) { fastaIterator = new FileLineBytesIterator(readsFiles[fileNumber]); isFasta = (fastaIterator.peekNextByte() == '>'); if (!isFasta && (fastaIterator.peekNextByte() != '@')) throw new IOException("Cannot determine type of reads file (doesn't start with '>' or '@': " + readsFiles[fileNumber]); } else { fastaIterator = null; isFasta = false; // don't care, won't use } // MAIN LOOP: while (iterator.hasNext()) { totalNumberOfReads++; final int numberOfMatches = iterator.next(); totalNumberOfMatches += numberOfMatches; final byte[] matchesText = iterator.getMatchesText(); // get matches as '\n' separated strings final int matchesTextLength = iterator.getMatchesTextLength(); final int queryNameLength = StringUtils.getFirstWord(matchesText, queryName); //System.err.println("Got: "+Basic.toString(matchesText,Math.min(100,matchesTextLength))); Long mateLocation = null; if (pairedReads) { final String strippedName = StringUtils.toString(queryName, 0, queryNameLength - pairedReadSuffixLength); mateLocation = read2PairedReadLocation.get(strippedName); if (mateLocation == null) { read2PairedReadLocation.put(strippedName, rma6FileCreator.getPosition()); } else { read2PairedReadLocation.remove(strippedName); } } byte[] queryText = null; int queryTextLength = 0; if (fastaIterator != null) { if (Utilities.findQuery(queryName, queryNameLength, fastaIterator, isFasta)) { queryTextLength = Utilities.getFastAText(fastaIterator, isFasta, fastAText); queryText = fastAText.get(); } else { if (missingReadWarnings++ < 50) System.err.println("WARNING: Failed to find read '" + StringUtils.toString(queryName, 0, queryNameLength) + "' in file: " + readsFiles[fileNumber]); if (missingReadWarnings == 50) System.err.println("No further 'failed to find read' warnings..."); } } if (iterator.getQueryText() != null) { queryText = iterator.getQueryText(); queryTextLength = iterator.getQueryText().length; } if (queryText == null) { queryText = queryName; queryTextLength = queryNameLength; } // for each match, write its taxonId and all its functional ids: if (mapClassificationId2DatabaseRank != null) { // use mapping database int offset = 0; final String[] queries = new String[numberOfMatches]; if (numberOfMatches >= matchLineRMA6s.length) { final MatchLineRMA6[] tmp = new MatchLineRMA6[2 * numberOfMatches]; System.arraycopy(matchLineRMA6s, 0, tmp, 0, matchLineRMA6s.length); for (int i = matchLineRMA6s.length; i < tmp.length; i++) { tmp[i] = new MatchLineRMA6(cNames.length, taxonMapperIndex); } matchLineRMA6s = tmp; } if (numberOfMatches >= match2classification2id.length) { match2classification2id = new int[2 * numberOfMatches][cNames.length]; } for (int matchCount = 0; matchCount < numberOfMatches; matchCount++) { queries[matchCount] = getFirstWord(Utilities.getToken(2, matchesText, offset)); final MatchLineRMA6 matchLineRMA6 = matchLineRMA6s[matchCount]; matchLineRMA6.parse(matchesText, offset); offset = Utilities.nextNewLine(matchesText, offset) + 1; } final Map<String, int[]> query2ids = accessAccessionMappingDatabase.getValues(queries, queries.length); for (int matchCount = 0; matchCount < queries.length; matchCount++) { final int[] ids = query2ids.get(queries[matchCount]); if (ids != null) { for (int c = 0; c < cNames.length; c++) { final int dbRank = mapClassificationId2DatabaseRank[c]; if (dbRank < ids.length) { final int id = ids[dbRank]; match2classification2id[matchCount][c] = id; matchLineRMA6s[matchCount].setFId(c, id); } else match2classification2id[matchCount][c] = 0; } } else Arrays.fill(match2classification2id[matchCount], 0); } } else { // use mapping files int offset = 0; for (int matchCount = 0; matchCount < numberOfMatches; matchCount++) { final String refName = Utilities.getToken(2, matchesText, offset); if (matchCount == matchLineRMA6s.length) { // double the array... MatchLineRMA6[] tmp = new MatchLineRMA6[2 * numberOfMatches]; System.arraycopy(matchLineRMA6s, 0, tmp, 0, matchCount); matchLineRMA6s = tmp; for (int i = matchCount; i < matchLineRMA6s.length; i++) matchLineRMA6s[i] = new MatchLineRMA6(cNames.length, taxonMapperIndex); } if (matchCount == match2classification2id.length) { int[][] tmp = new int[2 * numberOfMatches][cNames.length]; System.arraycopy(match2classification2id, 0, tmp, 0, matchCount); match2classification2id = tmp; } final MatchLineRMA6 matchLineRMA6 = matchLineRMA6s[matchCount]; matchLineRMA6.parse(matchesText, offset); for (int i = 0; i < parsers.length; i++) { final int id = parsers[i].getIdFromHeaderLine(refName); match2classification2id[matchCount][i] = id; matchLineRMA6.setFId(i, id); } offset = Utilities.nextNewLine(matchesText, offset) + 1; } } rma6FileCreator.addQuery(queryText, queryTextLength, numberOfMatches, matchesText, matchesTextLength, match2classification2id, mateLocation != null ? mateLocation : 0); progress.setProgress(iterator.getProgress()); } // end of iterator } // end of files } finally { if (accessAccessionMappingDatabase != null) accessAccessionMappingDatabase.close(); } rma6FileCreator.endAddingQueries(); progress.reportTaskCompleted(); System.err.printf("Total reads: %,16d%n", totalNumberOfReads); System.err.printf("Alignments: %,15d%n", totalNumberOfMatches); progress.reportTaskCompleted(); // nothing to write rma6FileCreator.writeClassifications(null, null, null); rma6FileCreator.writeAuxBlocks(null); // zero aux blocks rma6FileCreator.close(); if (pairedReads) { // update paired reads info long count = 0; if (progress instanceof ProgressPercentage) progress.reportTaskCompleted(); try (InputOutputReaderWriter raf = new InputOutputReaderWriter(rma6File, "rw"); IReadBlockIterator it = (new RMA6Connector(rma6File)).getAllReadsIterator(0, 10, false, false)) { progress.setSubtask("Linking paired reads"); progress.setProgress(0); progress.setProgress(it.getMaximumProgress()); while (it.hasNext()) { final IReadBlock readBlock = it.next(); if (readBlock.getMateUId() > 0) { if (readBlock.getMateUId() > readBlock.getUId()) throw new IOException("Mate uid=" + readBlock.getMateUId() + ": too big"); raf.seek(readBlock.getMateUId()); // if defined, mate UID is first number in record, so this is ok raf.writeLong(readBlock.getUId()); count++; } progress.setProgress(it.getProgress()); } System.err.printf("Number of pairs:%,14d%n", count); } } // we need to run data processor to perform classification doc.processReadHits(); // update and then save auxiliary data: final String sampleName = FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(rma6File), ""); SyncArchiveAndDataTable.syncRecomputedArchive2Summary(doc.getReadAssignmentMode(), sampleName, "LCA", doc.getBlastMode(), doc.getParameterString(), new RMA6Connector(rma6File), doc.getDataTable(), 0); doc.saveAuxiliaryData(); } /** * set contaminants * */ public void setContaminants(String contaminantTaxonIdsString) { doc.getDataTable().setContaminants(contaminantTaxonIdsString); } private static String getFirstWord(String string) { int a = 0; while (a < string.length() && (string.charAt(a) == '>' || Character.isWhitespace(string.charAt(a)))) { a++; } int b = a; while (b < string.length() && (string.charAt(b) == '_' || Character.isLetterOrDigit(string.charAt(b)))) { b++; } return string.substring(a, b); } }
17,771
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/MatchBlockRMA6.java
/* * MatchBlockRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.Single; import jloda.util.StringUtils; import megan.classification.Classification; import megan.classification.IdParser; import megan.data.IMatchBlock; import megan.parsers.sam.SAMMatch; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; /** * matchblock for RMA6 * Daniel Huson, 6.2015 */ public class MatchBlockRMA6 implements IMatchBlock { private static long countUids = 0; private static final Object sync = new Object(); private long uid; private float percentIdentity; private String text; private final Map<String, Integer> fName2Id = new HashMap<>(); private SAMMatch samMatch; // major update: we now keep the sam match and only compute text if necessary /** * constructor */ public MatchBlockRMA6() { } /** * set match data from a SAM match * */ public void setFromSAM(SAMMatch samMatch) { text = null; percentIdentity = 0; this.samMatch = samMatch; synchronized (sync) { uid = countUids++; } } /** * erase the block (for reuse) */ public void clear() { samMatch = null; uid = 0; percentIdentity = 0; text = null; fName2Id.clear(); } /** * get the unique identifier for this match (unique within a dataset). * In an RMA file, this is always the file position for the match * * @return uid */ public long getUId() { return uid; } public void setUId(long uid) { this.uid = uid; } /** * get the taxon id of the match * */ public int getTaxonId() { return getId(Classification.Taxonomy); } public void setTaxonId(int taxonId) { setId(Classification.Taxonomy, taxonId); } public int getId(String cName) { Integer id = fName2Id.get(cName); return id != null ? id : 0; } /** * gets all defined ids * * @return ids */ public int[] getIds(String[] cNames) { int[] ids = new int[cNames.length]; for (int i = 0; i < cNames.length; i++) { ids[i] = getId(cNames[i]); } return ids; } public void setId(String cName, Integer id) { fName2Id.put(cName, id); } /** * get the score of the match * */ public float getBitScore() { if (samMatch == null) System.err.println("null"); return samMatch.getBitScore(); } public void setBitScore(float bitScore) { throw new RuntimeException("Not implemented"); } /** * get the percent identity * */ public float getPercentIdentity() { if (text == null) getText(); // percent identity is calculated while creating text return percentIdentity; } public void setPercentIdentity(float percentIdentity) { this.percentIdentity = percentIdentity; } /** * get the refseq id * */ public String getRefSeqId() { return getText() != null ? parseRefSeqId(getText()) : null; } public void setRefSeqId(String refSeqId) { } /** * gets the E-value * */ public void setExpected(float expected) { throw new RuntimeException("Not implemented"); } public float getExpected() { return samMatch.getExpected(); } /** * gets the match length * */ public void setLength(int length) { throw new RuntimeException("Not implemented"); } public int getLength() { return samMatch.getTLength(); } /** * get the ignore status */ @Deprecated public boolean isIgnore() { return false; } /** * set the ignore status */ @Deprecated public void setIgnore(boolean ignore) { } /** * get the text * */ public String getText() { if (text == null) { final Single<Float> value = new Single<>(0f); text = samMatch.getBlastAlignmentText(value); percentIdentity = value.get(); } return text; } @Override public String getTextFirstWord() { return getText() != null ? StringUtils.getFirstWord(getText()) : null; } public void setText(String text) { throw new RuntimeException("Not implemented"); } public String toString() { StringWriter w = new StringWriter(); w.write("Match uid: " + uid + "--------\n"); for (String cName : fName2Id.keySet()) w.write(String.format(" %s: ", cName) + fName2Id.get(cName)); w.write("\n"); if (getBitScore() != 0) w.write("bitScore: " + getBitScore() + "\n"); if (percentIdentity != 0) w.write("percentIdentity: " + getPercentIdentity() + "\n"); if (getExpected() != 0) w.write("expected: " + getExpected() + "\n"); if (getLength() != 0) w.write("length: " + getLength() + "\n"); w.write("text: " + text + "\n"); return w.toString(); } /** * parses a Accession id * * @return refseq id */ private static String parseRefSeqId(String aLine) { int pos = aLine.indexOf(IdParser.REFSEQ_TAG); if (pos != -1) { int start = pos + IdParser.REFSEQ_TAG.length(); int end = start; while (end < aLine.length() && (Character.isLetterOrDigit(aLine.charAt(end)) || aLine.charAt(end) == '_')) end++; if (end > start) return aLine.substring(start, end); } return null; } @Override public int getAlignedQueryStart() { return samMatch.getAlignedQueryStart(); } @Override public int getAlignedQueryEnd() { return samMatch.getAlignedQueryEnd(); } @Override public int getRefLength() { return samMatch.getRefLength(); } }
6,841
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6File.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6File.java
/* * RMA6File.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import megan.io.IInputReader; import megan.io.IInputReaderOutputWriter; import megan.io.InputOutputReaderWriter; import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * read-alignment archive file * Daniel Huson, 6.2015 */ public class RMA6File implements Closeable { public final static int MAGIC_NUMBER = ('R' << 3) | ('M' << 2) | ('A' << 1) | ('R'); public final static int VERSION = 6; public final static int MINOR_VERSION = 0; final public static String READ_ONLY = "r"; final static String READ_WRITE = "rw"; private final HeaderSectionRMA6 headerSectionRMA6; final FooterSectionRMA6 footerSectionRMA6; String fileName; IInputReaderOutputWriter readerWriter; /** * constructor */ public RMA6File() { headerSectionRMA6 = new HeaderSectionRMA6(); footerSectionRMA6 = new FooterSectionRMA6(); } /** * constructor */ public RMA6File(String fileName, String mode) throws IOException { headerSectionRMA6 = new HeaderSectionRMA6(); footerSectionRMA6 = new FooterSectionRMA6(); load(fileName, mode); } /** * load an existing file * */ private void load(String fileName, String mode) throws IOException { this.fileName = fileName; this.readerWriter = new InputOutputReaderWriter(fileName, mode); headerSectionRMA6.read(readerWriter); readerWriter.seek(FooterSectionRMA6.readStartFooterSection(readerWriter)); footerSectionRMA6.read(readerWriter); } /** * close the file * */ public void close() throws IOException { if (readerWriter != null) { readerWriter.close(); readerWriter = null; } } public HeaderSectionRMA6 getHeaderSectionRMA6() { return headerSectionRMA6; } public FooterSectionRMA6 getFooterSectionRMA6() { return footerSectionRMA6; } public IInputReader getReader() { return readerWriter; } /** * reads the aux blocks * * @return aux blocks */ public Map<String, byte[]> readAuxBlocks() throws IOException { final Map<String, byte[]> label2data = new HashMap<>(); readerWriter.seek(footerSectionRMA6.getStartAuxDataSection()); final int count = readerWriter.readInt(); for (int i = 0; i < count && readerWriter.getPosition() < footerSectionRMA6.getEndAuxDataSection(); i++) { String name = readerWriter.readString(); int length = readerWriter.readInt(); byte[] bytes = new byte[length]; readerWriter.read(bytes, 0, length); label2data.put(name, bytes); } return label2data; } /** * write aux blocks * */ public void writeAuxBlocks(Map<String, byte[]> label2data) throws IOException { getFooterSectionRMA6().setStartAuxDataSection(readerWriter.getPosition()); if (label2data == null) readerWriter.writeInt(0); else { readerWriter.writeInt(label2data.size()); // number of aux blocks for (String label : label2data.keySet()) { readerWriter.writeStringNoCompression(label); final byte[] data = label2data.get(label); if (data == null) readerWriter.writeInt(0); else { readerWriter.writeInt(data.length); readerWriter.write(data); } } } getFooterSectionRMA6().setEndAuxDataSection(readerWriter.getPosition()); } }
4,501
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
FooterSectionRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/FooterSectionRMA6.java
/* * FooterSectionRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import megan.io.IInputReader; import megan.io.IInputReaderOutputWriter; import megan.io.IOutputWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * footer for read-alignment archive format * Daniel Huson, 6.2015 */ public class FooterSectionRMA6 { private long numberOfReads; private long numberOfMatches; private final Map<String, Long> availableClassification2Position = new HashMap<>(); // classifications available private long startHeaderSection; private long endHeaderSection; private long startReadsSection; private long endReadsSection; private long startClassificationsSection; private long endClassificationsSection; private long startAuxDataSection; private long endAuxDataSection; private long startFooterSection; private long endFooterSection; public void read(IInputReader reader) throws IOException { numberOfReads = reader.readLong(); numberOfMatches = reader.readLong(); int numberOfAvailableClassifications = reader.readInt(); for (int i = 0; i < numberOfAvailableClassifications; i++) { final String classificationName = reader.readString(); final long pos = reader.readLong(); if (pos > reader.length()) throw new IOException("Bad file position: " + pos); availableClassification2Position.put(classificationName, pos); } startHeaderSection = reader.readLong(); endHeaderSection = reader.readLong(); startReadsSection = reader.readLong(); endReadsSection = reader.readLong(); startClassificationsSection = reader.readLong(); endClassificationsSection = reader.readLong(); startAuxDataSection = reader.readLong(); endAuxDataSection = reader.readLong(); startFooterSection = reader.readLong(); endFooterSection = reader.readLong(); if (endFooterSection != reader.length()) throw new IOException("endFooterSection mismatch"); } /** * reads the start of the footer section * * @return start position of the footer section */ public static long readStartFooterSection(IInputReaderOutputWriter reader) throws IOException { reader.seek(reader.length() - 16); return reader.readLong(); } /** * write the footer * */ public void write(IOutputWriter writer) throws IOException { writer.writeLong(numberOfReads); writer.writeLong(numberOfMatches); writer.writeInt(availableClassification2Position.size()); for (String classificationName : availableClassification2Position.keySet()) { writer.writeString(classificationName); writer.writeLong(availableClassification2Position.get(classificationName)); } writer.writeLong(startHeaderSection); writer.writeLong(endHeaderSection); writer.writeLong(startReadsSection); writer.writeLong(endReadsSection); writer.writeLong(startClassificationsSection); writer.writeLong(endClassificationsSection); writer.writeLong(startAuxDataSection); writer.writeLong(endAuxDataSection); writer.writeLong(startFooterSection); endFooterSection = writer.length() + 8; writer.writeLong(endFooterSection); } public long getNumberOfReads() { return numberOfReads; } public void setNumberOfReads(long numberOfReads) { this.numberOfReads = numberOfReads; } public long getNumberOfMatches() { return numberOfMatches; } public void setNumberOfMatches(long numberOfMatches) { this.numberOfMatches = numberOfMatches; } public Map<String, Long> getAvailableClassification2Position() { return availableClassification2Position; } public long getStartHeaderSection() { return startHeaderSection; } public void setStartHeaderSection(long startHeaderSection) { this.startHeaderSection = startHeaderSection; } public long getEndHeaderSection() { return endHeaderSection; } public void setEndHeaderSection(long endHeaderSection) { this.endHeaderSection = endHeaderSection; } public long getStartReadsSection() { return startReadsSection; } public void setStartReadsSection(long startReadsSection) { this.startReadsSection = startReadsSection; } public long getEndReadsSection() { return endReadsSection; } public void setEndReadsSection(long endReadsSection) { this.endReadsSection = endReadsSection; } public long getStartClassificationsSection() { return startClassificationsSection; } public void setStartClassificationsSection(long startClassificationsSection) { this.startClassificationsSection = startClassificationsSection; } public long getEndClassificationsSection() { return endClassificationsSection; } public void setEndClassificationsSection(long endClassificationsSection) { this.endClassificationsSection = endClassificationsSection; } public long getStartAuxDataSection() { return startAuxDataSection; } public void setStartAuxDataSection(long startAuxDataSection) { this.startAuxDataSection = startAuxDataSection; } public long getEndAuxDataSection() { return endAuxDataSection; } public void setEndAuxDataSection(long endAuxDataSection) { this.endAuxDataSection = endAuxDataSection; } public long getStartFooterSection() { return startFooterSection; } public void setStartFooterSection(long startFooterSection) { this.startFooterSection = startFooterSection; } public long getEndFooterSection() { return endFooterSection; } public void setEndFooterSection(long endFooterSection) { this.endFooterSection = endFooterSection; } /** * gets the start position for a named classification * * @return start or -1 */ public Long getStartClassification(String classificationName) { return getAvailableClassification2Position().get(classificationName); } }
7,118
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6FileModifier.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6FileModifier.java
/* * RMA6FileModifier.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.ListOfLongs; import jloda.util.StringUtils; import megan.io.InputOutputReaderWriter; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.Map; /** * class used to update the classifications in an Rma6 file * Daniel Huson, 4.2015 */ public class RMA6FileModifier extends RMA6File implements Closeable { private InputOutputReaderWriter io; /** * construct an RMA6 modifier and read in RMA6 data * */ public RMA6FileModifier(String fileName) throws IOException { super(fileName, READ_WRITE); super.close(); // have read the file, now close the readerWriter } /** * update the classifications * */ public void updateClassifications(String[] cNames, Map<Integer, ListOfLongs>[] fName2ClassId2Location, Map<Integer, Float>[] fName2ClassId2Weight) throws IOException { io = new InputOutputReaderWriter(new File(fileName), READ_WRITE); io.seek(footerSectionRMA6.getStartClassificationsSection()); io.setLength(io.getPosition()); footerSectionRMA6.getAvailableClassification2Position().clear(); for (int c = 0; c < cNames.length; c++) { final String cName = cNames[c]; final ClassificationBlockRMA6 classification = new ClassificationBlockRMA6(cName); final Map<Integer, ListOfLongs> id2locations = fName2ClassId2Location[c]; for (int id : id2locations.keySet()) { final Float weight = fName2ClassId2Weight[c].get(id); classification.setWeightedSum(id, weight != null ? weight : 0f); final ListOfLongs list = fName2ClassId2Location[c].get(id); classification.setSum(id, list != null ? list.size() : 0); } footerSectionRMA6.getAvailableClassification2Position().put(cName, io.getPosition()); classification.write(io, id2locations); System.err.printf("Numb. %4s classes: %,10d%n", StringUtils.abbreviate(cName, 4), id2locations.size()); } footerSectionRMA6.setEndClassificationsSection(io.getPosition()); footerSectionRMA6.setStartAuxDataSection(io.getPosition()); io.writeInt(0); footerSectionRMA6.setEndAuxDataSection(io.getPosition()); footerSectionRMA6.setStartFooterSection(io.getPosition()); footerSectionRMA6.write(io); close(); } /** * close the readerWriter/writer, if it is open * */ public void close() throws IOException { if (io != null) { try { io.close(); } finally { io = null; } } } /** * save the aux data to the rma6 file * */ public void saveAuxData(Map<String, byte[]> label2data) throws IOException { final long location = footerSectionRMA6.getStartAuxDataSection(); io = new InputOutputReaderWriter(new File(fileName), READ_WRITE); io.setLength(location); io.seek(location); io.writeInt(label2data.size()); for (String name : label2data.keySet()) { io.writeString(name); byte[] bytes = label2data.get(name); io.writeInt(bytes.length); io.write(bytes); } footerSectionRMA6.setEndAuxDataSection(io.getPosition()); footerSectionRMA6.setStartFooterSection(io.getPosition()); footerSectionRMA6.write(io); close(); } static class DataRecord { ListOfLongs locations; float weight; int sum; } }
4,421
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Utilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/Utilities.java
/* * Utilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.*; import megan.io.InputReader; import java.io.File; import java.io.IOException; /** * Some utilities for creating Rma6 files * Created by huson on 5/23/14. */ class Utilities { /** * find the query in the reads file. When found, FileLineBytesIterator is pointing to location of query in file * * @return true, if found */ public static boolean findQuery(byte[] queryName, int queryNameLength, FileLineBytesIterator it, boolean isFastA) { try { if (isFastA) { while (it.hasNext()) { byte[] line = it.next(); if (line[0] == '>' && matchName(queryName, queryNameLength, line, it.getLineLength())) return true; } } else { // assume that this is fastQ if (it.getLinePosition() == 0) // at beginning of file { byte[] line = it.next(); // System.err.println(Basic.toString(line,it.getLineLength())); if (line[0] != '@') throw new IOException("Expected FastQ header line (starting with '@'), got: " + StringUtils.toString(line, it.getLineLength())); if (matchName(queryName, queryNameLength, line, it.getLineLength())) return true; it.next(); it.next(); it.next(); } while (it.hasNext()) { byte[] line = it.next(); // System.err.println(Basic.toString(line,it.getLineLength())); if (line[0] != '@') throw new IOException("Expected FastQ header line (starting with '@'), got: " + StringUtils.toString(line, it.getLineLength())); if (matchName(queryName, queryNameLength, line, it.getLineLength())) return true; it.next(); it.next(); it.next(); } } } catch (Exception ex) { Basic.caught(ex); } return false; } /** * assuming that the FileLineBytesIterator has just returned the header line of a fastA or fastQ record, writes the full text of the match * * @return string */ public static String getFastAText(FileLineBytesIterator it, boolean isFastA) { final StringBuilder buf = new StringBuilder(); if (isFastA) { byte[] bytes = it.getLine(); while (true) { for (int i = 0; i < it.getLineLength(); i++) buf.append((char) bytes[i]); if (!it.hasNext() || it.peekNextByte() == '>') break; bytes = it.next(); } } else // fastq, copy in fastA format... { byte[] bytes = it.getLine(); buf.append(">"); for (int i = 1; i < it.getLineLength(); i++) // first line has header, skip the leading '@' buf.append((char) bytes[i]); if (it.hasNext()) { // second line has sequence bytes = it.next(); for (int i = 0; i < it.getLineLength(); i++) buf.append((char) bytes[i]); } // skip the two next lines: if (it.hasNext()) it.next(); if (it.hasNext()) it.next(); } return buf.toString(); } /** * assuming that the FileLineBytesIterator has just returned the header line of a fastA or fastQ record, writes the full text of the match * */ public static void skipFastAText(FileLineBytesIterator it, boolean isFastA) { if (isFastA) { while (it.hasNext() && it.peekNextByte() != '>') { it.next(); } } else // fastq { if (it.hasNext()) { // second it.next(); } if (it.hasNext()) { // third it.next(); } if (it.hasNext()) { // fourth line it.next(); } } } /** * assuming that the FileLineBytesIterator has just returned the header line of a fastA or fastQ record, copies the full text of the match * * @return size */ public static int getFastAText(FileLineBytesIterator it, boolean isFastA, Single<byte[]> result) { // todo: has not been tested! byte[] buffer = result.get(); if (isFastA) { byte[] bytes = it.getLine(); int length = 0; while (true) { if (length + it.getLineLength() >= buffer.length) { // grow result buffer byte[] tmp = new byte[2 * (length + it.getLineLength())]; System.arraycopy(buffer, 0, tmp, 0, length); buffer = tmp; result.set(buffer); } System.arraycopy(bytes, 0, buffer, length, it.getLineLength()); length += it.getLineLength(); if (!it.hasNext() || it.peekNextByte() == '>') break; bytes = it.next(); } return length; } else // fastq { byte[] bytes = it.getLine(); if (it.getLineLength() + 1 >= buffer.length) { // grow result buffer buffer = new byte[2 * (it.getLineLength() + 1)]; result.set(buffer); } int length = 0; buffer[length++] = '>'; // first character is '>' (not '@') System.arraycopy(bytes, 1, buffer, length, it.getLineLength() - 1); length += it.getLineLength() - 1; buffer[length++] = '\n'; if (it.hasNext()) { // second line has sequence bytes = it.next(); if (length + it.getLineLength() + 1 >= buffer.length) { // grow result buffer byte[] tmp = new byte[2 * (length + it.getLineLength() + 1)]; System.arraycopy(buffer, 0, tmp, 0, length); buffer = tmp; result.set(buffer); } System.arraycopy(bytes, 0, buffer, length, it.getLineLength()); length += it.getLineLength(); } if (it.hasNext()) { // third it.next(); } if (it.hasNext()) { // fourth line it.next(); } return length; } } /** * match header line with query name * * @return true, if name matches name in line */ private static boolean matchName(byte[] queryName, int queryNameLength, byte[] line, int lineLength) { int start = 0; if (line[start] == '>' || line[0] == '@') start++; while (Character.isWhitespace(line[start]) && start < lineLength) start++; int end = start; while (!Character.isWhitespace(line[end]) && end < lineLength) { end++; } if (end - start != queryNameLength) return false; // have different lengths for (int i = 0; i < queryNameLength; i++) { if (queryName[i] != line[start + i]) return false; } return true; } /** * returns a fastA or fastQ record as FastA * * @return fastA record at current position */ public static String getFastAText(InputReader reader, long position) throws IOException { StringBuilder buf = new StringBuilder(); reader.seek(position); char letter = (char) reader.read(); boolean isFastA = (letter == '>'); if (!isFastA && (letter != '@')) throw new IOException("Expected '>' or '@' at position: " + position + ", got: " + letter); buf.append('>'); if (isFastA) { letter = (char) reader.read(); while (letter != '>') { if (letter != '\r') buf.append(letter); letter = (char) reader.read(); } } else // fastq, copy in fastA format... { boolean seenFirstEndOfLine = false; letter = (char) reader.read(); while (true) { if (letter != '\r') buf.append(letter); if (letter == '\n') { if (!seenFirstEndOfLine) seenFirstEndOfLine = true; else break; } letter = (char) reader.read(); } } return buf.toString(); } /** * get the header from a fastA record * * @return header */ public static String getFastAHeader(String fastAText) { int end = fastAText.indexOf('\n'); if (end == -1) return fastAText; else return fastAText.substring(0, end); } /** * get the seqiemce from a fastA record * * @return header */ public static String getFastASequence(String fastAText) { int start = fastAText.indexOf('\n'); if (start == -1) return "Unavailable"; else return fastAText.substring(start + 1); } /** * is the given file a MALT or Diamond -generated SAM file? * * @return true, if file is MALT or Diamond generated SAM file */ public static boolean IsMaltOrDiamondSAMFile(File file) { String suffix = FileUtils.getFileSuffix(FileUtils.getFileNameWithoutZipOrGZipSuffix(file.getName())); if (suffix == null) return false; if (!suffix.equalsIgnoreCase(".sam")) return false; try { try (FileLineIterator it = new FileLineIterator(file.getPath())) { while (it.hasNext()) { String aLine = it.next(); if (aLine.startsWith("@")) { if (aLine.contains("PN:MALT") || (aLine.contains("PN:DIAMOND"))) return true; } else { return false; } } } } catch (IOException ignored) { } return false; } /** * gets the specified token from a tab separated text * * @param n which token (starting at 0) * @return n-th token */ public static String getToken(int n, byte[] text, int offset) { int prev = offset; while (true) { while (text[offset] != '\t') offset++; if (n-- == 0) break; offset++; prev = offset; } return new String(text, prev, offset - prev); } /** * gets the position of the next newline character * * @return next new line */ public static int nextNewLine(byte[] text, int offset) { while (offset < text.length) { if (text[offset] == '\n') return offset; else offset++; } return offset; } /** * split a given text into strings * * @return strings */ public static String[] split(byte[] text, int offset, int end, byte splitChar) { // skip leading white space: while (Character.isWhitespace((char) text[offset]) && offset < end) offset++; int count = 0; for (int i = offset; i < end; i++) { if (text[i] == splitChar) count++; } String[] result = new String[count]; count = 0; for (int i = offset; i < end; i++) { if (text[i] == splitChar) { result[count++] = new String(text, offset, i - offset); offset = i + 1; } } return result; } }
12,835
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6FileCreator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6FileCreator.java
/* * RMA6FileCreator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.seq.BlastMode; import jloda.util.ListOfLongs; import megan.io.OutputWriter; import java.io.File; import java.io.IOException; import java.util.Map; /** * class used to create a new RMA6 file * Daniel Huson, 6.2015 */ public class RMA6FileCreator extends RMA6File { private boolean isPairedReads; private final boolean useCompression; private int numberOfClassificationNames; private long totalNumberOfReads; private long totalNumberOfMatches; /** * constructor * */ public RMA6FileCreator(String fileName, boolean useCompression) { super(); this.useCompression = useCompression; this.fileName = fileName; } /** * setup and write the header * */ public void writeHeader(String creator, BlastMode blastMode, String[] matchClassificationNames, boolean isPairedReads) throws IOException { // setup header: final HeaderSectionRMA6 headerSection = getHeaderSectionRMA6(); headerSection.setCreationDate(System.currentTimeMillis()); headerSection.setCreator(creator); headerSection.setBlastMode(blastMode); headerSection.setMatchClassNames(matchClassificationNames); headerSection.setIsPairedReads(isPairedReads); this.isPairedReads = isPairedReads; numberOfClassificationNames = matchClassificationNames.length; File file = new File(fileName); if (file.exists() && !file.delete()) throw new IOException("Can't delete existing file: " + file); readerWriter = new OutputWriter(new File(fileName)); // need to stream output for efficiency readerWriter.setUseCompression(useCompression); getFooterSectionRMA6().setStartHeaderSection(readerWriter.getPosition()); getHeaderSectionRMA6().write(readerWriter); getFooterSectionRMA6().setEndHeaderSection(readerWriter.getPosition()); } /** * Start adding queries and writing them to a file. Assumes that the header section has been set appropriately * */ public void startAddingQueries() throws IOException { totalNumberOfReads = 0; totalNumberOfMatches = 0; getFooterSectionRMA6().setStartReadsSection(readerWriter.getPosition()); } /** * add a query and its matches to the file * */ public void addQuery(byte[] queryText, int queryTextLength, int numberOfMatches, byte[] matchesText, int matchesTextLength, int[][] match2Classification2Id, long mateLocation) throws IOException { final long location = readerWriter.getPosition(); if (isPairedReads) readerWriter.writeLong(mateLocation); readerWriter.writeString(queryText, 0, queryTextLength); readerWriter.writeInt(numberOfMatches); for (int i = 0; i < numberOfMatches; i++) { for (int j = 0; j < numberOfClassificationNames; j++) { readerWriter.writeInt(match2Classification2Id[i][j]); } } readerWriter.writeString(matchesText, 0, matchesTextLength); this.totalNumberOfReads++; this.totalNumberOfMatches += numberOfMatches; } /** * finish creating the file. Assumes that the footer section has been set appropriately * */ public void endAddingQueries() throws IOException { getFooterSectionRMA6().setEndReadsSection(readerWriter.getPosition()); getFooterSectionRMA6().setNumberOfReads(totalNumberOfReads); getFooterSectionRMA6().setNumberOfMatches(totalNumberOfMatches); } /** * writes the classifications * */ public void writeClassifications(String[] cNames, Map<Integer, ListOfLongs>[] fName2Location, Map<Integer, Integer>[] fName2weight) throws IOException { getFooterSectionRMA6().setStartClassificationsSection(readerWriter.getPosition()); getFooterSectionRMA6().getAvailableClassification2Position().clear(); if (cNames != null) { for (int i = 0; i < cNames.length; i++) { final String cName = cNames[i]; final ClassificationBlockRMA6 classification = new ClassificationBlockRMA6(cName); final Map<Integer, ListOfLongs> id2locations = fName2Location[i]; for (int id : id2locations.keySet()) { final Integer weight = fName2weight[i].get(id); classification.setSum(id, weight != null ? weight : 0); } getFooterSectionRMA6().getAvailableClassification2Position().put(cName, readerWriter.getPosition()); classification.write(readerWriter, id2locations); System.err.printf("Class. %-13s%,10d%n", cName + ":", id2locations.size()); } } getFooterSectionRMA6().setEndClassificationsSection(readerWriter.getPosition()); } /** * finish creating the file. Assumes that the footer section has been set appropriately * */ public void close() throws IOException { getFooterSectionRMA6().setStartFooterSection(readerWriter.getPosition()); getFooterSectionRMA6().write(readerWriter); readerWriter.close(); readerWriter = null; } public long getPosition() throws IOException { return readerWriter.getPosition(); } }
6,175
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockGetterRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/ReadBlockGetterRMA6.java
/* * ReadBlockGetterRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.Basic; import megan.data.IReadBlock; import megan.data.IReadBlockGetter; import megan.io.IInputReader; import java.io.IOException; /** * Read block getter * Daniel Huson, 4.2015 */ public class ReadBlockGetterRMA6 implements IReadBlockGetter { private final RMA6File rma6File; private final boolean wantReadSequence; private final boolean wantMatches; private final float minScore; private final float maxExpected; private final boolean streamOnly; private final ReadBlockRMA6 reuseableReadBlock; private final long start; private final long end; private final IInputReader reader; /** * constructor * */ public ReadBlockGetterRMA6(RMA6File rma6File, boolean wantReadSequence, boolean wantMatches, float minScore, float maxExpected, boolean streamOnly, boolean reuseReadBlockObject) throws IOException { this.rma6File = rma6File; this.wantReadSequence = wantReadSequence; this.wantMatches = wantMatches; this.minScore = minScore; this.maxExpected = maxExpected; this.streamOnly = streamOnly; this.start = rma6File.getFooterSectionRMA6().getStartReadsSection(); this.end = rma6File.getFooterSectionRMA6().getEndReadsSection(); reader = rma6File.getReader(); if (streamOnly) reader.seek(start); if (reuseReadBlockObject) reuseableReadBlock = new ReadBlockRMA6(rma6File.getHeaderSectionRMA6().getBlastMode(), rma6File.getHeaderSectionRMA6().isPairedReads(), rma6File.getHeaderSectionRMA6().getMatchClassNames()); else reuseableReadBlock = null; } /** * gets the read block associated with the given uid * * @param uid or -1, if in streaming mode * @return read block or null */ @Override public IReadBlock getReadBlock(long uid) throws IOException { if (uid == -1) { if (!streamOnly) throw new IOException("getReadBlock(uid=" + uid + ") failed: not streamOnly"); } else { if (streamOnly) { throw new IOException("getReadBlock(uid=" + uid + ") failed: streamOnly"); } reader.seek(uid); } if (reader.getPosition() < end) { if (uid >= 0) { } final ReadBlockRMA6 readBlock = (reuseableReadBlock == null ? new ReadBlockRMA6(rma6File.getHeaderSectionRMA6().getBlastMode(), rma6File.getHeaderSectionRMA6().isPairedReads(), rma6File.getHeaderSectionRMA6().getMatchClassNames()) : reuseableReadBlock); readBlock.read(reader, wantReadSequence, wantMatches, minScore, maxExpected); return readBlock; } return null; } /** * closes the accessor * */ @Override public void close() { try { reader.close(); } catch (IOException e) { Basic.caught(e); } } public long getStart() { return start; } public long getEnd() { return end; } public long getPosition() { try { return rma6File.getReader().getPosition(); } catch (IOException e) { return -1; } } /** * get total number of reads * * @return total number of reads */ @Override public long getCount() { return rma6File.getFooterSectionRMA6().getNumberOfReads(); } }
4,299
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastFileReadBlockIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/BlastFileReadBlockIterator.java
/* * BlastFileReadBlockIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.seq.BlastMode; import jloda.util.*; import megan.classification.ClassificationManager; import megan.classification.IdParser; import megan.parsers.blast.BlastFileFormat; import megan.parsers.blast.BlastModeUtils; import megan.parsers.blast.ISAMIterator; import megan.parsers.blast.IteratorManager; import megan.parsers.sam.SAMMatch; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; /** * iterates over all read blocks found in a blast file * Daniel Huson, 4.2015 */ public class BlastFileReadBlockIterator implements Iterator<ReadBlockRMA6>, ICloseableIterator<ReadBlockRMA6> { private final String readsFile; private final BlastMode blastMode; private final String[] cNames; private final IdParser[] parsers; private final ISAMIterator iterator; private final FileLineBytesIterator fastaIterator; private final boolean isFasta; private final byte[] queryName = new byte[100000]; private final Single<byte[]> fastAText = new Single<>(new byte[1000]); private int missingReadWarnings; /** * constructor * */ public BlastFileReadBlockIterator(String blastFile, String readsFile, BlastFileFormat format, BlastMode blastMode, String[] cNames, int maxMatchesPerRead, boolean longReads) throws IOException { this.readsFile = readsFile; this.cNames = cNames; parsers = new IdParser[cNames.length]; for (int i = 0; i < cNames.length; i++) { parsers[i] = ClassificationManager.get(cNames[i], true).getIdMapper().createIdParser(); } if (format == BlastFileFormat.Unknown) { format = BlastFileFormat.detectFormat(null, blastFile, false); } if (blastMode == BlastMode.Unknown) { blastMode = BlastModeUtils.detectMode(null, blastFile, false); } this.blastMode = blastMode; iterator = IteratorManager.getIterator(blastFile, format, blastMode, maxMatchesPerRead, longReads); if (readsFile != null) { fastaIterator = new FileLineBytesIterator(readsFile); isFasta = (fastaIterator.peekNextByte() == '>'); if (!isFasta && (fastaIterator.peekNextByte() != '@')) throw new IOException("Cannot determine type of reads file (doesn't start with '>' or '@"); } else { fastaIterator = null; isFasta = false; } } /** * close * */ public void close() throws IOException { iterator.close(); } /** * gets the maximum progress value * * @return maximum progress value */ @Override public long getMaximumProgress() { return iterator.getMaximumProgress(); } /** * gets the current progress value * * @return current progress value */ @Override public long getProgress() { return iterator.getProgress(); } /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { return iterator.hasNext(); } /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override public ReadBlockRMA6 next() { if (!hasNext()) throw new NoSuchElementException(); final int numberOfMatches = iterator.next(); final byte[] matchesText = iterator.getMatchesText(); final int matchesTextLength = iterator.getMatchesTextLength(); final ReadBlockRMA6 readBlock = new ReadBlockRMA6(blastMode, false, cNames); final int queryNameLength = StringUtils.getFirstWord(matchesText, queryName); // write the read text boolean foundRead = false; if (fastaIterator != null) { if (Utilities.findQuery(queryName, queryNameLength, fastaIterator, isFasta)) { final int length = Utilities.getFastAText(fastaIterator, isFasta, fastAText); String fasta = StringUtils.toString(fastAText.get(), 0, length); int pos = fasta.indexOf('\n'); if (pos > 0) { readBlock.setReadHeader(fasta.substring(0, pos)); if (pos + 1 < fasta.length()) readBlock.setReadSequence(fasta.substring((pos + 1))); } foundRead = true; } else { if (missingReadWarnings++ < 50) System.err.println("WARNING: Failed to find read '" + StringUtils.toString(queryName, 0, queryNameLength) + "' in file: " + readsFile); if (missingReadWarnings == 50) System.err.println("No further missing warnings"); } } if (!foundRead) { readBlock.setReadHeader(String.format(">%s\n", StringUtils.toString(queryName, 0, queryNameLength))); } int start = 0; MatchBlockRMA6[] matchBlocks = new MatchBlockRMA6[numberOfMatches]; for (int matchCount = 0; matchCount < numberOfMatches; matchCount++) { int end = Utilities.nextNewLine(matchesText, start); final String aLine = StringUtils.toString(matchesText, start, end - start + 1); start = end + 1; MatchBlockRMA6 matchBlock = new MatchBlockRMA6(); SAMMatch samMatch = new SAMMatch(blastMode); try { samMatch.parse(aLine); } catch (IOException e) { Basic.caught(e); return null; } matchBlock.setFromSAM(samMatch); for (IdParser parser : parsers) { try { matchBlock.setId(parser.getCName(), parser.getIdFromHeaderLine(samMatch.getRefName())); } catch (IOException e) { Basic.caught(e); } } matchBlocks[matchCount] = matchBlock; } readBlock.setNumberOfMatches(numberOfMatches); readBlock.setMatchBlocks(matchBlocks); return readBlock; } @Override public void remove() { } }
7,204
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AllReadsIteratorRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/AllReadsIteratorRMA6.java
/* * AllReadsIteratorRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.Basic; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import java.io.IOException; /** * Iterates over all reads in an RMA6 file * Created by huson on 5/16/14. */ public class AllReadsIteratorRMA6 implements IReadBlockIterator { private final ReadBlockGetterRMA6 readBlockGetter; private int countReads = 0; /** * constructor * */ public AllReadsIteratorRMA6(boolean wantReadSequence, boolean wantMatches, RMA6File file, float minScore, float maxExpected) throws IOException { readBlockGetter = new ReadBlockGetterRMA6(file, wantReadSequence, wantMatches, minScore, maxExpected, true, false); } @Override public String getStats() { return "Reads: " + countReads; } @Override public void close() { readBlockGetter.close(); } @Override public long getMaximumProgress() { return readBlockGetter.getEnd() - readBlockGetter.getStart(); } @Override public long getProgress() { return readBlockGetter.getPosition() - readBlockGetter.getStart(); } @Override public boolean hasNext() { return readBlockGetter.getPosition() < readBlockGetter.getEnd(); } @Override public IReadBlock next() { if (!hasNext()) return null; try { final IReadBlock readBlock = readBlockGetter.getReadBlock(-1); countReads++; return readBlock; } catch (IOException e) { Basic.caught(e); return null; } } @Override public void remove() { } }
2,466
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/ReadBlockRMA6.java
/* * ReadBlockRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.seq.BlastMode; import jloda.util.StringUtils; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.io.IInputReader; import megan.parsers.sam.SAMMatch; import megan.util.ReadMagnitudeParser; import java.io.IOException; /** * ReadBlock for RMA6 * Daniel Huson, 6.2015 */ public class ReadBlockRMA6 implements IReadBlock { private final BlastMode blastMode; private final boolean pairedReads; private final String[] cNames; private long uid; private String readHeader; private String readSequence; private int readLength; private float readComplexity; private int readWeight; private long mateUid; private byte mateType; private int numberOfMatches; private IMatchBlock[] matchBlocks; /** * Constructor * */ public ReadBlockRMA6(BlastMode blastMode, boolean pairedReads, String[] cNames) { this.blastMode = blastMode; this.pairedReads = pairedReads; this.cNames = cNames; } /** * get the unique identifier for this read (unique within a dataset). * In an RMA file, this is always the file position for the read * * @return uid */ public long getUId() { return uid; } public void setUId(long uid) { this.uid = uid; } /** * get the name of the read (first word in header) * * @return name */ public String getReadName() { return readHeader != null ? StringUtils.swallowLeadingGreaterSign(StringUtils.getFirstWord(readHeader)) : null; } /** * get the fastA header for the read * * @return fastA header */ public String getReadHeader() { return readHeader; } public void setReadHeader(String readHeader) { this.readHeader = readHeader; } /** * get the sequence of the read * * @return sequence */ public String getReadSequence() { return readSequence; } public void setReadSequence(String readSequence) { this.readSequence = readSequence; } /** * gets the uid of the mated read * * @return uid of mate or 0 */ public long getMateUId() { return mateUid; } public void setMateUId(long mateUid) { this.mateUid = mateUid; } /** * get the mate type * Possible values: FIRST_MATE, SECOND_MATE * * @return mate type */ public byte getMateType() { return mateType; } public void setMateType(byte mateType) { this.mateType = mateType; } /** * set the read length * */ public void setReadLength(int readLength) { this.readLength = readLength; } public int getReadLength() { return readLength; } /** * get the complexity * */ public void setComplexity(float readComplexity) { this.readComplexity = readComplexity; } public float getComplexity() { return readComplexity; } /** * set the weight of a read * */ public void setReadWeight(int readWeight) { this.readWeight = readWeight; } /** * get the weight of a read * * @return weight */ public int getReadWeight() { return readWeight; } /** * get the original number of matches * * @return number of matches */ public int getNumberOfMatches() { return numberOfMatches; } public void setNumberOfMatches(int numberOfMatches) { this.numberOfMatches = numberOfMatches; } /** * gets the current number of matches available * */ public int getNumberOfAvailableMatchBlocks() { return matchBlocks != null ? matchBlocks.length : 0; } /** * get the matches. May be less than the original number of matches (when filtering matches) * * @return matches */ public IMatchBlock[] getMatchBlocks() { return matchBlocks; } public void setMatchBlocks(IMatchBlock[] matchBlocks) { this.matchBlocks = matchBlocks; } /** * get the i-th match block * * @return match block */ public IMatchBlock getMatchBlock(int i) { return matchBlocks[i]; } /** * reads a read block * */ public void read(IInputReader reader, boolean wantReadSequence, boolean wantMatches, float minScore, float maxExpected) throws IOException { setUId(reader.getPosition()); if (pairedReads) mateUid = reader.readLong(); String readText = reader.readString(); if (readText.length() > 0) { int pos = readText.indexOf('\n'); if (pos == -1) // only one line... { setReadHeader(readText); setReadWeight(ReadMagnitudeParser.parseMagnitude(getReadHeader())); setReadSequence(null); setReadLength(0); } else if (pos > 0) { // looks like more than one line setReadHeader(readText.substring(0, pos)); setReadWeight(ReadMagnitudeParser.parseMagnitude(getReadHeader())); if (pos + 1 < readText.length()) { String sequence = StringUtils.removeAllWhiteSpaces(readText.substring(pos + 1)); setReadSequence(wantReadSequence ? sequence : null); setReadLength(sequence.length()); } else { setReadSequence(null); setReadLength(0); } } else { setReadHeader(null); setReadSequence(null); setReadLength(0); } } numberOfMatches = reader.readInt(); if (wantMatches) { // construct match blocks: matchBlocks = new MatchBlockRMA6[numberOfMatches]; for (int i = 0; i < numberOfMatches; i++) matchBlocks[i] = new MatchBlockRMA6(); // for each match, read taxon-id and classification ids: for (int i = 0; i < numberOfMatches; i++) { for (String cName : cNames) { matchBlocks[i].setId(cName, reader.readInt()); // read 4*fName.length bytes } } // read the text for all matches: final String matchesText = reader.readString(); // assume each line is in SAM format and ends on \n String querySequence = getReadSequence(); String queryQuality = null; // if the read is not given, find the longest reported sequence, inserting any hard clip that it might have if (querySequence == null) { int offset = 0; int queryHardClip = 0; for (int i = 0; i < numberOfMatches; i++) { int end = matchesText.indexOf('\n', offset + 1); if (end == -1) end = matchesText.length(); final String aLine = matchesText.substring(offset, end); offset = end + 1; final String[] tokens = StringUtils.split(aLine, '\t'); if (tokens.length > 10) { final String query = tokens[9]; if (query != null && (querySequence == null || querySequence.length() < query.length())) { querySequence = query; queryQuality = tokens[10]; queryHardClip = parseLeadingHardClip(tokens[5]); } } } // note: must insert 0's here because SAMMatch looks for initial 0 to identify queries that have had the hard-clipped sequence inserted as 0's querySequence = insertLeading0Characters(querySequence, queryHardClip); // todo: if we want to use the quality values, then we must uncomment the next line: // queryQuality=insertLeading0Characters(queryQuality,queryHardClip); } // parse and copy the matches that we want to keep int offset = 0; int matchCount = 0; final IMatchBlock[] copies = new MatchBlockRMA6[numberOfMatches]; // need to copy matches we want to keep for (int i = 0; i < numberOfMatches; i++) { int end = matchesText.indexOf('\n', offset + 1); if (end == -1) end = matchesText.length(); final String aLine = matchesText.substring(offset, end); offset = end + 1; try { final SAMMatch samMatch = new SAMMatch(blastMode); final String[] tokens = StringUtils.split(aLine, '\t'); if (tokens.length > 10) { if ((tokens[9].equals("*") || tokens[9].length() == 0) && querySequence != null) { tokens[9] = querySequence; if (queryQuality != null) tokens[10] = queryQuality; } } samMatch.parse(tokens, tokens.length); if (samMatch.getRefName() != null) { final MatchBlockRMA6 matchBlock = (MatchBlockRMA6) matchBlocks[i]; matchBlock.setFromSAM(samMatch); if ((minScore == 0 || matchBlock.getBitScore() >= minScore) && matchBlock.getExpected() <= maxExpected) copies[matchCount++] = matchBlock; // this match is ok, keep it } } catch (IOException ex) { System.err.println("RMA6 Parse error: " + ex.getMessage() + ", numberOfMatches=" + numberOfMatches + ", i=" + i + " line=" + aLine); } } if (matchCount < matchBlocks.length) { // some matches didn't meet the minScore or maxExpected criteria, resize matchBlocks = new MatchBlockRMA6[matchCount]; System.arraycopy(copies, 0, matchBlocks, 0, matchCount); } } else { reader.skipBytes(cNames.length * numberOfMatches * 4); // skip taxon and cName ids reader.skipBytes(Math.abs(reader.readInt())); // skip text } } /** * gets the leading hard clip * * @return leading hard clip or 0 */ private static int parseLeadingHardClip(String cigar) { for (int i = 0; i < cigar.length(); i++) { char ch = cigar.charAt(i); if (!Character.isDigit(ch)) { if (Character.toUpperCase(ch) == 'H' && i > 0) return Integer.parseInt(cigar.substring(0, i)); else return 0; } } return 0; } /** * inserts the given number of 0 characters * * @return extended string */ private static String insertLeading0Characters(String sequence, int numberOfLeading0Characters) { if (numberOfLeading0Characters == 0) return sequence; else return new String(new char[numberOfLeading0Characters]) + sequence; } }
12,104
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchLineRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/MatchLineRMA6.java
/* * MatchLineRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; /** * stores data required to perform LCA and functional analysis * Daniel Huson, 4.2015 */ public class MatchLineRMA6 { private float bitScore; private float expected; private float percentIdentity; private final int[] fIds; private final int taxonomyIndex; // index of the fId that contains the taxon index /** * constructor * */ public MatchLineRMA6(int numberOfFNames, int taxonomyIndex) { fIds = new int[numberOfFNames]; this.taxonomyIndex = taxonomyIndex; } /** * parse SAM match that starts at given offset (ignoring any further matches that come after a newline) * */ public void parse(byte[] matchesText, int offset) { bitScore = 0; expected = 0; percentIdentity = 0; int end = Utilities.nextNewLine(matchesText, offset); offset = skipTabs(matchesText, offset, 11); if (offset > -1) { String[] tokens = Utilities.split(matchesText, offset, end, (byte) '\t'); for (String token : tokens) { if (token.startsWith("AS:i:")) bitScore = Integer.parseInt(token.substring(5)); else if (token.startsWith("ZE:f:")) expected = Float.parseFloat(token.substring(5)); else if (token.startsWith("ZI:i:")) percentIdentity = Float.parseFloat(token.substring(5)); } } } /** * skip a given count of tabs * * @return position of n-th tab after offset */ private static int skipTabs(byte[] text, int offset, int n) { while (n > 0) { if (offset == text.length) return -1; if (text[offset] == '\t') n--; offset++; } return offset - 1; } public float getBitScore() { return bitScore; } public void setBitScore(float bitScore) { this.bitScore = bitScore; } public float getExpected() { return expected; } public void setExpected(float expected) { this.expected = expected; } public float getPercentIdentity() { return percentIdentity; } public void setPercentIdentity(float percentIdentity) { this.percentIdentity = percentIdentity; } public int getTaxId() { return fIds[taxonomyIndex]; } public void setTaxId(int taxId) { fIds[taxonomyIndex] = taxId; } public int getFId(int i) { return fIds[i]; } public void setFId(int i, int id) { fIds[i] = id; } }
3,455
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationBlockRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/ClassificationBlockRMA6.java
/* * ClassificationBlockRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.ListOfLongs; import megan.data.IClassificationBlock; import megan.io.IInputReader; import megan.io.IOutputWriter; import megan.io.InputReader; import megan.io.OutputWriterHumanReadable; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * implements a classification block * Created by huson on 5/16/14. */ public class ClassificationBlockRMA6 implements IClassificationBlock { private final Map<Integer, Integer> id2count = new HashMap<>(); private final Map<Integer, Float> id2weight = new HashMap<>(); private String classificationName; public ClassificationBlockRMA6(String classificationName) { this.classificationName = classificationName; } public int getSum(Integer key) { Integer sum = id2count.get(key); return (sum != null ? sum : 0); } public float getWeightedSum(Integer key) { final Float result = id2weight.get(key); if (result != null && result > 0) return result; else return getSum(key); } public void setSum(Integer key, int num) { id2count.put(key, num); } @Override public void setWeightedSum(Integer key, float num) { id2weight.put(key, num); } public String getName() { return classificationName; } public void setName(String name) { classificationName = name; } public Set<Integer> getKeySet() { return id2weight.keySet(); } /** * write to file * */ public void write(IOutputWriter writer, Map<Integer, ListOfLongs> classId2locations) throws IOException { writer.writeInt(id2weight.size()); for (Integer key : id2weight.keySet()) { writer.writeInt(key); // class id final Float weight = id2weight.get(key); writer.writeInt(Math.round(weight != null ? weight : 0)); //weight if (classId2locations != null) { final ListOfLongs list = classId2locations.get(key); writer.writeInt(list.size()); for (int i = 0; i < list.size(); i++) writer.writeLong(list.get(i)); } else writer.writeInt(0); } } /** * reads the named classification block * */ public void read(long position, IInputReader reader) throws IOException { id2weight.clear(); reader.seek(position); final int numberOfClasses = reader.readInt(); for (int i = 0; i < numberOfClasses; i++) { final int classId = reader.readInt(); final int weight = reader.readInt(); final int count = reader.readInt(); reader.skipBytes(count * 8); // skip all locations, 8 bytes each id2weight.put(classId, (float) weight); id2count.put(classId, count); } id2weight.size(); } /** * reads the named classification block * * @return size */ public int read(long position, InputReader reader, int classId) throws IOException { reader.seek(position); id2weight.clear(); final int numberOfClasses = reader.readInt(); for (int i = 0; i < numberOfClasses; i++) { final int currentId = reader.readInt(); final int weight = reader.readInt(); final int count = reader.readInt(); reader.skipBytes(count * 8); // skip all locations, 8 bytes each if (currentId == classId) { id2weight.put(currentId, (float) weight); id2count.put(currentId, count); break; } } return id2weight.size(); } /** * read all locations for a given class and adds them to list * */ public void readLocations(long position, IInputReader reader, int classId, ListOfLongs list) throws IOException { reader.seek(position); final int numberOfClasses = reader.readInt(); for (int i = 0; i < numberOfClasses; i++) { final int currentId = reader.readInt(); reader.readInt(); // weight final int count = reader.readInt(); if (currentId == classId) { for (int z = 0; z < count; z++) { list.add(reader.readLong()); } } else reader.skipBytes(count * 8); // skip all locations, 8 bytes each } list.size(); } /** * human readable representation * * @return string */ public String toString() { final IOutputWriter w = new OutputWriterHumanReadable(new StringWriter()); try { // w.writeString(classificationType.toString()+":\n"); write(w, null); } catch (IOException ignored) { } return w.toString(); } }
5,785
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RMA6ToSAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/RMA6ToSAMIterator.java
/* * RMA6ToSAMIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.Basic; import jloda.util.ListOfLongs; import megan.io.IInputReader; import megan.parsers.blast.ISAMIterator; import java.io.IOException; import java.util.Collection; /** * iterator over an RMA6 file that returns reads and matches in SAM format * Daniel Huson, 4.2015 */ public class RMA6ToSAMIterator implements ISAMIterator { private final RMA6File rma6File; private final IInputReader reader; private final ListOfLongs list; private final int positionInList = 0; private final String[] cNames; private final boolean pairedReads; private String readText; private byte[] matchesText; private int matchesTextLength; private boolean parseLongReads; /** * constructor * */ public RMA6ToSAMIterator(String classificationName, Collection<Integer> classIds, String fileName) throws IOException { rma6File = new RMA6File(fileName, "r"); reader = rma6File.getReader(); pairedReads = rma6File.getHeaderSectionRMA6().isPairedReads(); cNames = rma6File.getHeaderSectionRMA6().getMatchClassNames(); final ClassificationBlockRMA6 block = new ClassificationBlockRMA6(classificationName); long start = rma6File.getFooterSectionRMA6().getStartClassification(classificationName); block.read(start, rma6File.getReader()); list = new ListOfLongs(); for (Integer classId : classIds) { if (block.getSum(classId) > 0) { block.readLocations(start, rma6File.getReader(), classId, list); } } } /** * gets the next matches * * @return number of matches */ @Override public int next() { try { if (pairedReads) reader.skipBytes(8); // skip paired read info readText = reader.readString(); // read the read text final int numberOfMatches = reader.readInt(); // number of matches reader.skipBytes(numberOfMatches * cNames.length * 4); // skip taxon and classification ids matchesText = reader.readString().getBytes(); // todo: implement reading this directly into byte[] matchesTextLength = matchesText.length; return numberOfMatches; } catch (IOException ex) { Basic.caught(ex); return -1; } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return positionInList < list.size(); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesText; } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextLength; } @Override public long getMaximumProgress() { return list.size(); } @Override public long getProgress() { return positionInList; } @Override public void close() throws IOException { rma6File.close(); } /** * gets the read text * * @return read text */ public String getReadText() { return readText; } @Override public byte[] getQueryText() { return readText.getBytes(); } @Override public void setParseLongReads(boolean longReads) { parseLongReads = longReads; } @Override public boolean isParseLongReads() { return parseLongReads; } }
4,436
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractToNewDocumentRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/ExtractToNewDocumentRMA6.java
/* * ExtractToNewDocumentRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.util.CanceledException; import jloda.util.ListOfLongs; import jloda.util.Single; import jloda.util.progress.ProgressListener; import megan.io.IInputReader; import megan.io.OutputWriter; import java.io.File; import java.io.IOException; import java.util.Collection; /** * extract a given classification and class-ids to a new document * Daniel Huson, 4.2015 */ public class ExtractToNewDocumentRMA6 { /** * extract all named classes in the given classsification to a new RMA6 file * * @param totalReads return the total reads extracted here */ public static void apply(String sourceRMA6FileName, String sourceClassification, Collection<Integer> sourceClassIds, String targetRMA6FileName, ProgressListener progressListener, Single<Long> totalReads) throws IOException, CanceledException { final long startTime = System.currentTimeMillis(); final RMA6File sourceRMA6File = new RMA6File(sourceRMA6FileName, "r"); final boolean pairedReads = sourceRMA6File.getHeaderSectionRMA6().isPairedReads(); final String[] cNames = sourceRMA6File.getHeaderSectionRMA6().getMatchClassNames(); // determine the set of all positions to extract: final ClassificationBlockRMA6 block = new ClassificationBlockRMA6(sourceClassification); long start = sourceRMA6File.getFooterSectionRMA6().getStartClassification(sourceClassification); block.read(start, sourceRMA6File.getReader()); final ListOfLongs list = new ListOfLongs(); for (Integer classId : sourceClassIds) { if (block.getSum(classId) > 0) { block.readLocations(start, sourceRMA6File.getReader(), classId, list); } } long totalMatches = 0; // open the target file for writing try (OutputWriter writer = new OutputWriter(new File(targetRMA6FileName))) { final FooterSectionRMA6 footerSection = new FooterSectionRMA6(); try { // user might cancel inside this block.... progressListener.setTasks("Extracting", ""); progressListener.setProgress(0); progressListener.setMaximum(list.size()); // copy the file header from the source file: footerSection.setStartHeaderSection(0); sourceRMA6File.getHeaderSectionRMA6().write(writer); footerSection.setEndHeaderSection(writer.getPosition()); footerSection.setStartReadsSection(writer.getPosition()); // copy all reads that belong to the given classes of the given classification: try (IInputReader reader = sourceRMA6File.getReader()) { for (int i = 0; i < list.size(); i++) { reader.seek(list.get(i)); totalReads.set(totalReads.get() + 1); if (pairedReads) { reader.skipBytes(8); // skip over mate UID, note that we can't use it writer.writeLong(0); } // copy read text without decompressing: { int length = reader.readInt(); writer.writeInt(length); length = Math.abs(length); for (int b = 0; b < length; b++) { writer.write(reader.read()); } } final int numberOfMatches = reader.readInt(); // number of matches writer.writeInt(numberOfMatches); totalMatches += numberOfMatches; // copy classifications: { int length = numberOfMatches * cNames.length * 4; for (int b = 0; b < length; b++) { writer.write(reader.read()); } } // copy matches text without decompressing: { int length = reader.readInt(); writer.writeInt(length); length = Math.abs(length); for (int b = 0; b < length; b++) { writer.write(reader.read()); } } progressListener.incrementProgress(); } } } finally { // if user cancels, finish writing file before leaving... long position = writer.getPosition(); footerSection.setEndReadsSection(position); // write the footer section: footerSection.setStartClassificationsSection(position); footerSection.setEndClassificationsSection(position); footerSection.setStartAuxDataSection(position); footerSection.setEndAuxDataSection(position); footerSection.setStartFooterSection(position); footerSection.setNumberOfReads(totalReads.get()); footerSection.setNumberOfMatches(totalMatches); footerSection.write(writer); } } System.err.println("Extraction required " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds"); } }
6,394
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HeaderSectionRMA6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma6/HeaderSectionRMA6.java
/* * HeaderSectionRMA6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.rma6; import jloda.seq.BlastMode; import megan.io.IInputReader; import megan.io.IOutputWriter; import java.io.IOException; /** * header for read-alignment archive format * Daniel Huson, 6.2015 */ public class HeaderSectionRMA6 { private String creator; private long creationDate = 0; private BlastMode blastMode; private boolean pairedReads; private String[] matchClassNames; // classifications for which matches have identifiers /** * read the header * */ public void read(IInputReader reader) throws IOException { final int magicNumber = reader.readInt(); if (magicNumber != RMA6File.MAGIC_NUMBER) { throw new IOException("Not an RMA file"); } final int version = reader.readInt(); if (version != RMA6File.VERSION) { throw new IOException("Not an RMA " + RMA6File.VERSION + " file"); } int minorVersion = reader.readInt(); creator = reader.readString(); creationDate = reader.readLong(); blastMode = BlastMode.valueOf(reader.readString()); pairedReads = (reader.read() == 1); matchClassNames = new String[reader.readInt()]; for (int i = 0; i < matchClassNames.length; i++) { matchClassNames[i] = reader.readString(); } } /** * writer the header * */ public void write(IOutputWriter writer) throws IOException { writer.writeInt(RMA6File.MAGIC_NUMBER); writer.writeInt(RMA6File.VERSION); writer.writeInt(RMA6File.MINOR_VERSION); writer.writeString(creator); if (creationDate == 0) creationDate = System.currentTimeMillis(); writer.writeLong(creationDate); writer.writeString(blastMode.toString()); writer.write(pairedReads ? 1 : 0); writer.writeInt(matchClassNames.length); for (String name : matchClassNames) writer.writeString(name); } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public long getCreationDate() { return creationDate; } public void setCreationDate(long creationDate) { this.creationDate = creationDate; } public BlastMode getBlastMode() { return blastMode; } public void setBlastMode(BlastMode blastMode) { this.blastMode = blastMode; } public boolean isPairedReads() { return pairedReads; } public void setIsPairedReads(boolean isPairedReads) { this.pairedReads = isPairedReads; } public String[] getMatchClassNames() { return matchClassNames; } public void setMatchClassNames(String[] matchClassNames) { this.matchClassNames = matchClassNames; } }
3,663
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAReferencesAnnotator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/DAAReferencesAnnotator.java
/* * DAAReferencesAnnotator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa; import javafx.beans.property.SimpleObjectProperty; import jloda.fx.util.ProgramExecutorService; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.CanceledException; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.accessiondb.AccessAccessionMappingDatabase; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.classification.IdParser; import megan.daa.io.*; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; /** * adds reference annotations to DAA file * Daniel Huson, 8.2105 */ class DAAReferencesAnnotator { /** * add reference annotations to a DAA file * */ public static void apply(String daaFile, boolean doTaxonomy, Collection<String> cNames0, final ProgressListener progress) throws IOException { DAAModifier.removeAllMEGANData(daaFile); final var header = new DAAHeader(daaFile); header.load(); header.loadReferences(false); final String[] cNames; { final var fNamesList = new LinkedList<>(cNames0); if (doTaxonomy && !fNamesList.contains(Classification.Taxonomy)) { fNamesList.add(Classification.Taxonomy); } else if (!doTaxonomy) fNamesList.remove(Classification.Taxonomy); cNames = fNamesList.toArray(new String[0]); } final var cName2ref2class = new int[cNames.length][header.getNumberOfReferences()]; final var service = Executors.newCachedThreadPool(); var exception = new SimpleObjectProperty<Exception>(); try { if (ClassificationManager.canUseMeganMapDBFile()) { System.err.println("Annotating DAA file using FAST mode (accession database and first accession per line)"); progress.setSubtask("Annotating references"); final var chunkSize = ProgramProperties.get("AccessionChunkSize",5000); // don't make this too big, query will exceed SQLITE size limitation final var numberOfTasks = (int) Math.ceil((double) header.getNumberOfReferences() / chunkSize); final var countDownLatch = new CountDownLatch(numberOfTasks); final var numberOfThreads = Math.min(numberOfTasks, ProgramExecutorService.getNumberOfCoresToUse()); //System.err.println("Number of tasks: "+numberOfTasks); //System.err.println("Number of threads: "+numberOfThreads); progress.setMaximum(numberOfTasks / numberOfThreads); progress.setProgress(0); for (var t = 0; t < numberOfThreads; t++) { final var task = t; service.submit(() -> { try (final var accessAccessionMappingDatabase = new AccessAccessionMappingDatabase(ClassificationManager.getMeganMapDBFile())) { final var mapClassificationId2DatabaseRank = accessAccessionMappingDatabase.setupMapClassificationId2DatabaseRank(cNames); final var queries = new String[chunkSize]; for (var r = task * chunkSize; r < header.getNumberOfReferences(); r += numberOfThreads * chunkSize) { try { if (exception.get() != null) return; for (var i = 0; i < chunkSize; i++) { final var a = r + i; if (a < header.getNumberOfReferences()) { queries[i] = getFirstWord(header.getReference(a, null)); } else break; } final var size = Math.min(chunkSize, header.getNumberOfReferences() - r); final var query2ids = accessAccessionMappingDatabase.getValues(queries, size); for (var q = 0; q < size; q++) { final var ids = query2ids.get(queries[q]); if (ids != null) { for (var c = 0; c < cNames.length; c++) { final var dbRank = mapClassificationId2DatabaseRank[c]; if (dbRank < ids.length) cName2ref2class[c][r + q] = ids[dbRank]; } } } } finally { if (task == 0) progress.incrementProgress(); countDownLatch.countDown(); } } } catch (Exception ex) { synchronized (exception) { exception.set(ex); } while (countDownLatch.getCount() > 0) countDownLatch.countDown(); service.shutdownNow(); } }); } try { countDownLatch.await(); } catch (InterruptedException e) { Basic.caught(e); } } else { System.err.println("Annotating DAA file using EXTENDED mode"); final var numberOfThreads = Math.max(1, Math.min(header.getNumberOfReferences(), Math.min(ProgramExecutorService.getNumberOfCoresToUse(), Runtime.getRuntime().availableProcessors()))); final var countDownLatch = new CountDownLatch(numberOfThreads); progress.setSubtask("Annotating references"); progress.setMaximum(header.getNumberOfReferences()); progress.setProgress(0); // determine the names for references: for (var t = 0; t < numberOfThreads; t++) { final var task = t; service.submit(() -> { try { final var idParsers = new IdParser[cNames.length]; // need to use only one database per thread. for (var i = 0; i < cNames.length; i++) { idParsers[i] = ClassificationManager.get(cNames[i], true).getIdMapper().createIdParser(); } for (var r = task; r < header.getNumberOfReferences(); r += numberOfThreads) { final var ref = StringUtils.toString(header.getReference(r, null)); for (var i = 0; i < idParsers.length; i++) { try { cName2ref2class[i][r] = idParsers[i].getIdFromHeaderLine(ref); } catch (IOException e) { Basic.caught(e); } } if (task == 0) progress.setProgress(r); } } catch (Exception ex) { synchronized (exception) { exception.set(ex); } while (countDownLatch.getCount() > 0) countDownLatch.countDown(); service.shutdownNow(); } finally { countDownLatch.countDown(); } }); } try { countDownLatch.await(); } catch (InterruptedException e) { Basic.caught(e); } } if (exception.get() != null) { if (exception.get() instanceof CanceledException) throw (CanceledException) exception.get(); else throw new IOException(exception.get()); } // get all bytes: final var cName2Bytes = new byte[cNames.length][]; final var cName2Size = new int[cNames.length]; final var countDownLatch2 = new CountDownLatch(cNames.length); for (var t = 0; t < cNames.length; t++) { final var task = t; service.submit(() -> { try { final var outs = new ByteOutputStream(1048576); final var w = new OutputWriterLittleEndian(outs); w.writeNullTerminatedString(cNames[task].getBytes()); final var ref2class = cName2ref2class[task]; if (task == 0) { progress.setSubtask("Writing"); progress.setMaximum(ref2class.length); progress.setProgress(0); } for (var classId : ref2class) { w.writeInt(classId); if (task == 0) progress.incrementProgress(); } cName2Bytes[task] = outs.getBytes(); cName2Size[task] = outs.size(); } catch (Exception ex) { System.err.println("Exception during preparation of block: " + cNames[task]); Basic.caught(ex); } finally { countDownLatch2.countDown(); } }); } try { countDownLatch2.await(); } catch (InterruptedException e) { Basic.caught(e); } DAAModifier.appendBlocks(header, BlockType.megan_ref_annotations, cName2Bytes, cName2Size); progress.reportTaskCompleted(); } finally { service.shutdownNow(); } } private static String getFirstWord(byte[] bytes) { var a = 0; while (a < bytes.length && (bytes[a] == '>' || Character.isWhitespace(bytes[a]))) { a++; } var b = a; while (b < bytes.length && (bytes[b] == '_' || Character.isLetterOrDigit(bytes[b]))) { b++; } return new String(bytes, a, b - a); } }
11,934
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Meganize.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/Meganize.java
/* * Meganize.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.CanceledException; import jloda.util.FileUtils; import jloda.util.progress.ProgressListener; import megan.classification.Classification; import megan.core.ContaminantManager; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.daa.connector.DAAConnector; import megan.daa.io.DAAHeader; import megan.daa.io.DAAParser; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * meganizes a DAA file * Daniel Huson, 3.2016 */ public class Meganize { /** * meganizes a DAA file * */ public static void apply(final ProgressListener progress, final String daaFile, final String metaDataFile, final ArrayList<String> cNames, float minScore, float maxExpected, float minPercentIdentity, float topPercent, float minSupportPercent, int minSupport, boolean pairedReads, int pairedReadsSuffixLength, int minReadLength, Document.LCAAlgorithm lcaAlgorithm, Document.ReadAssignmentMode readAssignmentMode, float lcaCoveragePercent, boolean longReads, float minPercentReadToCover, float minPercentReferenceToCover, String contaminantsFile) throws IOException, CanceledException { progress.setTasks("Meganizing", "init"); final long start = System.currentTimeMillis(); DAAReferencesAnnotator.apply(daaFile, true, cNames, progress); if (ProgramProperties.get("enable-database-lookup", false)) System.err.printf("(Reference annotation of file %s took %.1f sec)%n", daaFile, (System.currentTimeMillis() - start) / 1000.0); final Document doc = new Document(); doc.setOpenDAAFileOnlyIfMeganized(false); doc.getMeganFile().setFileFromExistingFile(daaFile, false); doc.getActiveViewers().add(Classification.Taxonomy); doc.getActiveViewers().addAll(cNames); doc.setMinScore(minScore); doc.setMaxExpected(maxExpected); doc.setMinPercentIdentity(minPercentIdentity); doc.setTopPercent(topPercent); doc.setMinSupportPercent(minSupportPercent); doc.setMinSupport(minSupport); doc.setPairedReads(pairedReads); doc.setPairedReadSuffixLength(pairedReadsSuffixLength); doc.setMinReadLength(minReadLength); doc.setBlastMode(DAAParser.getBlastMode(daaFile)); doc.setLcaAlgorithm(lcaAlgorithm); doc.setLcaCoveragePercent(lcaCoveragePercent); doc.setMinPercentReadToCover(minPercentReadToCover); doc.setMinPercentReferenceToCover(minPercentReferenceToCover); doc.setLongReads(longReads); doc.setReadAssignmentMode(readAssignmentMode); if (contaminantsFile.length() > 0) { ContaminantManager contaminantManager = new ContaminantManager(); contaminantManager.read(contaminantsFile); System.err.printf("Contaminants profile: %,d input, %,d total%n", contaminantManager.inputSize(), contaminantManager.size()); doc.getDataTable().setContaminants(contaminantManager.getTaxonIdsString()); doc.setUseContaminantFilter(contaminantManager.size() > 0); } doc.setProgressListener(progress); doc.processReadHits(); // save auxiliary data: doc.saveAuxiliaryData(); if (metaDataFile.length() > 0) { final DAAConnector connector = (DAAConnector) doc.getConnector(); try { System.err.println("Saving metadata:"); SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); sampleAttributeTable.read(new FileReader(metaDataFile), Collections.singletonList(FileUtils.getFileBaseName(FileUtils.getFileNameWithoutPath(daaFile))), false); Map<String, byte[]> label2data = new HashMap<>(); label2data.put(SampleAttributeTable.SAMPLE_ATTRIBUTES, sampleAttributeTable.getBytes()); connector.putAuxiliaryData(label2data); System.err.println("done"); } catch (Exception ex) { Basic.caught(ex); } } // set meganized flag: final DAAHeader header = new DAAHeader(daaFile); header.load(); header.setReserved3(DAAHeader.MEGAN_VERSION); header.save(); if (ProgramProperties.get("enable-database-lookup", false)) System.err.printf("(Meganization of file %s took %.1f sec)%n", daaFile, (System.currentTimeMillis() - start) / 1000.0); } }
5,418
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OutputWriterLittleEndian.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/OutputWriterLittleEndian.java
/* * OutputWriterLittleEndian.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; import jloda.util.StringUtils; import megan.io.FileInputStreamAdapter; import megan.io.FileOutputStreamAdapter; import megan.io.IOutput; import java.io.Closeable; import java.io.File; import java.io.IOException; /** * write data in little endian format * Daniel Huson, 8.2015 */ public class OutputWriterLittleEndian implements Closeable { private final IOutput outs; private final byte[] bytes = new byte[8]; private final java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(8); /** * constructor * */ public OutputWriterLittleEndian(IOutput outs) { this.outs = outs; } /** * write a byte * */ public void write(int b) throws IOException { outs.write(b); } /** * write bytes * */ public void write(byte[] bytes, int offset, int len) throws IOException { outs.write(bytes, offset, len); } /** * write char, little endian * */ public void writeChar(char a) throws IOException { outs.write((byte) (a)); outs.write((byte) (a >> 8)); } /** * write int, little endian * */ public void writeInt(int a) throws IOException { outs.write((byte) (a)); outs.write((byte) (a >> 8)); outs.write((byte) (a >> 16)); outs.write((byte) (a >> 24)); } /** * write long, little endian * */ public void writeLong(long a) throws IOException { outs.write((byte) (a)); outs.write((byte) (a >> 8)); outs.write((byte) (a >> 16)); outs.write((byte) (a >> 24)); outs.write((byte) (a >> 32)); outs.write((byte) (a >> 40)); outs.write((byte) (a >> 48)); outs.write((byte) (a >> 56)); } /** * write float, little endian * */ public void writeFloat(float a) throws IOException { byteBuffer.putFloat(0, a); byteBuffer.rewind(); byteBuffer.get(bytes, 0, 4); swap(bytes, 4); outs.write(bytes, 0, 4); } /** * write double, little endian * */ public void writeDouble(double a) throws IOException { byteBuffer.putDouble(0, a); byteBuffer.rewind(); byteBuffer.get(bytes, 0, 8); swap(bytes, 8); outs.write(bytes, 0, 8); } /** * swap order of bytes * */ private void swap(byte[] bytes, int len) { int top = len / 2; int j = len - 1; for (int i = 0; i < top; i++, j--) { byte b = bytes[i]; bytes[i] = bytes[j]; bytes[j] = b; } } /** * write bytes as a null-terminated string * */ public void writeNullTerminatedString(byte[] bytes) throws IOException { int pos = 0; while (pos < bytes.length) { if (bytes[pos] == 0) break; pos++; } if (pos > 0) write(bytes, 0, pos); write((byte) 0); } /** * write size-prefixed bytes * */ public void writeSizedPrefixedBytes(byte[] bytes) throws IOException { writeSizedPrefixedBytes(bytes, 0, bytes.length); } /** * write size-prefixed bytes * */ private void writeSizedPrefixedBytes(byte[] bytes, int offset, int length) throws IOException { writeInt(length); write(bytes, offset, length); } /** * get current position * * @return position */ public long getPosition() throws IOException { return outs.getPosition(); } /** * close * */ public void close() throws IOException { outs.close(); } public static void main(String[] args) throws IOException { FileOutputStreamAdapter outs = new FileOutputStreamAdapter(new File("/tmp/xxx")); try (OutputWriterLittleEndian w = new OutputWriterLittleEndian(outs)) { w.writeInt(1234567); w.writeLong(123456789123456789L); w.writeFloat(9999999); w.writeDouble(4E09); w.writeNullTerminatedString("HELLO".getBytes()); w.writeSizedPrefixedBytes("?AGAIN?".getBytes(), 1, 5); } FileInputStreamAdapter ins = new FileInputStreamAdapter("/tmp/xxx"); try (InputReaderLittleEndian r = new InputReaderLittleEndian(ins)) { System.err.println(r.readInt()); System.err.println(r.readLong()); System.err.println(r.readFloat()); System.err.println(r.readDouble()); byte[] bytes = new byte[100]; int len = r.readNullTerminatedBytes(bytes); System.err.println(StringUtils.toString(bytes, 0, len)); ByteInputBuffer buffer = new ByteInputBuffer(); r.readSizePrefixedBytes(buffer); System.err.println(buffer); } } }
5,747
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ByteInputStream.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/ByteInputStream.java
/* * ByteInputStream.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import megan.io.IInput; import java.io.ByteArrayInputStream; /** * Byte input stream * 8.2015 */ public class ByteInputStream extends ByteArrayInputStream implements IInput { private static final byte[] EMPTY_ARRAY = new byte[0]; public ByteInputStream() { this(EMPTY_ARRAY, 0); } public ByteInputStream(byte[] buf, int length) { super(buf, 0, length); } public ByteInputStream(byte[] buf, int offset, int length) { super(buf, offset, length); } public byte[] getBytes() { return this.buf; } public int getCount() { return this.count; } public void close() { this.reset(); } public void setBuf(byte[] buf) { this.buf = buf; this.pos = 0; this.count = buf.length; } @Override public int skipBytes(int bytes) { return (int) this.skip(bytes); } @Override public long getPosition() { return this.count; } @Override public long length() { return this.count; } @Override public boolean supportsSeek() { return false; } @Override public void seek(long pos) { } }
2,032
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignMode.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/AlignMode.java
/* * AlignMode.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.seq.BlastMode; /** * alignment mode enum * Daniel Huson, 8.2015 */ public enum AlignMode { blastp, blastx, blastn; public static byte rank(AlignMode mode) { return (byte) switch (mode) { case blastp -> 2; case blastx -> 3; case blastn -> 4; }; } public static AlignMode value(int rank) { return switch (rank) { case 2 -> blastp; default /* case 3 */ -> blastx; case 4 -> blastn; }; } public static BlastMode getBlastMode(int rank) { return switch (rank) { case 2 -> BlastMode.BlastP; default /* case 3 */ -> BlastMode.BlastX; case 4 -> BlastMode.BlastN; }; } }
1,553
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PackedOperation.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/PackedOperation.java
/* * PackedOperation.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; /** * A packed operation * Daniel Huson, 8.2015 */ public class PackedOperation { private final int code; /** * constructor * */ public PackedOperation(int code) { this.code = code; } /** * constructor * */ public PackedOperation(PackedTranscript.EditOperation op, int count) { code = (byte) (((op.ordinal() << 6) | count) & 0xFF); } /** * constructor * */ public PackedOperation(PackedTranscript.EditOperation op, byte value) { code = ((op.ordinal() << 6) | (int) value) & 0xFF; } /** * get the operation * */ public PackedTranscript.EditOperation getEditOperation() { return PackedTranscript.EditOperation.values()[code >>> 6]; } public int getOpCode() { return code >>> 6; } /** * get the count * */ public int getCount() { return code & 63; } /** * get the letter * */ public byte getLetter() { return (byte) (code & 63); } static public PackedOperation terminator() { return new PackedOperation(PackedTranscript.EditOperation.op_match, 0); } public boolean equals(Object op) { return op instanceof PackedOperation && code == ((PackedOperation) op).code; } public String toString() { return "" + getEditOperation() + "," + getCount(); } }
2,254
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAParser.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAParser.java
/* * DAAParser.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.seq.BlastMode; import jloda.util.Basic; import jloda.util.ByteInputBuffer; import jloda.util.ByteOutputBuffer; import jloda.util.Pair; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.io.FileInputStreamAdapter; import megan.io.FileRandomAccessReadOnlyAdapter; import megan.parsers.blast.PostProcessMatches; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.concurrent.BlockingQueue; /** * DAA file * Daniel Huson, 8.2015 */ public class DAAParser { private final DAAHeader header; private final byte[] sourceAlphabet; private final byte[] alignmentAlphabet; private final BlastMode blastMode; // blocking queue sentinel: public final static Pair<byte[], byte[]> SENTINEL_SAM_ALIGNMENTS = new Pair<>(null, null); public final static Pair<DAAQueryRecord, DAAMatchRecord[]> SENTINEL_QUERY_MATCH_BLOCKS = new Pair<>(); private final IntervalTree<DAAMatchRecord> intervalTree = new IntervalTree<>(); // used in parsing of long reads private final ArrayList<DAAMatchRecord> list = new ArrayList<>(); /** * constructor */ public DAAParser(final String fileName) throws IOException { this(new DAAHeader(fileName, true)); } /** * constructor */ public DAAParser(final DAAHeader header) { this.header = header; switch (header.getAlignMode()) { case blastx: sourceAlphabet = Translator.DNA_ALPHABET; if (header.getDiamondBuild() >= 132) alignmentAlphabet = Translator.AMINO_ACID_ALPHABET; else alignmentAlphabet = Translator.AMINO_ACID_ALPHABET_PRE_DIAMOND_132; break; case blastp: if (header.getDiamondBuild() >= 132) { alignmentAlphabet = Translator.AMINO_ACID_ALPHABET; sourceAlphabet = Translator.AMINO_ACID_ALPHABET; } else { alignmentAlphabet = Translator.AMINO_ACID_ALPHABET_PRE_DIAMOND_132; sourceAlphabet = Translator.AMINO_ACID_ALPHABET_PRE_DIAMOND_132; } break; case blastn: sourceAlphabet = Translator.DNA_ALPHABET; alignmentAlphabet = Translator.DNA_ALPHABET; break; default: sourceAlphabet = null; alignmentAlphabet = null; } blastMode = AlignMode.getBlastMode(header.getModeRank()); } /** * read the header of a DAA file and all reference names * */ public static boolean isMeganizedDAAFile(String fileName, boolean checkWhetherMeganized) throws IOException { try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(fileName))) { long magicNumber = ins.readLong(); if (magicNumber != DAAHeader.MAGIC_NUMBER) throw new IOException("Input file is not a DAA file."); long version = ins.readLong(); if (version > DAAHeader.DAA_VERSION) throw new IOException("DAA version requires later version of MEGAN."); if (!checkWhetherMeganized) return true; ins.skip(76); int meganVersion = ins.readInt(); // reserved3 if (meganVersion <= 0) return false; if (meganVersion > DAAHeader.MEGAN_VERSION) throw new IOException("DAA version requires later version of MEGAN."); else return true; } } /** * get the blast mode * * @return blast mode */ public BlastMode getBlastMode() { return blastMode; } public static BlastMode getBlastMode(String fileName) { try { DAAParser daaParser = new DAAParser(fileName); return daaParser.getBlastMode(); } catch (IOException ignored) { } return BlastMode.Unknown; } /** * get all alignments in SAM format * */ void getAllAlignmentsSAMFormat(int maxMatchesPerRead, BlockingQueue<Pair<byte[], byte[]>> outputQueue, boolean parseLongReads) throws IOException { final ByteInputBuffer inputBuffer = new ByteInputBuffer(); final ByteOutputBuffer outputBuffer = new ByteOutputBuffer(100000); final float minProportionCoverToDominate; final float topProportionScoreToDominate; if (parseLongReads) { final PostProcessMatches postProcessMatches = new PostProcessMatches(); postProcessMatches.setParseLongReads(true); minProportionCoverToDominate = postProcessMatches.getMinProportionCoverToStronglyDominate(); topProportionScoreToDominate = postProcessMatches.getTopProportionScoreToStronglyDominate(); } else { minProportionCoverToDominate = 0; topProportionScoreToDominate = 0; } try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(header.getFileName())); final InputReaderLittleEndian refIns = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(header.getFileName()))) { ins.seek(header.getLocationOfBlockInFile(header.getAlignmentsBlockIndex())); final DAAQueryRecord queryRecord = new DAAQueryRecord(this); final DAAMatchRecord matchRecord = new DAAMatchRecord(queryRecord); for (int a = 0; a < header.getQueryRecords(); a++) { inputBuffer.rewind(); queryRecord.setLocation(ins.getPosition()); ins.readSizePrefixedBytes(inputBuffer); queryRecord.parseBuffer(inputBuffer); if (!parseLongReads) { int numberOfMatches = 0; while (inputBuffer.getPosition() < inputBuffer.size()) { if (++numberOfMatches > maxMatchesPerRead) break; matchRecord.parseBuffer(inputBuffer, refIns); SAMUtilities.createSAM(this, matchRecord, outputBuffer, alignmentAlphabet); } } else // parse long reads { intervalTree.clear(); while (inputBuffer.getPosition() < inputBuffer.size()) { final DAAMatchRecord aMatchRecord = new DAAMatchRecord(queryRecord); aMatchRecord.parseBuffer(inputBuffer, refIns); intervalTree.add(aMatchRecord.getQueryBegin(), aMatchRecord.getQueryEnd(), aMatchRecord); } list.clear(); for (Interval<DAAMatchRecord> interval : intervalTree) { boolean covered = false; for (Interval<DAAMatchRecord> other : intervalTree.getIntervals(interval)) { if (other.overlap(interval) >= minProportionCoverToDominate * interval.length() && topProportionScoreToDominate * other.getData().getScore() > interval.getData().getScore()) { covered = true; break; } } if (!covered) list.add(interval.getData()); } for (DAAMatchRecord aMatchRecord : list) { SAMUtilities.createSAM(this, aMatchRecord, outputBuffer, alignmentAlphabet); } } if (outputBuffer.size() > 0) { outputQueue.put(new Pair<>(queryRecord.getQueryFastA(sourceAlphabet), outputBuffer.copyBytes())); outputBuffer.rewind(); } } outputQueue.put(SENTINEL_SAM_ALIGNMENTS); // System.err.println(String.format("Total reads: %,15d", header.getQueryRecords())); // System.err.println(String.format("Alignments: %,15d", alignmentCount)); } catch (InterruptedException e) { Basic.caught(e); } } /** * get all queries with matches * */ void getAllQueriesAndMatches(boolean wantMatches, int maxMatchesPerRead, BlockingQueue<Pair<DAAQueryRecord, DAAMatchRecord[]>> outputQueue, boolean longReads) throws IOException { final ByteInputBuffer inputBuffer = new ByteInputBuffer(); try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(header.getFileName())); final InputReaderLittleEndian refIns = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(header.getFileName()))) { ins.seek(header.getLocationOfBlockInFile(header.getAlignmentsBlockIndex())); final DAAMatchRecord[] matchRecords = new DAAMatchRecord[maxMatchesPerRead]; for (int a = 0; a < header.getQueryRecords(); a++) { final Pair<DAAQueryRecord, DAAMatchRecord[]> pair = readQueryAndMatches(ins, refIns, wantMatches, maxMatchesPerRead, inputBuffer, matchRecords, longReads); outputQueue.put(pair); } outputQueue.put(SENTINEL_QUERY_MATCH_BLOCKS); } catch (InterruptedException e) { Basic.caught(e); } } /** * read a query and its matches * * @param inputBuffer used internally, if non null * @param matchRecords used internally, if non null * @return query and matches */ public Pair<DAAQueryRecord, DAAMatchRecord[]> readQueryAndMatches(InputReaderLittleEndian ins, InputReaderLittleEndian refIns, boolean wantMatches, int maxMatchesPerRead, ByteInputBuffer inputBuffer, DAAMatchRecord[] matchRecords, boolean longReads) throws IOException { final DAAQueryRecord queryRecord = new DAAQueryRecord(this); if (inputBuffer == null) inputBuffer = new ByteInputBuffer(); else inputBuffer.rewind(); queryRecord.setLocation(ins.getPosition()); ins.readSizePrefixedBytes(inputBuffer); queryRecord.parseBuffer(inputBuffer); int numberOfMatches = 0; if (wantMatches) { if (!longReads) { if (matchRecords == null) matchRecords = new DAAMatchRecord[maxMatchesPerRead]; while (inputBuffer.getPosition() < inputBuffer.size()) { DAAMatchRecord matchRecord = new DAAMatchRecord(queryRecord); try { matchRecord.parseBuffer(inputBuffer, refIns); if (numberOfMatches < maxMatchesPerRead) matchRecords[numberOfMatches++] = matchRecord; else break; } catch (Exception ex) { Basic.caught(ex); } } } else { intervalTree.clear(); final Set<Interval<DAAMatchRecord>> alive = new HashSet<>(); while (inputBuffer.getPosition() < inputBuffer.size()) { final DAAMatchRecord aMatchRecord = new DAAMatchRecord(queryRecord); aMatchRecord.parseBuffer(inputBuffer, refIns); final Interval<DAAMatchRecord> interval = new Interval<>(aMatchRecord.getQueryBegin(), aMatchRecord.getQueryEnd(), aMatchRecord); if (interval.getStart() > 10 && interval.getEnd() < queryRecord.getQueryLength() - 10 && aMatchRecord.getSubjectLen() < 0.8 * aMatchRecord.getTotalSubjectLen()) continue; // skip mini alignment that are not at the beginning or end of the read boolean covered = false; for (Interval<DAAMatchRecord> other : intervalTree.getIntervals(interval)) { if (alive.contains(other)) { if (interval.overlap(other) >= 0.5 * interval.length() && interval.getData().getScore() < 0.95 * other.getData().getScore()) { covered = true; break; } else if (interval.overlap(other) >= 0.5 * other.length() && other.getData().getScore() < 0.95 * interval.getData().getScore()) { alive.remove(other); } } } if (!covered) { alive.add(interval); intervalTree.add(interval); } } numberOfMatches = alive.size(); if (matchRecords == null || numberOfMatches >= matchRecords.length) { matchRecords = new DAAMatchRecord[numberOfMatches]; } { int i = 0; for (Interval<DAAMatchRecord> interval : intervalTree.getAllIntervals(true)) { if (alive.contains(interval)) matchRecords[i++] = interval.getData(); } } } } if (numberOfMatches > 0) { final DAAMatchRecord[] usedMatchRecords = new DAAMatchRecord[numberOfMatches]; System.arraycopy(matchRecords, 0, usedMatchRecords, 0, numberOfMatches); return new Pair<>(queryRecord, usedMatchRecords); } else return new Pair<>(queryRecord, new DAAMatchRecord[0]); } /** * get the header block * * @return header */ public DAAHeader getHeader() { return header; } public byte[] getSourceAlphabet() { return sourceAlphabet; } public byte[] getAlignmentAlphabet() { return alignmentAlphabet; } public int getRefAnnotation(String cName, int refId) { return header.getRefAnnotation(header.getRefAnnotationIndex(cName), refId); } /** * gets a block as a string of bytes * * @return block */ public static byte[] getBlock(DAAHeader header, BlockType blockType) throws IOException { int index = header.getIndexForBlockType(blockType); if (index == -1) return null; long location = header.getLocationOfBlockInFile(index); if (header.getBlockSize(index) > Integer.MAX_VALUE - 10) throw new IOException("Internal error: block too big"); int size = (int) header.getBlockSize(index); try (RandomAccessFile raf = new RandomAccessFile(header.getFileName(), "r")) { raf.seek(location); byte[] bytes = new byte[size]; raf.read(bytes); return bytes; } } }
15,736
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PackedTranscript.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/PackedTranscript.java
/* * PackedTranscript.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; import java.util.ArrayList; /** * packed alignment transcript * daniel huson, 8.2105 */ public class PackedTranscript { public enum EditOperation {op_match, op_insertion, op_deletion, op_substitution} private PackedOperation[] transcript = new PackedOperation[100]; private int size; /** * read a packed transcript from a buffer * */ public void read(ByteInputBuffer buffer) { size = 0; for (PackedOperation op = new PackedOperation(buffer.read()); !op.equals(PackedOperation.terminator()); op = new PackedOperation(buffer.read())) { if (size == transcript.length - 1) { final PackedOperation[] tmp = new PackedOperation[2 * transcript.length]; System.arraycopy(transcript, 0, tmp, 0, size); transcript = tmp; } transcript[size++] = op; } } private PackedOperation getPackedOperation(int i) { return transcript[i]; } /** * get number of operations * * @return size */ private int size() { return size; } /** * gather all edits into combined operations * * @return combined operations */ public CombinedOperation[] gather() { final ArrayList<CombinedOperation> list = new ArrayList<>(); for (int i = 0; i < size(); i++) { PackedOperation pop = getPackedOperation(i); final CombinedOperation cop = new CombinedOperation(); cop.setEditOperation(pop.getEditOperation()); if (pop.getEditOperation().equals(EditOperation.op_deletion) || pop.getEditOperation().equals(EditOperation.op_substitution)) { cop.setLetter(pop.getLetter()); cop.setCount(1); } else { cop.setCount(0); while (true) { cop.incrementCount(pop.getCount()); i++; if (i == size()) break; pop = getPackedOperation(i); if (cop.getEditOperation() != pop.getEditOperation()) break; } i--; } list.add(cop); } return list.toArray(new CombinedOperation[0]); } }
3,192
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Utilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/Utilities.java
/* * Utilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; /** * basic utilities * Daniel Huson, 8.2015 */ public class Utilities { /** * determines whether two byte arrays are equalOverShorterOfBoth over the whole minimum of their two lengths * * @return true, if shared indices have same value */ public static boolean equalOverShorterOfBoth(byte[] a, byte[] b) { int top = Math.min(a.length, b.length); for (int i = 0; i < top; i++) { if (a[i] != b[i]) return false; } return true; } /** * copies the src to the target, resizing the target, if necessary * * @return result, possibly resized */ public static byte[] copy(byte[] src, byte[] target) { if (target.length < src.length) { target = new byte[src.length]; } System.arraycopy(src, 0, target, 0, src.length); return target; } /** * computes percent identity * * @return percent identity */ public static int computePercentIdentity(DAAMatchRecord match) { return match.getIdentities() * 100 / match.getLen(); } }
1,955
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAModifier.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAModifier.java
/* * DAAModifier.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; /** * modifies a DAA file * Daniel Huson, 8.2105 */ public class DAAModifier { /** * remove all data added by MEGAN */ public static void removeAllMEGANData(String fileName) throws IOException { final var header = new DAAHeader(fileName); header.load(); var newFileSize = -1L; for (var i = 0; i < header.getBlockTypeRankArrayLength(); i++) { var type = header.getBlockType(i); if (type != BlockType.empty) { if (type.toString().startsWith("megan")) { if (newFileSize == -1L) newFileSize = header.getLocationOfBlockInFile(i); header.setBlockTypeRank(i, BlockType.rank(BlockType.empty)); header.setBlockSize(i, 0L); } } if (newFileSize != -1) { try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw")) { raf.setLength(newFileSize); } } if (newFileSize != -1 || header.getReserved3() > 0) { header.setReserved3(0); header.save(); } } } /** * remove all classification data added by MEGAN (leaves ref annotations) */ public static void removeMEGANClassificationData(DAAHeader header) throws IOException { var hasMeganBlock = false; var meganStart = header.getHeaderSize(); for (var i = 0; i < header.getBlockTypeRankArrayLength(); i++) { var type = header.getBlockType(i); if (type != BlockType.empty) { if (type.toString().startsWith("megan") && !type.equals(BlockType.megan_ref_annotations)) { hasMeganBlock = true; header.setBlockTypeRank(i, BlockType.rank(BlockType.empty)); header.setBlockSize(i, 0L); } else meganStart += header.getBlockSize(i); } } if (hasMeganBlock) { header.save(); try (RandomAccessFile raf = new RandomAccessFile(header.getFileName(), "rw")) { raf.setLength(meganStart); } } } /** * replace a block * */ public static void replaceBlock(DAAHeader header, BlockType blockType, byte[] bytes, int size) throws IOException { var index = header.getIndexForBlockType(blockType); { if (index != -1) { header.setBlockTypeRank(index, BlockType.rank(BlockType.empty)); header.setBlockSize(index, 0); if (index >= header.getLastDefinedBlockIndex()) { var newSize = header.getLocationOfBlockInFile(index); if (newSize > 0) { try (var raf = new RandomAccessFile(header.getFileName(), "rw")) { raf.setLength(newSize); } } } else throw new IOException("Can't replace block, not last"); } } try (var outs = new BufferedOutputStream(new FileOutputStream(header.getFileName(), true))) { // append index = header.getFirstAvailableBlockIndex(); header.setBlockTypeRank(index, BlockType.rank(blockType)); header.setBlockSize(index, size); outs.write(bytes, 0, size); } header.save(); } /** * add new blocks * */ public static void appendBlocks(DAAHeader header, BlockType[] types, byte[][] blocks, int[] sizes) throws IOException { try (var outs = new BufferedOutputStream(new FileOutputStream(header.getFileName(), true))) { // append to file... for (var i = 0; i < blocks.length; i++) { final var bytes = blocks[i]; final var size = sizes[i]; final var index = header.getFirstAvailableBlockIndex(); header.setBlockTypeRank(index, BlockType.rank(types[i])); header.setBlockSize(index, size); outs.write(bytes, 0, size); } } header.save(); // overwrite header } /** * append new blocks * */ public static void appendBlocks(DAAHeader header, BlockType type, byte[][] blocks, int[] sizes) throws IOException { var types = new BlockType[blocks.length]; Arrays.fill(types, type); appendBlocks(header, types, blocks, sizes); } }
5,531
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAHeader.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAHeader.java
/* * DAAHeader.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.Basic; import jloda.util.StringUtils; import megan.classification.Classification; import megan.io.FileInputStreamAdapter; import megan.io.FileRandomAccessReadOnlyAdapter; import megan.io.FileRandomAccessReadWriteAdapter; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * DAA header block * Daniel Huson, 8.2015 */ public class DAAHeader { public final static long MAGIC_NUMBER = 4327487858190246763L; public final static long DAA_VERSION = 1L; // changed from 0 to 1 on Jan-25, 2018 public final static int MEGAN_VERSION = 6; private final String fileName; // header1 private long magicNumber; private long version; // header2: private long diamondBuild; private long dbSeqs; private long dbSeqsUsed; private long dbLetters; private long flags; private long queryRecords; private int modeRank; private int gapOpen; private int gapExtend; private int reward; private int penalty; private int reserved1; private int reserved2; private int reserved3; private double k; private double lambda; private double reserved4; private double reserved5; private final byte[] scoreMatrix = new byte[16]; private final long[] blockSize = new long[256]; private final byte[] blockTypeRank = new byte[256]; // references: private byte[][] references; private int[] refLengths; private final int referenceLocationChunkBits = 6; // 6 bits = 64 chunk size private final int referenceLocationChunkSize = 1 << referenceLocationChunkBits; private long[] referenceLocations; // location of every 2^referenceLocationChunkBits reference // ref annotations: private int numberOfRefAnnotations; private final int[][] refAnnotations = new int[256][]; private final String[] refAnnotationNames = new String[256]; private int refAnnotationIndexForTaxonomy = -1; // helper variables: private String scoreMatrixName; private long headerSize; private int refNamesBlockIndex = -1; private int refLengthsBlockIndex = -1; private int alignmentsBlockIndex = -1; private double lnK; /** * constructor * */ public DAAHeader(String fileName) { this.fileName = fileName; } /** * constructor * */ public DAAHeader(String fileName, boolean load) throws IOException { this.fileName = fileName; if (load) load(); } /** * read the header of a DAA file and all reference names * */ public void load() throws IOException { if (magicNumber == 0) { //System.err.println("Loading DAA header..."); try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(fileName))) { magicNumber = ins.readLong(); if (magicNumber != MAGIC_NUMBER) throw new IOException("Input file is not a DAA file."); version = ins.readLong(); if (version > DAA_VERSION) throw new IOException("DAA version not supported by this version of MEGAN."); diamondBuild = ins.readLong(); dbSeqs = ins.readLong(); dbSeqsUsed = ins.readLong(); dbLetters = ins.readLong(); flags = ins.readLong(); queryRecords = ins.readLong(); modeRank = ins.readInt(); gapOpen = ins.readInt(); gapExtend = ins.readInt(); reward = ins.readInt(); penalty = ins.readInt(); reserved1 = ins.readInt(); reserved2 = ins.readInt(); reserved3 = ins.readInt(); k = ins.readDouble(); lambda = ins.readDouble(); reserved4 = ins.readDouble(); reserved5 = ins.readDouble(); for (int i = 0; i < scoreMatrix.length; i++) { scoreMatrix[i] = (byte) ins.read(); } scoreMatrixName = StringUtils.toString(scoreMatrix); for (int i = 0; i < blockSize.length; i++) blockSize[i] = ins.readLong(); if (blockSize[0] == 0) throw new IOException("Invalid DAA file. DIAMOND run probably has not completed successfully."); for (int i = 0; i < blockTypeRank.length; i++) { blockTypeRank[i] = (byte) ins.read(); switch (BlockType.value(blockTypeRank[i])) { case ref_names -> { if (refNamesBlockIndex != -1) throw new IOException("DAA file contains multiple ref_names blocks, not implemented."); refNamesBlockIndex = i; } case ref_lengths -> { if (refLengthsBlockIndex != -1) throw new IOException("DAA file contains multiple ref_lengths blocks, not implemented."); refLengthsBlockIndex = i; } case alignments -> { if (alignmentsBlockIndex != -1) throw new IOException("DAA file contains multiple alignments blocks, not implemented."); alignmentsBlockIndex = i; } } } if (refNamesBlockIndex == -1) throw new IOException("DAA file contains 0 ref_names blocks, not implemented."); if (refLengthsBlockIndex == -1) throw new IOException("DAA file contains 0 ref_lengths blocks, not implemented."); if (alignmentsBlockIndex == -1) throw new IOException("DAA file contains 0 alignments blocks, not implemented."); if (refLengthsBlockIndex < refNamesBlockIndex) throw new IOException("DAA file contains ref_lengths block before ref_names block, not implemented."); headerSize = ins.getPosition(); lnK = Math.log(k); } } } /** * load all references from file (if not already loaded) * */ public void loadReferences(boolean loadOnDemand) throws IOException { if (references == null) { //System.err.println("Loading DAA references..."); try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(fileName))) { ins.skip(getLocationOfBlockInFile(getRefNamesBlockIndex())); initializeReferences((int) getDbSeqsUsed(), loadOnDemand); if (loadOnDemand) { // load on demand for (int r = 0; r < getDbSeqsUsed(); r++) { if ((r & (referenceLocationChunkSize - 1)) == 0) { referenceLocations[r >>> referenceLocationChunkBits] = ins.getPosition(); } ins.skipNullTerminatedBytes(); } } else { // load all now for (int r = 0; r < getDbSeqsUsed(); r++) { setReference(r, ins.readNullTerminatedBytes().getBytes()); } } initializeRefLengths((int) getDbSeqsUsed()); for (int i = 0; i < getDbSeqsUsed(); i++) { setRefLength(i, ins.readInt()); } } } } private void initializeReferences(int numberOfReferences, boolean loadOnDemand) { this.references = new byte[numberOfReferences][]; if (loadOnDemand) this.referenceLocations = new long[1 + (numberOfReferences >>> referenceLocationChunkBits)]; } /** * get a reference header * * @return reference header */ public byte[] getReference(final int i, final InputReaderLittleEndian ins) throws IOException { if (references[i] != null) return references[i]; if (ins == null) throw new IOException("getReference(i,ins==null)"); // we need to load: int iChunk = (i >>> referenceLocationChunkBits); final long savePosition = ins.getPosition(); ins.seek(referenceLocations[iChunk]); int start = iChunk * referenceLocationChunkSize; // the smallest multiple of 64 that is <= i // System.err.println("i "+i+" start "+start+" (i-start) "+(i-start)); int stop = Math.min((int) getDbSeqsUsed(), start + referenceLocationChunkSize); for (int r = start; r < stop; r++) { setReference(r, ins.readNullTerminatedBytes().getBytes()); } ins.seek(savePosition); // restore current position // System.err.println("got: "+((stop-start)+" more entries")); return references[i]; } /** * load all reference annotations from file * */ public void loadRefAnnotations() throws IOException { numberOfRefAnnotations = 0; refAnnotationIndexForTaxonomy = -1; try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileInputStreamAdapter(fileName))) { for (int b = 0; b < blockTypeRank.length; b++) { if (getBlockType(b) == BlockType.megan_ref_annotations) { ins.seek(getLocationOfBlockInFile(b)); refAnnotationNames[numberOfRefAnnotations] = ins.readNullTerminatedBytes(); if (refAnnotationNames[numberOfRefAnnotations].equals(Classification.Taxonomy)) refAnnotationIndexForTaxonomy = numberOfRefAnnotations; int[] annotations = refAnnotations[numberOfRefAnnotations] = new int[getNumberOfReferences()]; for (int i = 0; i < getNumberOfReferences(); i++) { annotations[i] = ins.readInt(); } numberOfRefAnnotations++; } } } } public String getFileName() { return fileName; } public long getMagicNumber() { return magicNumber; } public long getVersion() { return version; } public long getDiamondBuild() { return diamondBuild; } public long getDbSeqs() { return dbSeqs; } public long getDbSeqsUsed() { return dbSeqsUsed; } private long getDbLetters() { return dbLetters; } public long getFlags() { return flags; } public long getQueryRecords() { return queryRecords; } public int getModeRank() { return modeRank; } public int getGapOpen() { return gapOpen; } public int getGapExtend() { return gapExtend; } public int getReward() { return reward; } public int getPenalty() { return penalty; } public int getReserved1() { return reserved1; } public int getReserved2() { return reserved2; } public int getReserved3() { return reserved3; } public void setReserved3(int reserved3) { this.reserved3 = reserved3; } public double getK() { return k; } public double getLambda() { return lambda; } public double getReserved4() { return reserved4; } public double getReserved5() { return reserved5; } public byte[] getScoreMatrix() { return scoreMatrix; } public long getBlockSize(int i) { return blockSize[i]; } public void setBlockSize(int i, long size) { blockSize[i] = size; } public int getBlockTypeRankArrayLength() { return blockSize.length; } public byte getBlockTypeRank(int i) { return blockTypeRank[i]; } public BlockType getBlockType(int i) { return BlockType.value(blockTypeRank[i]); } public void setBlockTypeRank(int i, byte rank) { blockTypeRank[i] = rank; } public int getNumberOfReferences() { return references == null ? 0 : references.length; } private void setReference(int i, byte[] reference) { references[i] = reference; } public int getRefLength(int i) { return refLengths[i]; } private void setRefLength(int i, int length) { refLengths[i] = length; } private void initializeRefLengths(int numberOfReferences) { this.refLengths = new int[numberOfReferences]; } public String getScoreMatrixName() { return scoreMatrixName; } public long getHeaderSize() { return headerSize; } private int getRefNamesBlockIndex() { return refNamesBlockIndex; } public int getRefLengthsBlockIndex() { return refLengthsBlockIndex; } public int getAlignmentsBlockIndex() { return alignmentsBlockIndex; } public double getLnK() { return lnK; } /** * gets the first available block index. This is the first index of a block that is empty and is not followed by any non-empty block * * @return first available block index or -1, if available */ public int getFirstAvailableBlockIndex() { int index = getLastDefinedBlockIndex() + 1; if (index < getBlockTypeRankArrayLength()) return index; else return -1; } /** * get the first index for the given blockType, or -1, if not found * * @return index or -1 */ public int getIndexForBlockType(BlockType blockType) { for (int i = 0; i < getBlockTypeRankArrayLength(); i++) { if (getBlockType(i) == blockType) return i; } return -1; } /** * gets the index of the last defined block * * @return highest index of any defined block */ public int getLastDefinedBlockIndex() { final int emptyRank = BlockType.rank(BlockType.empty); for (int i = blockTypeRank.length - 1; i >= 0; i--) { if (blockTypeRank[i] != emptyRank) return i; } return -1; } public long getLocationOfBlockInFile(int blockIndex) { long location = getHeaderSize(); for (int i = 0; i < blockIndex; i++) location += getBlockSize(i); return location; } public AlignMode getAlignMode() { return AlignMode.value(modeRank); } public long computeBlockStart(int index) { long start = headerSize; for (int k = 0; k < index; k++) start += blockSize[k]; return start; } /** * gets the index assigned to a named reference annotation * * @return index */ public int getRefAnnotationIndex(String cName) { for (int i = 0; i < numberOfRefAnnotations; i++) { if (refAnnotationNames[i] != null && refAnnotationNames[i].equals(cName)) return i; } return -1; } public int getRefAnnotationIndexForTaxonomy() { return refAnnotationIndexForTaxonomy; } /** * returns the reference annotation for a given reference annotation index and a given refNumber * * @return reference annotation */ public int getRefAnnotation(int refAnnotationIndex, int refNumber) { if (refAnnotationIndex < 0 || refAnnotationIndex >= refAnnotations.length) return 0; return refAnnotations[refAnnotationIndex][refNumber]; } public String getRefAnnotationName(int i) { return refAnnotationNames[i]; } public int getNumberOfRefAnnotations() { return numberOfRefAnnotations; } public String[] getRefAnnotationNames() { final List<String> list = new ArrayList<>(); try (InputReaderLittleEndian reader = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(fileName))) { for (int i = 0; i < getBlockTypeRankArrayLength(); i++) { if (getBlockType(i) == BlockType.megan_ref_annotations) { final long pos = getLocationOfBlockInFile(i); reader.seek(pos); final String name = reader.readNullTerminatedBytes(); list.add(name); } } } catch (IOException e) { Basic.caught(e); } return list.toArray(new String[0]); } /** * read the header of a DAA file and all reference names * */ public void save() throws IOException { try (OutputWriterLittleEndian outs = new OutputWriterLittleEndian(new FileRandomAccessReadWriteAdapter(fileName, "rw"))) { outs.writeLong(magicNumber); outs.writeLong(version); outs.writeLong(diamondBuild); outs.writeLong(dbSeqs); outs.writeLong(dbSeqsUsed); outs.writeLong(dbLetters); outs.writeLong(flags); outs.writeLong(queryRecords); outs.writeInt(modeRank); outs.writeInt(gapOpen); outs.writeInt(gapExtend); outs.writeInt(reward); outs.writeInt(penalty); outs.writeInt(reserved1); outs.writeInt(reserved2); outs.writeInt(reserved3); outs.writeDouble(k); outs.writeDouble(lambda); outs.writeDouble(reserved4); outs.writeDouble(reserved5); for (byte a : scoreMatrix) { outs.write(a); } scoreMatrixName = StringUtils.toString(scoreMatrix); for (long a : blockSize) { outs.writeLong(a); } for (byte a : blockTypeRank) { outs.write(a); } } } private static final double LN_2 = 0.69314718055994530941723212145818; /** * compute the bit score from a raw score * * @return bitscore */ public float computeAlignmentBitScore(int rawScore) { return (float) ((lambda * rawScore - lnK) / LN_2); } /** * compute expected value * * @return expected */ public float computeAlignmentExpected(int queryLength, int rawScore) { double bitScore = (float) ((lambda * rawScore - lnK) / LN_2); return (float) (((double) getDbLetters() * queryLength * Math.pow(2, -bitScore))); } }
19,497
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAMatchRecord.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAMatchRecord.java
/* * DAAMatchRecord.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; import java.io.IOException; /** * match record * daniel Huson, 8.2105 */ public class DAAMatchRecord { private final DAAQueryRecord queryRecord; private final DAAParser daaParser; private final DAAHeader daaHeader; private int subjectId, totalSubjectLen, score, queryBegin, subjectBegin, frame, translatedQueryBegin, translatedQueryLen, subjectLen, len, identities, mismatches, gapOpenings; private int frameShiftAdjustmentForBlastXMode; // added to accommodate frame shift counts in DAA files generated from MAF files private byte[] subjectName; private final PackedTranscript transcript = new PackedTranscript(); /** * constructor * */ public DAAMatchRecord(DAAQueryRecord queryRecord) { this.queryRecord = queryRecord; this.daaParser = queryRecord.getDaaParser(); this.daaHeader = daaParser.getHeader(); } /** * parse from buffer * * @param refIns input stream to read reference sequences */ public void parseBuffer(ByteInputBuffer buffer, InputReaderLittleEndian refIns) throws IOException { subjectId = buffer.readIntLittleEndian(); int flag = buffer.read(); score = buffer.readPacked(flag & 3); queryBegin = buffer.readPacked((flag >>> 2) & 3); subjectBegin = buffer.readPacked((flag >>> 4) & 3); transcript.read(buffer); if (refIns != null) subjectName = daaHeader.getReference(subjectId, refIns); else subjectName = "unknown".getBytes(); totalSubjectLen = daaHeader.getRefLength(subjectId); switch (daaHeader.getAlignMode()) { case blastx -> { frame = (flag & (1 << 6)) == 0 ? queryBegin % 3 : 3 + (queryRecord.getSourceSequence().length - 1 - queryBegin) % 3; translatedQueryBegin = getQueryTranslatedBegin(queryBegin, frame, queryRecord.getSourceSequence().length, true); } case blastp -> { frame = 0; translatedQueryBegin = queryBegin; } case blastn -> { frame = (flag & (1 << 6)) == 0 ? 0 : 1; translatedQueryBegin = getQueryTranslatedBegin(queryBegin, frame, queryRecord.getSourceSequence().length); } } parseTranscript(transcript); } /** * parse the transcript. * Sets all these variables: * translatedQueryLen * frameShiftAdjustmentForBlastXMode * subjectLen * identities * mismatches * gapOpeningS * */ private void parseTranscript(PackedTranscript transcript) { translatedQueryLen = 0; frameShiftAdjustmentForBlastXMode = 0; subjectLen = 0; len = 0; identities = 0; mismatches = 0; gapOpenings = 0; int d = 0; for (CombinedOperation op : transcript.gather()) { int count = op.getCount(); len += count; switch (op.getEditOperation()) { case op_match -> { identities += count; translatedQueryLen += count; subjectLen += count; d = 0; } case op_substitution -> { byte c = daaParser.getAlignmentAlphabet()[op.getLetter()]; if (c == '/') { // reverse shift frameShiftAdjustmentForBlastXMode -= 4; // minus 1 for frame shift and 3 for translatedQueryLen increment } else if (c == '\\') { // forward shift frameShiftAdjustmentForBlastXMode -= 2; // plus 1 for frame shift and 3 for translatedQueryLen increment } translatedQueryLen += count; subjectLen += count; mismatches += count; d = 0; } case op_insertion -> { translatedQueryLen += count; ++gapOpenings; d = 0; } case op_deletion -> { subjectLen += count; if (d == 0) ++gapOpenings; d += count; } } } } private int getQueryTranslatedBegin(int query_begin, int frame, int dna_len) { // this needs testing if (frame == 0) return query_begin; else return dna_len - query_begin - 1; } private int getQueryTranslatedBegin(int query_begin, int frame, int dna_len, boolean query_translated) { if (!query_translated) return query_begin; int f = frame <= 2 ? frame + 1 : 2 - frame; if (f > 0) return (query_begin - (f - 1)) / 3; else return (dna_len + f - query_begin) / 3; } /** * gets the end of the query * * @return query end */ public int getQueryEnd() { switch (daaHeader.getAlignMode()) { case blastp: { return queryBegin + translatedQueryLen - 1; } case blastx: { final int len; if (frame > 2) { len = -(3 * translatedQueryLen + frameShiftAdjustmentForBlastXMode); } else len = 3 * translatedQueryLen + frameShiftAdjustmentForBlastXMode; //System.err.println("queryEnd: "+queryEnd); return queryBegin + (len > 0 ? -1 : 1) + len; } case blastn: { int len = translatedQueryLen * (frame > 0 ? -1 : 1); return queryBegin + (len > 0 ? -1 : 1) + len; } default: return 0; } } public DAAQueryRecord getQueryRecord() { return queryRecord; } public int getTotalSubjectLen() { return totalSubjectLen; } public int getScore() { return score; } public int getQueryBegin() { return queryBegin; } public int getSubjectBegin() { return subjectBegin; } public int getFrame() { return frame; } public int getTranslatedQueryBegin() { return translatedQueryBegin; } public int getTranslatedQueryLen() { return translatedQueryLen; } public int getSubjectLen() { return subjectLen; } public int getLen() { return len; } public int getIdentities() { return identities; } public int getMismatches() { return mismatches; } public int getGapOpenings() { return gapOpenings; } public byte[] getSubjectName() { return subjectName; } public int getSubjectId() { return subjectId; } public PackedTranscript getTranscript() { return transcript; } public byte[] getQuery() { return queryRecord.getContext()[frame]; } public int getFrameShiftAdjustmentForBlastXMode() { return frameShiftAdjustmentForBlastXMode; } }
8,006
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Translator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/Translator.java
/* * Translator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; /** * translates stuff * Daniel Huson, 8.2015 */ public class Translator { private static final byte[] reverseNucleotide = new byte[]{3, 2, 1, 0, 4}; private static final byte[][][] lookup = { {{11, 2, 11, 2, 23}, {16, 16, 16, 16, 16}, {1, 15, 1, 15, 23}, {9, 9, 12, 9, 23}, {23, 23, 23, 23, 23}, }, {{5, 8, 5, 8, 23}, {14, 14, 14, 14, 14}, {1, 1, 1, 1, 1}, {10, 10, 10, 10, 10}, {23, 23, 23, 23, 23}, }, {{6, 3, 6, 3, 23}, {0, 0, 0, 0, 0}, {7, 7, 7, 7, 7}, {19, 19, 19, 19, 19}, {23, 23, 23, 23, 23}, }, {{23, 18, 23, 18, 23}, {15, 15, 15, 15, 15}, {23, 4, 17, 4, 23}, {10, 13, 10, 13, 23}, {23, 23, 23, 23, 23}, }, {{23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, }}; private static final byte[][][] lookupReverse = { {{13, 10, 13, 10, 23}, {4, 17, 4, 23, 23}, {15, 15, 15, 15, 15}, {18, 23, 18, 23, 23}, {23, 23, 23, 23, 23}, }, {{19, 19, 19, 19, 19}, {7, 7, 7, 7, 7}, {0, 0, 0, 0, 0}, {3, 6, 3, 6, 23}, {23, 23, 23, 23, 23}, }, {{10, 10, 10, 10, 10}, {1, 1, 1, 1, 1}, {14, 14, 14, 14, 14}, {8, 5, 8, 5, 23}, {23, 23, 23, 23, 23}, }, {{9, 12, 9, 9, 23}, {15, 1, 15, 1, 23}, {16, 16, 16, 16, 16}, {2, 11, 2, 11, 23}, {23, 23, 23, 23, 23}, }, {{23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, {23, 23, 23, 23, 23}, }}; public static final byte[] DNA_ALPHABET = "ACGTN".getBytes(); public static final byte[] AMINO_ACID_ALPHABET = "ARNDCQEGHILKMFPSTWYVBJZX*_/\\".getBytes(); // last two must be: / and then \ public static final byte[] AMINO_ACID_ALPHABET_PRE_DIAMOND_132 = "ARNDCQEGHILKMFPSTWYVBJZX*/\\".getBytes(); // last two must be: / and then \ /** * get reversed-complemented DNA * * @return reverse component */ public static byte[] getReverseComplement(byte[] dna) { byte[] reverse = new byte[dna.length]; int j = dna.length - 1; for (byte a : dna) { reverse[j--] = reverseNucleotide[dna[a]]; } return reverse; } /** * get reversed-complemented DNA * * @return reverse component */ public static byte[] getReverseComplement(byte[] dna, int offset, int length) { byte[] reverse = new byte[length]; int j = offset + length - 1; for (int i = 0; i < length; i++) { reverse[i] = reverseNucleotide[dna[j--]]; } return reverse; } /** * get six frame translations * * @return six frame translations */ public static byte[][] getSixFrameTranslations(byte[] dnaSequence) { byte[][] proteins = new byte[6][]; int length = dnaSequence.length; int d = length / 3; proteins[0] = new byte[d]; proteins[3] = new byte[d]; d = (length - 1) / 3; proteins[1] = new byte[d]; proteins[4] = new byte[d]; d = (length - 2) / 3; proteins[2] = new byte[d]; proteins[5] = new byte[d]; int r = length - 2; int pos = 0; int i = 0; while (r > 2) { proteins[0][i] = getAminoAcid(dnaSequence, pos++); proteins[3][i] = getAminoAcidReverse(dnaSequence, --r); proteins[1][i] = getAminoAcid(dnaSequence, pos++); proteins[4][i] = getAminoAcidReverse(dnaSequence, --r); proteins[2][i] = getAminoAcid(dnaSequence, pos++); proteins[5][i] = getAminoAcidReverse(dnaSequence, --r); ++i; } if (r > 0) { proteins[0][i] = getAminoAcid(dnaSequence, pos++); proteins[3][i] = getAminoAcidReverse(dnaSequence, --r); } if (r > 0) { proteins[1][i] = getAminoAcid(dnaSequence, pos); proteins[4][i] = getAminoAcidReverse(dnaSequence, r); } return proteins; } static public byte getAminoAcid(byte[] dnaSequence, int pos) { return lookup[dnaSequence[pos]][dnaSequence[pos + 1]][dnaSequence[pos + 2]]; } private static byte getAminoAcidReverse(byte[] dnaSequence, int pos) { return lookupReverse[dnaSequence[pos + 2]][dnaSequence[pos + 1]][dnaSequence[pos]]; } /** * decode sequence to nucleotides or amino acids * * @return decoded sequence */ public static byte[] translate(byte[] sequence, byte[] alphabet, int offset, int length) { byte[] result = new byte[length]; for (int i = 0; i < length; i++) result[i] = alphabet[sequence[i + offset]]; return result; } /** * decode sequence to nucleotides or amino acids * * @return decoded sequence */ public static byte[] translate(byte[] sequence, byte[] alphabet) { return translate(sequence, alphabet, 0, sequence.length); } }
6,681
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ModifyClassificationsDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/ModifyClassificationsDAA.java
/* * ModifyClassificationsDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ListOfLongs; import java.io.IOException; import java.util.Map; /** * modifies a DAA file * Daniel Huson, 8.2015 */ public class ModifyClassificationsDAA { /** * update the classifications * */ public static void saveClassifications(DAAHeader header, String[] cNames, Map<Integer, ListOfLongs>[] fName2ClassId2Location, Map<Integer, Float>[] fName2ClassId2Weight) throws IOException { DAAModifier.removeMEGANClassificationData(header); for (int c = 0; c < cNames.length; c++) { final String cName = cNames[c]; final ByteOutputStream outputStreamClassKeys = new ByteOutputStream(1000000); final OutputWriterLittleEndian writerClassKeys = new OutputWriterLittleEndian(outputStreamClassKeys); final ByteOutputStream outputStreamClassReadLocationsDump = new ByteOutputStream(1000000); final OutputWriterLittleEndian writerClassReadLocationsDump = new OutputWriterLittleEndian(outputStreamClassReadLocationsDump); final Map<Integer, ListOfLongs> id2locations = fName2ClassId2Location[c]; writerClassKeys.writeNullTerminatedString(cName.getBytes()); writerClassKeys.writeInt(id2locations.size()); writerClassReadLocationsDump.writeNullTerminatedString(cName.getBytes()); for (int classId : id2locations.keySet()) { writerClassKeys.writeInt(classId); float weight = fName2ClassId2Weight[c].get(classId); writerClassKeys.writeInt((int) weight); final ListOfLongs list = id2locations.get(classId); writerClassKeys.writeInt(list.size()); writerClassKeys.writeLong(writerClassReadLocationsDump.getPosition()); // offset for (int i = 0; i < list.size(); i++) { writerClassReadLocationsDump.writeLong(list.get(i)); } } DAAModifier.appendBlocks(header, new BlockType[]{BlockType.megan_classification_key_block, BlockType.megan_classification_dump_block}, new byte[][]{outputStreamClassKeys.getBytes(), outputStreamClassReadLocationsDump.getBytes()}, new int[]{outputStreamClassKeys.size(), outputStreamClassReadLocationsDump.size()}); } } }
3,202
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ByteOutputStream.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/ByteOutputStream.java
/* * ByteOutputStream.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.Basic; import megan.io.IOutput; import java.io.OutputStream; /** * byte output stream */ public final class ByteOutputStream extends OutputStream implements IOutput { private byte[] buf; private int count; public ByteOutputStream() { this(1024); } public ByteOutputStream(int size) { this.count = 0; this.buf = new byte[size]; } public void write(int b) { this.ensureCapacity(1); this.buf[this.count] = (byte) b; ++this.count; } private void ensureCapacity(int space) { int newCount = space + this.count; if (newCount > this.buf.length) { if ((long) newCount > (long) Basic.MAX_ARRAY_SIZE) throw new RuntimeException("ByteOutputStream overflow"); var tmp = new byte[Math.max((int) Math.min((long) Basic.MAX_ARRAY_SIZE, ((long) this.buf.length) << 1L), newCount)]; System.arraycopy(this.buf, 0, tmp, 0, this.count); this.buf = tmp; } } public void write(byte[] b, int off, int len) { this.ensureCapacity(len); System.arraycopy(b, off, this.buf, this.count, len); this.count += len; } public void write(byte[] b) { this.write(b, 0, b.length); } public void reset() { this.count = 0; } public int size() { return this.count; } public String toString() { return new String(this.buf, 0, this.count); } public void close() { } public byte[] getBytes() { return this.buf; } public byte[] getExactLengthCopy() { final byte[] bytes = new byte[size()]; System.arraycopy(getBytes(), 0, bytes, 0, bytes.length); return bytes; } public int getCount() { return this.count; } @Override public long getPosition() { return count; } @Override public long length() { return count; } @Override public boolean supportsSeek() { return false; } @Override public void seek(long pos) { } }
2,958
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAQueryRecord.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAQueryRecord.java
/* * DAAQueryRecord.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; import jloda.util.ByteOutputBuffer; /** * DAA query record * Daniel Huson, 8.2015 */ public class DAAQueryRecord { private DAAParser daaParser; private byte[] queryName; private byte[] sourceSequence; private final byte[][] context = new byte[6][]; private int queryLength; // additional stuff: private long location; // location in file /** * constructor */ public DAAQueryRecord() { } /** * constructor * */ public DAAQueryRecord(DAAParser daaParser) { this.setDaaParser(daaParser); } /** * parses a buffer */ public void parseBuffer(ByteInputBuffer buffer) { queryLength = buffer.readIntLittleEndian(); queryName = buffer.readBytesNullTerminated(); int flags = buffer.readCharBigEndian(); boolean hasN = ((flags & 1) == 1); switch (daaParser.getHeader().getAlignMode()) { case blastp -> { // todo: untested byte[] packed = PackedSequence.readPackedSequence(buffer, queryLength, 5); sourceSequence = context[0] = PackedSequence.getUnpackedSequence(packed, queryLength, 5); } case blastx -> { byte[] packed = PackedSequence.readPackedSequence(buffer, queryLength, hasN ? 3 : 2); sourceSequence = PackedSequence.getUnpackedSequence(packed, queryLength, hasN ? 3 : 2); byte[][] sixFrameTranslation = Translator.getSixFrameTranslations(sourceSequence); System.arraycopy(sixFrameTranslation, 0, context, 0, sixFrameTranslation.length); } case blastn -> { // todo: untested byte[] packed = PackedSequence.readPackedSequence(buffer, queryLength, hasN ? 3 : 2); sourceSequence = PackedSequence.getUnpackedSequence(packed, queryLength, hasN ? 3 : 2); context[0] = sourceSequence; context[1] = Translator.getReverseComplement(sourceSequence); } default -> { } } } public DAAParser getDaaParser() { return daaParser; } private void setDaaParser(DAAParser daaParser) { this.daaParser = daaParser; } public byte[] getQueryName() { return queryName; } public byte[] getSourceSequence() { return sourceSequence; } public byte[][] getContext() { return context; } public byte[] getQueryFastA(byte[] alphabet) { ByteOutputBuffer buffer = new ByteOutputBuffer(); buffer.write((byte) '>'); buffer.write(queryName); buffer.write((byte) '\n'); buffer.write(Translator.translate(sourceSequence, alphabet, 0, sourceSequence.length)); buffer.write((byte) '\n'); return buffer.copyBytes(); } public long getLocation() { return location; } public void setLocation(long location) { this.location = location; } public int getQueryLength() { return queryLength; } }
3,900
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
InputReaderLittleEndian.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/InputReaderLittleEndian.java
/* * InputReaderLittleEndian.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; import megan.io.ByteByteInt; import megan.io.IInput; import megan.io.IInputReader; import java.io.Closeable; import java.io.IOException; /** * read data in little endian format as produced by C++ programs * Daniel Huson, 8.2015 */ public class InputReaderLittleEndian implements Closeable, IInputReader { private final IInput ins; private final byte[] bytes = new byte[8]; private final java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(8); /** * constructor * */ public InputReaderLittleEndian(IInput ins) { this.ins = ins; } /** * read byte * * @return byte */ public int read() throws IOException { return ins.read(); } /** * read bytes */ public int read(byte[] bytes, int offset, int len) throws IOException { if (ins.read(bytes, offset, len) < len) throw new IOException("buffer underflow"); return len; } /** * read bytes */ public int read_available(byte[] bytes, int offset, int len) throws IOException { return ins.read(bytes, offset, len); } /** * read bytes */ public byte[] readBytes(int count) throws IOException { final byte[] bytes = new byte[count]; read(bytes, 0, count); return bytes; } /** * read int little endian * * @return int */ public int readInt() throws IOException { if (ins.read(bytes, 0, 4) < 4) throw new IOException("buffer underflow at file pos: " + ins.getPosition()); return (((int) bytes[0] & 0xFF)) | (((int) bytes[1] & 0xFF) << 8) | (((int) bytes[2] & 0xFF) << 16) | (((int) bytes[3]) << 24); } /** * read long, little endian * * @return long */ public long readLong() throws IOException { if (ins.read(bytes, 0, 8) < 8) throw new IOException("buffer underflow"); return (((long) bytes[0] & 0xFF)) | (((long) bytes[1] & 0xFF) << 8) | (((long) bytes[2] & 0xFF) << 16) | (((long) bytes[3] & 0xFF) << 24) | (((long) bytes[4] & 0xFF) << 32) | (((long) bytes[5] & 0xFF) << 40) | (((long) bytes[6] & 0xFF) << 48) | (((long) bytes[7] & 0xFF) << 56); } /** * read float, little endian * * @return float */ public float readFloat() throws IOException { read(bytes, 0, 4); for (int i = 0; i < 4; i++) byteBuffer.put(i, bytes[4 - i - 1]); return byteBuffer.getFloat(0); } /** * read double, little endian * * @return double */ public double readDouble() throws IOException { read(bytes, 0, 8); for (int i = 0; i < 8; i++) byteBuffer.put(i, bytes[8 - i - 1]); return byteBuffer.getDouble(0); } /** * reads a null-terminated string * * @return length */ public int readNullTerminatedBytes(byte[] bytes) throws IOException { int i = 0; while (true) { byte letter = (byte) ins.read(); if (letter == 0) return i; else bytes[i++] = letter; } } /** * reads a null-terminated string * * @return length */ public String readNullTerminatedBytes() throws IOException { StringBuilder buf = new StringBuilder(); while (true) { byte letter = (byte) ins.read(); if (letter == -1) throw new IOException("readNullTerminatedBytes(): failed (EOF)"); if (letter == 0) break; else buf.append((char) letter); } return buf.toString(); } /** * skip a null-terminated string * */ public void skipNullTerminatedBytes() throws IOException { int letter = 1; while (letter != 0) { letter = ins.read(); if (letter == -1) throw new IOException("skipNullTerminatedBytes(): failed (EOF)"); } } /** * reads size-prefixed bytes * */ public void readSizePrefixedBytes(ByteInputBuffer buffer) throws IOException { buffer.setSize(readInt()); read(buffer.getBytes(), 0, buffer.size()); buffer.rewind(); } /** * skip n bytes * */ public void skip(long n) throws IOException { seek(getPosition() + n); } /** * get current position * * @return position */ public long getPosition() throws IOException { return ins.getPosition(); } /** * close * */ public void close() throws IOException { ins.close(); } @Override public int readChar() { return 0; } @Override public ByteByteInt readByteByteInt() { return null; } @Override public String readString() throws IOException { ByteInputBuffer buffer = new ByteInputBuffer(); readSizePrefixedBytes(buffer); return buffer.toString(); } @Override public int skipBytes(int bytes) throws IOException { return ins.skipBytes(bytes); } @Override public long length() throws IOException { return ins.length(); } @Override public boolean supportsSeek() throws IOException { return ins.supportsSeek(); } @Override public void seek(long pos) throws IOException { ins.seek(pos); } }
6,455
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PackedSequence.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/PackedSequence.java
/* * PackedSequence.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteInputBuffer; /** * Packed sequence * Daniel Huson, 8.2015 */ class PackedSequence { /** * read packed sequence from buffer * * @return packed sequence */ public static byte[] readPackedSequence(ByteInputBuffer buffer, int query_len, int bits) { int size = (query_len * bits + 7) / 8; //System.err.println("len=" + query_len); //System.err.println("b=" + bits); //System.err.println("size=" + size); return buffer.readBytes(size); } /** * get the unpacked sequence * * @return unpacked sequence */ public static byte[] getUnpackedSequence(byte[] packed, int query_len, int bits) { byte[] result = new byte[query_len]; long x = 0; int n = 0, l = 0; int mask = (1 << bits) - 1; for (byte b : packed) { x |= (long) (b & 0xFF) << n; n += 8; while (n >= bits && l < query_len) { result[l] = (byte) (x & mask); n -= bits; x >>>= bits; l++; } } return result; } /** * report sequence in human-readable unpacked format * * @return unpacked */ public static String toStringUnpacked(byte[] unpacked) { StringBuilder buf = new StringBuilder(); for (byte a : unpacked) buf.append(String.format("%d", a)); return buf.toString(); } /** * report sequence in human-readable unpacked format * * @return unpacked */ public static String toStringPacked(byte[] packed) { StringBuilder buf = new StringBuilder(); for (byte a : packed) buf.append(" ").append(a & 0xFF); return buf.toString(); } }
2,623
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAA2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAA2SAMIterator.java
/* * DAA2SAMIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.Pair; import megan.parsers.blast.ISAMIterator; import java.io.IOException; /** * iterates over all SAM records in a DAA file */ public class DAA2SAMIterator implements ISAMIterator { private final DAA2QuerySAMIterator daa2QuerySAMIterator; private Pair<byte[], byte[]> next; private boolean parseLongReads; /** * constructor * */ public DAA2SAMIterator(String fileName, int maxMatchesPerRead, boolean parseLongReads) throws IOException { this.daa2QuerySAMIterator = new DAA2QuerySAMIterator(fileName, maxMatchesPerRead, parseLongReads); } /** * gets the next matches * * @return number of matches */ @Override public int next() { next = daa2QuerySAMIterator.next(); return countNewLines(next.getSecond()); } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return daa2QuerySAMIterator.hasNext(); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return next.getSecond(); } @Override public byte[] getQueryText() { return next.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return next.getSecond().length; } @Override public long getMaximumProgress() { return daa2QuerySAMIterator.getMaximumProgress(); } @Override public long getProgress() { return daa2QuerySAMIterator.getProgress(); } @Override public void close() throws IOException { daa2QuerySAMIterator.close(); } private int countNewLines(byte[] bytes) { int count = 0; for (byte aByte : bytes) { if (aByte == '\n') count++; } return count; } @Override public void setParseLongReads(boolean longReads) { parseLongReads = longReads; } @Override public boolean isParseLongReads() { return parseLongReads; } }
3,033
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AccessClassificationsDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/AccessClassificationsDAA.java
/* * AccessClassificationsDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ListOfLongs; import megan.daa.connector.ClassificationBlockDAA; import megan.data.IClassificationBlock; import megan.io.FileRandomAccessReadOnlyAdapter; import java.io.IOException; import java.util.Collection; /** * access classifications in a DAA file * Daniel Huson, 8.2015 */ public class AccessClassificationsDAA { /** * load all query locations for a given classification and class ids * */ public static ListOfLongs loadQueryLocations(DAAHeader daaHeader, String classificationName, Collection<Integer> classIds) throws IOException { for (int i = 0; i < daaHeader.getBlockTypeRankArrayLength() - 1; i++) { final int j = i + 1; if (daaHeader.getBlockType(i) == BlockType.megan_classification_key_block && daaHeader.getBlockType(j) == BlockType.megan_classification_dump_block) { try (InputReaderLittleEndian insKey = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName()))) { final long keyBase = daaHeader.computeBlockStart(i); insKey.seek(keyBase); final String cName = insKey.readNullTerminatedBytes(); if (cName.equals(classificationName)) { final int numberOfClasses = insKey.readInt(); final ListOfLongs list = new ListOfLongs(100000); try (InputReaderLittleEndian insDump = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName()))) { final long dumpBase = daaHeader.computeBlockStart(j); insDump.seek(dumpBase); if (!insDump.readNullTerminatedBytes().equals(classificationName)) throw new IOException("Internal error: key-dump mismatch"); for (int c = 0; c < numberOfClasses; c++) { int classId = insKey.readInt(); insKey.skip(4); // weight int size = insKey.readInt(); final long offset = insKey.readLong(); if (classIds.contains(classId)) { insDump.seek(dumpBase + offset); for (int n = 0; n < size; n++) { list.add(insDump.readLong()); } } } } return list; } } } } return null; } /** * load a named classification block * * @return classification */ public static IClassificationBlock loadClassification(DAAHeader daaHeader, String classificationName) throws IOException { for (int i = 0; i < daaHeader.getBlockTypeRankArrayLength() - 1; i++) { if (daaHeader.getBlockType(i) == BlockType.megan_classification_key_block) { long keyBase = daaHeader.computeBlockStart(i); try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName()))) { ins.seek(keyBase); String cName = ins.readNullTerminatedBytes(); if (cName.equalsIgnoreCase(classificationName)) { final ClassificationBlockDAA classificationBlock = new ClassificationBlockDAA(classificationName); int numberOfClasses = ins.readInt(); for (int c = 0; c < numberOfClasses; c++) { int classId = ins.readInt(); classificationBlock.setWeightedSum(classId, ins.readInt()); classificationBlock.setSum(classId, ins.readInt()); ins.skipBytes(8); // skip offset } return classificationBlock; } } } } return null; } }
5,063
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CombinedOperation.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/CombinedOperation.java
/* * CombinedOperation.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; /** * combined edit operations * Daniel Huson, 8.2015 */ public class CombinedOperation { private PackedTranscript.EditOperation editOperation; private int count; private byte letter; public CombinedOperation() { } public CombinedOperation(PackedTranscript.EditOperation editOperation, int count, Byte letter) { this.editOperation = editOperation; this.count = count; this.letter = (letter == null ? 0 : letter); } public PackedTranscript.EditOperation getEditOperation() { return editOperation; } public int getOpCode() { return editOperation.ordinal(); } public void setEditOperation(PackedTranscript.EditOperation editOperation) { this.editOperation = editOperation; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void incrementCount(int add) { this.count += add; } public byte getLetter() { return letter; } public void setLetter(byte letter) { this.letter = letter; } }
1,963
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlockType.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/BlockType.java
/* * BlockType.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; /** * Block type * Daniel Huson, 8.2015 */ public enum BlockType { empty, alignments, ref_names, ref_lengths, megan_ref_annotations, megan_classification_key_block, megan_classification_dump_block, megan_aux_data, megan_mate_pair; public static byte rank(BlockType type) { for (byte i = 0; i < values().length; i++) if (values()[i] == type) return i; return -1; } public static BlockType value(byte rank) { if (rank >= 0 && rank < values().length) return values()[rank]; else return empty; } }
1,432
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAA2QuerySAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAA2QuerySAMIterator.java
/* * DAA2QuerySAMIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.Basic; import jloda.util.ICloseableIterator; import jloda.util.Pair; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * iterator over all queries and sam records as text pairs */ public class DAA2QuerySAMIterator implements ICloseableIterator<Pair<byte[], byte[]>> { private final DAAParser daaParser; private final BlockingQueue<Pair<byte[], byte[]>> queue; private final ExecutorService executorService; private long count = 0; private Pair<byte[], byte[]> next = null; /** * constructor * */ public DAA2QuerySAMIterator(String daaFile, final int maxMatchesPerRead, final boolean parseLongReads) throws IOException { this.daaParser = new DAAParser(daaFile); daaParser.getHeader().loadReferences(true); queue = new ArrayBlockingQueue<>(1000); // start a thread that loads queue: executorService = Executors.newSingleThreadExecutor(); executorService.submit(() -> { try { daaParser.getAllAlignmentsSAMFormat(maxMatchesPerRead, queue, parseLongReads); } catch (IOException e) { Basic.caught(e); } }); } @Override public void close() { executorService.shutdownNow(); } @Override public long getMaximumProgress() { return daaParser.getHeader().getQueryRecords(); } @Override public long getProgress() { return count; } @Override public boolean hasNext() { synchronized (DAAParser.SENTINEL_SAM_ALIGNMENTS) { if (next == null) { try { next = queue.take(); } catch (InterruptedException e) { Basic.caught(e); } } return next != DAAParser.SENTINEL_SAM_ALIGNMENTS; } } @Override public Pair<byte[], byte[]> next() { synchronized (DAAParser.SENTINEL_SAM_ALIGNMENTS) { if (next == null || next == DAAParser.SENTINEL_SAM_ALIGNMENTS) return null; count++; Pair<byte[], byte[]> result; result = next; try { next = queue.take(); } catch (InterruptedException e) { Basic.caught(e); } return result; } } @Override public void remove() { } }
3,419
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAQueryMatchesIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/DAAQueryMatchesIterator.java
/* * DAAQueryMatchesIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.Basic; import jloda.util.ICloseableIterator; import jloda.util.Pair; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * iterator over queries and their matches * Daniel Huson, 8.2105 */ public class DAAQueryMatchesIterator implements ICloseableIterator<Pair<DAAQueryRecord, DAAMatchRecord[]>> { private final DAAParser daaParser; private final BlockingQueue<Pair<DAAQueryRecord, DAAMatchRecord[]>> queue; private final ExecutorService executorService; private long count = 0; private Pair<DAAQueryRecord, DAAMatchRecord[]> next = null; /** * constructor * */ public DAAQueryMatchesIterator(String daaFile, final boolean wantMatches, final int maxMatchesPerRead, final boolean longReads) throws IOException { this.daaParser = new DAAParser(daaFile); daaParser.getHeader().loadReferences(true); queue = new ArrayBlockingQueue<>(1000); // start a thread that loads queue: executorService = Executors.newSingleThreadExecutor(); executorService.submit(() -> { try { daaParser.getAllQueriesAndMatches(wantMatches, maxMatchesPerRead, queue, longReads); } catch (IOException e) { Basic.caught(e); } }); } @Override public void close() { executorService.shutdownNow(); } @Override public long getMaximumProgress() { return daaParser.getHeader().getQueryRecords(); } @Override public long getProgress() { return count; } @Override public boolean hasNext() { synchronized (DAAParser.SENTINEL_QUERY_MATCH_BLOCKS) { if (next == null) { try { next = queue.take(); } catch (InterruptedException e) { Basic.caught(e); } } return next != DAAParser.SENTINEL_QUERY_MATCH_BLOCKS; } } @Override public Pair<DAAQueryRecord, DAAMatchRecord[]> next() { synchronized (DAAParser.SENTINEL_QUERY_MATCH_BLOCKS) { if (next == null || next == DAAParser.SENTINEL_QUERY_MATCH_BLOCKS) return null; count++; Pair<DAAQueryRecord, DAAMatchRecord[]> result; result = next; try { next = queue.take(); } catch (InterruptedException e) { Basic.caught(e); } return result; } } @Override public void remove() { } }
3,571
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAMUtilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/io/SAMUtilities.java
/* * SAMUtilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.io; import jloda.util.ByteOutputBuffer; /** * generates SAM lines * Daniel Huson, 8.2015 */ public class SAMUtilities { private static final String FILE_HEADER_BLASTN_TEMPLATE = "@HD\tVN:1.5\tSO:unsorted\tGO:query\n@PG\tID:1\tPN:MEGAN\tCL:%s\tDS:BlastN\n@RG\tID:1\tPL:unknown\tSM:unknown\n@CO\tBlastN-like alignments\n" + "@CO\tReporting AS: bitScore, ZR: rawScore, ZE: expected, ZI: percent identity, ZL: reference length\n"; private static final String FILE_HEADER_BLASTP_TEMPLATE = "@HD\tVN:1.5\tSO:unsorted\tGO:query\n@PG\tID:1\tPN:MEGAN\tCL:%s\tDS:BlastP\n@RG\tID:1\tPL:unknown\tSM:unknown\n@CO\tBlastP-like alignments\n" + "@CO\tReporting AS: bitScore, ZR: rawScore, ZE: expected, ZI: percent identity, ZL: reference length\n"; private static final String FILE_HEADER_BLASTX_TEMPLATE = "@HD\tVN:1.5\tSO:unsorted\tGO:query\n@PG\tID:1\tPN:MEGAN\tCL:%s\tDS:BlastX\n@RG\tID:1\tPL:unknown\tSM:unknown\n@CO\tBlastX-like alignments\n" + "@CO\tReporting AS: bitScore, ZR: rawScore, ZE: expected, ZI: percent identity, ZL: reference length, ZF: frame, ZS: query start DNA coordinate\n"; private static final int[] mapDaaOpCode2CigarOpCode = {0, 1, 2, 0}; // op_match -> M, op_insertion-> I, op_deletion-> D, op_substitution -> M private static final char[] daaOpCode2CigarLetter = {'M', 'I', 'D'}; private static final CombinedOperation insertOperation = new CombinedOperation(PackedTranscript.EditOperation.op_insertion, 1, null); /** * create a sam line * */ public static void createSAM(DAAParser daaParser, DAAMatchRecord matchRecord, ByteOutputBuffer buffer, byte[] queryAlphabet) { buffer.write(matchRecord.getQueryRecord().getQueryName()); buffer.writeString("\t0\t"); buffer.write(matchRecord.getSubjectName()); buffer.writeString(String.format("\t%d\t255\t", matchRecord.getSubjectBegin() + 1)); final byte[][] cigarAndAlignedQueryAndMD; if (matchRecord.getFrameShiftAdjustmentForBlastXMode() != 0) { final int queryBegin = matchRecord.getQueryBegin(); final int queryEnd = matchRecord.getQueryEnd(); // query end position, in the case of BlastX, not taking frame shifts into account int start; byte[] querySequence; if (queryBegin < queryEnd) { // positive frame querySequence = matchRecord.getQueryRecord().getSourceSequence(); start = queryBegin; } else { // negative frame start = 0; int length = queryBegin - queryEnd + 1; querySequence = Translator.getReverseComplement(matchRecord.getQueryRecord().getSourceSequence(), queryEnd, length); } cigarAndAlignedQueryAndMD = computeCigarAndAlignedQueryAndMD(querySequence, start, queryAlphabet, matchRecord.getTranscript()); } else cigarAndAlignedQueryAndMD = null; if (cigarAndAlignedQueryAndMD == null) writeCigar(matchRecord, buffer); else buffer.write(cigarAndAlignedQueryAndMD[0]); buffer.writeString("\t*\t0\t0\t"); if (cigarAndAlignedQueryAndMD == null) { buffer.write(Translator.translate(matchRecord.getQuery(), queryAlphabet, matchRecord.getTranslatedQueryBegin(), matchRecord.getTranslatedQueryLen())); } else { buffer.write(cigarAndAlignedQueryAndMD[1]); } buffer.writeString("\t*\t"); float bitScore = daaParser.getHeader().computeAlignmentBitScore(matchRecord.getScore()); float evalue = daaParser.getHeader().computeAlignmentExpected(matchRecord.getQuery().length, matchRecord.getScore()); int percentIdentity = Utilities.computePercentIdentity(matchRecord); int blastFrame = computeBlastFrame(matchRecord.getFrame()); buffer.writeString( String.format("AS:i:%d\tNM:i:%d\tZL:i:%d\tZR:i:%d\tZE:f:%.1e\tZI:i:%d\tZF:i:%d\tZS:i:%d\tMD:Z:", (int) bitScore, matchRecord.getLen() - matchRecord.getIdentities(), matchRecord.getTotalSubjectLen(), matchRecord.getScore(), evalue, percentIdentity, blastFrame, matchRecord.getQueryBegin() + (matchRecord.getQueryBegin() < matchRecord.getQueryEnd() ? 1 : 1))); if (cigarAndAlignedQueryAndMD == null) writeMD(matchRecord, buffer, queryAlphabet); else buffer.write(cigarAndAlignedQueryAndMD[2]); buffer.write((byte) '\n'); } /** * compute the aligned query string, cigar and MD string * * @return alignment, cigar and MD string */ private static byte[][] computeCigarAndAlignedQueryAndMD(byte[] queryDNA, int start, byte[] queryAlphabet, PackedTranscript editTranscript) { final ByteOutputBuffer alignedQueryBuf = new ByteOutputBuffer(); //final ByteOutputBuffer alignedReferenceBuf=new ByteOutputBuffer(); final ByteOutputBuffer cigarBuf = new ByteOutputBuffer(); final ByteOutputBuffer mdBuf = new ByteOutputBuffer(); // used in computation of cigar: int previousCount = 0, previousOp = 0; // used in computation of MD string: int matches = 0, del = 0; // current query position int queryPosition = start; for (CombinedOperation editOp : editTranscript.gather()) { final CombinedOperation editOpCorrected; // compute sequence: switch (editOp.getEditOperation()) { case op_match -> { for (int i = 0; i < editOp.getCount(); i++) { byte aa = queryAlphabet[Translator.getAminoAcid(queryDNA, queryPosition)]; alignedQueryBuf.write(aa); //alignedReferenceBuf.write(aa); queryPosition += 3; } editOpCorrected = editOp; } case op_insertion -> { for (int i = 0; i < editOp.getCount(); i++) { byte aa = queryAlphabet[Translator.getAminoAcid(queryDNA, queryPosition)]; alignedQueryBuf.write(aa); //alignedReferenceBuf.write((byte)'-'); queryPosition += 3; } editOpCorrected = editOp; } case op_deletion -> { byte c = queryAlphabet[editOp.getLetter()]; //alignedQueryBuf.write((byte)'-'); //alignedReferenceBuf.write(c); editOpCorrected = editOp; } // Key idea here: Although a frame shift in the query is really an insertion in the query, // in a DAA file it is represented as a substitution by a / or \ in the reference, due to limitations due to the bit packed transcript encoding case op_substitution -> { byte c = queryAlphabet[editOp.getLetter()]; if (c == '/') { // reverse shift alignedQueryBuf.write(c); //alignedReferenceBuf.write((byte)'-'); queryPosition -= 1; editOpCorrected = insertOperation; } else if (c == '\\') { // forward shift alignedQueryBuf.write(c); //alignedReferenceBuf.write((byte)'-'); queryPosition += 1; editOpCorrected = insertOperation; } else { byte aa = queryAlphabet[Translator.getAminoAcid(queryDNA, queryPosition)]; alignedQueryBuf.write(aa); //alignedReferenceBuf.write(c); queryPosition += 3; editOpCorrected = editOp; } } default -> throw new RuntimeException("this should't happen"); } // compute cigar: if (mapDaaOpCode2CigarOpCode[editOpCorrected.getOpCode()] == previousOp) previousCount += editOpCorrected.getCount(); else { if (previousCount > 0) cigarBuf.writeString(String.format("%d", previousCount)); cigarBuf.write((byte) daaOpCode2CigarLetter[previousOp]); previousCount = editOpCorrected.getCount(); previousOp = mapDaaOpCode2CigarOpCode[editOpCorrected.getOpCode()]; } // compute md: switch (editOpCorrected.getEditOperation()) { case op_match: del = 0; matches += editOpCorrected.getCount(); break; case op_insertion: break; case op_substitution: if (matches > 0) { mdBuf.writeString(String.format("%d", matches)); matches = 0; } else if (del > 0) { mdBuf.write((byte) '0'); del = 0; } mdBuf.write(queryAlphabet[editOpCorrected.getLetter()]); break; case op_deletion: if (matches > 0) { mdBuf.writeString(String.format("%d", matches)); matches = 0; } if (del == 0) mdBuf.write((byte) '^'); mdBuf.write(queryAlphabet[editOpCorrected.getLetter()]); ++del; } } if (previousCount > 0) { // finish cigar cigarBuf.writeString(String.format("%d", previousCount)); cigarBuf.write((byte) daaOpCode2CigarLetter[previousOp]); } if (matches > 0) // finish md mdBuf.writeString(String.format("%d", matches)); return new byte[][]{cigarBuf.copyBytes(), alignedQueryBuf.copyBytes(), mdBuf.copyBytes()}; } /** * write the cigar string * */ private static void writeCigar(DAAMatchRecord match, ByteOutputBuffer buffer) { int previousCount = 0, previousOp = 0; for (final CombinedOperation cop : match.getTranscript().gather()) { int opCode = cop.getOpCode(); if (mapDaaOpCode2CigarOpCode[opCode] == previousOp) previousCount += cop.getCount(); else { if (previousCount > 0) buffer.writeString(String.format("%d", previousCount)); buffer.write((byte) daaOpCode2CigarLetter[previousOp]); previousCount = cop.getCount(); previousOp = mapDaaOpCode2CigarOpCode[opCode]; } } if (previousCount > 0) { buffer.writeString(String.format("%d", previousCount)); buffer.write((byte) daaOpCode2CigarLetter[previousOp]); } } /** * write the MD string * */ private static void writeMD(DAAMatchRecord match, ByteOutputBuffer buffer, byte[] queryAlphabet) { { int matches = 0, del = 0; for (CombinedOperation editOp : match.getTranscript().gather()) { switch (editOp.getEditOperation()) { case op_match: del = 0; matches += editOp.getCount(); break; case op_insertion: break; case op_substitution: if (matches > 0) { buffer.writeString(String.format("%d", matches)); matches = 0; } else if (del > 0) { buffer.write((byte) '0'); del = 0; } buffer.write(queryAlphabet[editOp.getLetter()]); break; case op_deletion: if (matches > 0) { buffer.writeString(String.format("%d", matches)); matches = 0; } if (del == 0) buffer.write((byte) '^'); buffer.write(queryAlphabet[editOp.getLetter()]); ++del; } } if (matches > 0) buffer.writeString(String.format("%d", matches)); } } /** * compute the BLAST frame * * @param frame (in range 0-5) * @return BLAST frame (in range -2 to 2) */ private static int computeBlastFrame(int frame) { return frame <= 2 ? frame + 1 : 2 - frame; } }
13,733
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockGetterDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/connector/ReadBlockGetterDAA.java
/* * ReadBlockGetterDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.connector; import jloda.util.Basic; import jloda.util.ByteInputBuffer; import jloda.util.Pair; import megan.daa.io.*; import megan.data.IReadBlock; import megan.data.IReadBlockGetter; import megan.io.FileInputStreamAdapter; import megan.io.FileRandomAccessReadOnlyAdapter; import java.io.IOException; /** * Read block getter * Daniel Huson, 8.2015 */ public class ReadBlockGetterDAA implements IReadBlockGetter { private final DAAParser daaParser; private final boolean wantReadSequences; private final boolean wantMatches; private final float minScore; private final float maxExpected; private final boolean streamOnly; private final ReadBlockDAA reuseableReadBlock; private final long start; private final long end; private final InputReaderLittleEndian reader; private final InputReaderLittleEndian refReader; private final ByteInputBuffer inputBuffer = new ByteInputBuffer(); private final DAAMatchRecord[] daaMatchRecords = new DAAMatchRecord[50000]; // when parsing long reads the number can be quite big private final boolean longReads; /** * constructor * */ public ReadBlockGetterDAA(DAAHeader daaHeader, boolean wantReadSequences, boolean wantMatches, float minScore, float maxExpected, boolean streamOnly, boolean reuseReadBlockObject, boolean longReads) throws IOException { this.daaParser = new DAAParser(daaHeader); if (daaHeader.getNumberOfReferences() == 0) daaHeader.loadReferences(!streamOnly || !wantMatches); if (daaHeader.getNumberOfRefAnnotations() == 0) daaHeader.loadRefAnnotations(); this.wantReadSequences = wantReadSequences; this.wantMatches = wantMatches; this.minScore = minScore; this.maxExpected = maxExpected; this.streamOnly = streamOnly; this.start = daaHeader.computeBlockStart(daaHeader.getAlignmentsBlockIndex()); this.end = start + daaHeader.getBlockSize(daaHeader.getAlignmentsBlockIndex()); reader = new InputReaderLittleEndian(streamOnly ? new FileInputStreamAdapter(daaHeader.getFileName()) : new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName())); refReader = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName())); // todo: 'stream only' doesn't work when need to grab reference headers //reader = new InputReaderLittleEndian(new FileRandomAccessReadOnlyAdapter(daaHeader.getFileName())); if (streamOnly) reader.seek(start); if (reuseReadBlockObject) reuseableReadBlock = new ReadBlockDAA(); else reuseableReadBlock = null; this.longReads = longReads; } /** * gets the read block associated with the given uid * * @param uid or -1, if in streaming mode * @return read block or null */ @Override public IReadBlock getReadBlock(long uid) throws IOException { if (uid == -1) { if (!streamOnly) throw new IOException("getReadBlock(uid=" + uid + ") failed: not streamOnly"); } else { if (streamOnly) { throw new IOException("getReadBlock(uid=" + uid + ") failed: streamOnly"); } reader.seek(uid); } if (reader.getPosition() < end) { if (uid >= 0) { } final ReadBlockDAA readBlock = (reuseableReadBlock == null ? new ReadBlockDAA() : reuseableReadBlock); final Pair<DAAQueryRecord, DAAMatchRecord[]> pair = daaParser.readQueryAndMatches(reader, refReader, wantMatches, daaMatchRecords.length, inputBuffer, daaMatchRecords, longReads); readBlock.setFromQueryAndMatchRecords(pair.getFirst(), pair.getSecond(), wantReadSequences, wantMatches, minScore, maxExpected); return readBlock; } return null; } /** * closes the accessor * */ @Override public void close() { try { reader.close(); refReader.close(); } catch (IOException e) { Basic.caught(e); } } public long getStart() { return start; } public long getEnd() { return end; } public long getPosition() { try { return reader.getPosition(); } catch (IOException e) { return -1; } } public DAAHeader getDAAHeader() { return daaParser.getHeader(); } /** * get total number of reads * * @return total number of reads */ @Override public long getCount() { return daaParser.getHeader().getQueryRecords(); } }
5,554
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/connector/ReadBlockDAA.java
/* * ReadBlockDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.connector; import jloda.util.StringUtils; import megan.daa.io.DAAMatchRecord; import megan.daa.io.DAAQueryRecord; import megan.daa.io.Translator; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.util.ReadMagnitudeParser; /** * ReadBlock for DAA * Daniel Huson, 8.2015 */ public class ReadBlockDAA implements IReadBlock { private boolean wantReadSequences; // to mimic other implementations of read sequences, we only support get read sequence, only if originally requested private DAAQueryRecord queryRecord; private int numberOfMatches; private IMatchBlock[] matchBlocks; private int readWeight = 1; /** * Constructor */ public ReadBlockDAA() { } /** * get the unique identifier for this read (unique within a dataset). * In an RMA file, this is always the file position for the read * * @return uid */ public long getUId() { return queryRecord.getLocation(); } public void setUId(long uid) { queryRecord.setLocation(uid); } /** * get the name of the read (first word in header) * * @return name */ public String getReadName() { return StringUtils.toString(queryRecord.getQueryName()); } /** * get the fastA header for the read * * @return fastA header */ public String getReadHeader() { return StringUtils.toString(queryRecord.getQueryName()); } public void setReadHeader(String readHeader) { System.err.println("Not implemented"); } /** * get the sequence of the read * * @return sequence */ public String getReadSequence() { return (wantReadSequences ? StringUtils.toString(Translator.translate(queryRecord.getSourceSequence(), queryRecord.getDaaParser().getSourceAlphabet())) : null); } public void setReadSequence(String readSequence) { System.err.println("Not implemented"); } /** * gets the uid of the mated read * * @return uid of mate or 0 */ public long getMateUId() { return 0; } public void setMateUId(long mateUid) { System.err.println("Not implemented"); } /** * get the mate type * Possible values: FIRST_MATE, SECOND_MATE * * @return mate type */ public byte getMateType() { return 0; } public void setMateType(byte mateType) { System.err.println("Not implemented"); } /** * set the read length * */ public void setReadLength(int readLength) { System.err.println("Not implemented"); } public int getReadLength() { return queryRecord.getSourceSequence().length; } /** * get the readComplexity * */ public void setComplexity(float readComplexity) { } public float getComplexity() { return 0; } /** * set the weight of a read * */ public void setReadWeight(int readWeight) { this.readWeight = readWeight; } /** * get the weight of a read * * @return weight */ public int getReadWeight() { return readWeight; } /** * get the original number of matches * * @return number of matches */ public int getNumberOfMatches() { return numberOfMatches; } public void setNumberOfMatches(int numberOfMatches) { this.numberOfMatches = numberOfMatches; } /** * gets the current number of matches available * */ public int getNumberOfAvailableMatchBlocks() { return matchBlocks != null ? matchBlocks.length : 0; } /** * get the matches. May be less than the original number of matches (when filtering matches) * * @return matches */ public IMatchBlock[] getMatchBlocks() { return matchBlocks; } public void setMatchBlocks(IMatchBlock[] matchBlocks) { this.matchBlocks = matchBlocks; } /** * get the i-th match block * * @return match block */ public IMatchBlock getMatchBlock(int i) { return matchBlocks[i]; } /** * set the read block and its match blocks from records * */ public void setFromQueryAndMatchRecords(DAAQueryRecord queryRecord, DAAMatchRecord[] matchRecords, boolean wantReadSequences, boolean wantMatches, float minScore, float maxExpected) { this.wantReadSequences = wantReadSequences; this.queryRecord = queryRecord; numberOfMatches = matchRecords.length; if (wantMatches) { matchBlocks = new IMatchBlock[matchRecords.length]; int numberGoodMatches = 0; for (DAAMatchRecord matchRecord : matchRecords) { MatchBlockDAA matchBlockDAA = new MatchBlockDAA(queryRecord.getDaaParser(), matchRecord); if (matchBlockDAA.getBitScore() >= minScore && matchBlockDAA.getExpected() <= maxExpected) { matchBlocks[numberGoodMatches++] = matchBlockDAA; } } if (numberGoodMatches < numberOfMatches) { final IMatchBlock[] tmp = new MatchBlockDAA[numberGoodMatches]; System.arraycopy(matchBlocks, 0, tmp, 0, numberGoodMatches); matchBlocks = tmp; } } else { matchBlocks = new IMatchBlock[0]; numberOfMatches = 0; } setReadWeight(ReadMagnitudeParser.parseMagnitude(getReadHeader())); } }
6,360
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/connector/MatchBlockDAA.java
/* * MatchBlockDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.connector; import jloda.util.Basic; import jloda.util.ByteOutputBuffer; import jloda.util.StringUtils; import megan.classification.IdParser; import megan.daa.io.*; import megan.data.IMatchBlock; import megan.parsers.sam.SAMMatch; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; /** * matchblock for DAA * Daniel Huson, 6.2015 */ public class MatchBlockDAA implements IMatchBlock { private static long countUids = 0; private static final Object sync = new Object(); private final DAAParser daaParser; private DAAMatchRecord matchRecord; private long uid; private final Map<String, Integer> fName2Id = new HashMap<>(); private int taxonId; /** * constructor */ public MatchBlockDAA(DAAParser daaParser, DAAMatchRecord matchRecord) { this.daaParser = daaParser; this.matchRecord = matchRecord; final DAAHeader header = daaParser.getHeader(); for (int f = 0; f < header.getNumberOfRefAnnotations(); f++) { fName2Id.put(header.getRefAnnotationName(f), header.getRefAnnotation(f, matchRecord.getSubjectId())); } taxonId = header.getRefAnnotation(header.getRefAnnotationIndexForTaxonomy(), matchRecord.getSubjectId()); synchronized (sync) { uid = countUids++; } } /** * erase the block (for reuse) */ public void clear() { uid = 0; matchRecord = null; fName2Id.clear(); taxonId = 0; } /** * get the unique identifier for this match (unique within a dataset). * In an RMA file, this is always the file position for the match * * @return uid */ public long getUId() { return uid; } public void setUId(long uid) { this.uid = uid; } /** * get the taxon id of the match * */ public int getTaxonId() { return taxonId; } public void setTaxonId(int taxonId) { this.taxonId = taxonId; } public int getId(String cName) { final Integer id = fName2Id.get(cName); return id != null ? id : 0; } /** * gets all defined ids * * @return ids */ public int[] getIds(String[] cNames) { int[] ids = new int[cNames.length]; for (int i = 0; i < cNames.length; i++) { ids[i] = getId(cNames[i]); } return ids; } public void setId(String cName, Integer id) { fName2Id.put(cName, id); } /** * get the score of the match * */ public float getBitScore() { return Math.round(daaParser.getHeader().computeAlignmentBitScore(matchRecord.getScore())); // we round because otherwise there is a small difference between RMA and DAA files } public void setBitScore(float bitScore) { System.err.println("Not implemented"); } /** * get the percent identity * */ public float getPercentIdentity() { return Utilities.computePercentIdentity(matchRecord); } public void setPercentIdentity(float percentIdentity) { System.err.println("Not implemented"); } /** * get the refseq id * */ public String getRefSeqId() { return getText() != null ? parseRefSeqId(getText()) : null; } public void setRefSeqId(String refSeqId) { System.err.println("Not implemented"); } /** * gets the E-value * */ public void setExpected(float expected) { System.err.println("Not implemented"); } public float getExpected() { return daaParser.getHeader().computeAlignmentExpected(matchRecord.getQuery().length, matchRecord.getScore()); } /** * gets the match length * */ public void setLength(int length) { System.err.println("Not implemented"); } public int getLength() { return matchRecord.getLen(); } /** * get the ignore status */ @Deprecated public boolean isIgnore() { return false; } /** * set the ignore status */ @Deprecated public void setIgnore(boolean ignore) { System.err.println("Not implemented"); } /** * get the text * */ public String getText() { try { // todo: do this directly and more efficently ByteOutputBuffer buffer = new ByteOutputBuffer(); SAMUtilities.createSAM(daaParser, matchRecord, buffer, daaParser.getAlignmentAlphabet()); SAMMatch match = new SAMMatch(daaParser.getBlastMode()); match.parse(buffer.getBytes(), buffer.size()); return match.getBlastAlignmentText(); } catch (Exception e) { Basic.caught(e); return ""; } } public String getTextBlastTab() { var bitScore = daaParser.getHeader().computeAlignmentBitScore(matchRecord.getScore()); var evalue = daaParser.getHeader().computeAlignmentExpected(matchRecord.getQuery().length, matchRecord.getScore()); var percentIdentity = Utilities.computePercentIdentity(matchRecord); // query id, ref id, percent identity, alignment length, number of mismatches, number of gap openings, query start, query end, subject start, subject end, Expect value, HSP bit score. // 0 1 2 3 4 5 6 7 8 9 10 11 return "%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.1f\t%.1f%n".formatted(StringUtils.toString(matchRecord.getQueryRecord().getQueryName()),StringUtils.toString(matchRecord.getSubjectName()),percentIdentity, matchRecord.getLen(),matchRecord.getMismatches(), matchRecord.getGapOpenings(),matchRecord.getQueryBegin(),matchRecord.getQueryEnd(),matchRecord.getSubjectBegin(),matchRecord.getSubjectBegin()+matchRecord.getSubjectLen(), evalue,bitScore); } /** * this is experimental code that is used to verify that DAA with frame-shifts is handled ok * * @return two alignment tracks */ private String[] computeAlignmentBlastX(DAAMatchRecord matchRecord, byte[] queryAlphabet) { final byte[] totalQuerySequence = matchRecord.getQueryRecord().getSourceSequence(); final int totalQueryLength = matchRecord.getQueryRecord().getQueryLength(); final byte[] querySeq = matchRecord.getFrame() > 0 ? totalQuerySequence : Translator.getReverseComplement(totalQuerySequence); final int start = matchRecord.getFrame() > 0 ? matchRecord.getQueryBegin() : totalQueryLength - matchRecord.getQueryBegin() - 1; final StringBuilder[] bufs = {new StringBuilder(), new StringBuilder()}; int q = start; for (CombinedOperation editOp : matchRecord.getTranscript().gather()) { switch (editOp.getEditOperation()) { case op_match -> // handling match { for (int i = 0; i < editOp.getCount(); i++) { char aa = (char) daaParser.getAlignmentAlphabet()[Translator.getAminoAcid(querySeq, q)]; bufs[0].append(aa); bufs[1].append(aa); q += 3; } } case op_insertion -> // handling insertion { for (int i = 0; i < editOp.getCount(); i++) { char aa = (char) daaParser.getAlignmentAlphabet()[Translator.getAminoAcid(querySeq, q)]; bufs[0].append(aa); bufs[1].append('-'); q += 3; } } case op_deletion -> // handling deletion { char c = (char) queryAlphabet[editOp.getLetter()]; bufs[0].append('-'); bufs[1].append(c); } case op_substitution -> // handling substitution { char c = (char) queryAlphabet[editOp.getLetter()]; if (c == '/') { bufs[0].append("/"); bufs[1].append("-"); q -= 1; } else if (c == '\\') { bufs[0].append("\\"); bufs[1].append("-"); q += 1; } else { char aa = (char) daaParser.getAlignmentAlphabet()[Translator.getAminoAcid(querySeq, q)]; bufs[0].append(aa); bufs[1].append(c); q += 3; } } } } return new String[]{bufs[0].toString(), bufs[1].toString()}; } @Override public String getTextFirstWord() { return StringUtils.toString(matchRecord.getSubjectName()); } public void setText(String text) { System.err.println("Not implemented"); } public String toString() { StringWriter w = new StringWriter(); w.write("Match uid: " + uid + "--------\n"); for (String cName : fName2Id.keySet()) w.write(String.format("%4s: ", cName) + fName2Id.get(cName)); w.write("\n"); if (getBitScore() != 0) w.write("bitScore: " + getBitScore() + "\n"); if (getPercentIdentity() != 0) w.write("percentIdentity: " + getPercentIdentity() + "\n"); if (getExpected() != 0) w.write("expected: " + getExpected() + "\n"); if (getLength() != 0) w.write("length: " + getLength() + "\n"); if (getText() != null) w.write("text: " + getText() + "\n"); return w.toString(); } /** * parses a Accession id * * @return refseq id */ private static String parseRefSeqId(String aLine) { int pos = aLine.indexOf(IdParser.REFSEQ_TAG); if (pos != -1) { int start = pos + IdParser.REFSEQ_TAG.length(); int end = start; while (end < aLine.length() && (Character.isLetterOrDigit(aLine.charAt(end)) || aLine.charAt(end) == '_')) end++; if (end > start) return aLine.substring(start, end); } return null; } public int getSubjectId() { return matchRecord.getSubjectId(); } @Override public int getAlignedQueryStart() { return matchRecord.getQueryBegin() + 1; } @Override public int getAlignedQueryEnd() { return matchRecord.getQueryEnd() + 1; } @Override public int getRefLength() { return matchRecord.getTotalSubjectLen(); } /** * compute the BLAST frame * * @param frame (in range 0-5) * @return BLAST frame (in range -2 to 2) */ private static int computeBlastFrame(int frame) { return frame <= 2 ? frame + 1 : 2 - frame; } }
12,159
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAConnector.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/connector/DAAConnector.java
/* * DAAConnector.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.connector; import jloda.util.CanceledException; import jloda.util.ListOfLongs; import jloda.util.Single; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.daa.io.*; import megan.data.*; import megan.io.InputStreamAdapter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; /** * DAA connector * Daniel Huson, 8.2015 */ public class DAAConnector implements IConnector { private String fileName; private DAAHeader daaHeader; public static boolean openDAAFileOnlyIfMeganized = true; // only allow DAA files that have been Meganized public static final Object syncObject = new Object(); // use for changing openDAAFileOnlyIfMeganized private boolean longReads = false; public static boolean reuseReadBlockInGetter=true; /** * constructor * */ public DAAConnector(String fileName) throws IOException { setFile(fileName); if (openDAAFileOnlyIfMeganized && !isMeganized()) throw new IOException("DAA file has not been meganized: " + fileName); } @Override public void setFile(String file) throws IOException { this.fileName = file; this.daaHeader = new DAAHeader(fileName); daaHeader.load(); } @Override public String getFilename() { return fileName; } @Override public boolean isReadOnly() { return fileName != null && ((new File(fileName)).canWrite()); } @Override public long getUId() throws IOException { return Files.readAttributes(Paths.get(fileName), BasicFileAttributes.class).creationTime().toMillis(); } @Override public IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new AllReadsIterator(new ReadBlockGetterDAA(daaHeader, wantReadSequence, wantMatches, minScore, maxExpected, true, false, longReads)); } @Override public IReadBlockIterator getReadsIterator(String classification, int classId, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return getReadsIteratorForListOfClassIds(classification, Collections.singletonList(classId), minScore, maxExpected, wantReadSequence, wantMatches); } @Override public IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { var list = AccessClassificationsDAA.loadQueryLocations(daaHeader, classification, classIds); if (list == null) list = new ListOfLongs(); return new ReadBlockIterator(list.iterator(), list.size(), getReadBlockGetter(minScore, maxExpected, wantReadSequence, wantMatches)); } @Override public IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException { return new FindAllReadsIterator(regEx, findSelection, getAllReadsIterator(0, 10, true, true), canceled); } @Override public IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new ReadBlockGetterDAA(daaHeader, wantReadSequence, wantMatches, minScore, maxExpected, false, reuseReadBlockInGetter, longReads); } @Override public String[] getAllClassificationNames() { return daaHeader.getRefAnnotationNames(); } @Override public int getClassificationSize(String classificationName) throws IOException { var classificationBlock = getClassificationBlock(classificationName); if(classificationBlock==null) { System.err.printf("Error: getClassificationSize(%s): classificationBlock is null%n", classificationName); System.err.println("Known classifications: " + StringUtils.toString(getAllClassificationNames(),", ")); } return classificationBlock==null?0:classificationBlock.getKeySet().size(); } @Override public int getClassSize(String classificationName, int classId) throws IOException { var classificationBlock = getClassificationBlock(classificationName); if(classificationBlock==null) System.err.printf("Error: getClassSize(%s,%d): classificationBlock is null%n",classificationName,classId); return classificationBlock==null?0:classificationBlock.getSum(classId); } @Override public IClassificationBlock getClassificationBlock(String classificationName) throws IOException { return AccessClassificationsDAA.loadClassification(daaHeader, classificationName); } /** * rescan classifications after running the data processor * */ @Override public void updateClassifications(String[] cNames, List<UpdateItem> updateItemList, ProgressListener progressListener) throws IOException, CanceledException { final UpdateItemList updateItems = (UpdateItemList) updateItemList; long maxProgress = 0; for (int i = 0; i < cNames.length; i++) { maxProgress += updateItems.getClassIds(i).size(); } progressListener.setMaximum(maxProgress); final Map<Integer, ListOfLongs>[] fName2ClassId2Location = new HashMap[cNames.length]; final Map<Integer, Float>[] fName2ClassId2Weight = new HashMap[cNames.length]; for (int i = 0; i < cNames.length; i++) { fName2ClassId2Location[i] = new HashMap<>(10000); fName2ClassId2Weight[i] = new HashMap<>(10000); } for (int i = 0; i < cNames.length; i++) { final Map<Integer, ListOfLongs> classId2Location = fName2ClassId2Location[i]; final Map<Integer, Float> classId2weight = fName2ClassId2Weight[i]; for (Integer classId : updateItems.getClassIds(i)) { classId2weight.put(classId, updateItems.getWeight(i, classId)); final ListOfLongs positions = new ListOfLongs(); classId2Location.put(classId, positions); if (updateItems.getWeight(i, classId) > 0) { for (UpdateItem item = updateItems.getFirst(i, classId); item != null; item = item.getNextInClassification(i)) { positions.add(item.getReadUId()); } } progressListener.incrementProgress(); } } ModifyClassificationsDAA.saveClassifications(daaHeader, cNames, fName2ClassId2Location, fName2ClassId2Weight); } @Override public int getNumberOfReads() throws IOException { DAAHeader daaHeader = new DAAHeader(fileName); daaHeader.load(); return (int) daaHeader.getQueryRecords(); } @Override public int getNumberOfMatches() { return 0; // todo: fix /* DAAHeader daaHeader=new DAAHeader(fileName); daaHeader.load(); return (int)daaHeader.getNumberOfAlignments(); */ } @Override public void setNumberOfReads(int numberOfReads) { // todo: allow user to change number of reads //System.err.println("Not implemented"); } @Override public void putAuxiliaryData(Map<String, byte[]> label2data) throws IOException { final ByteOutputStream outs = new ByteOutputStream(100000); final OutputWriterLittleEndian w = new OutputWriterLittleEndian(outs); w.writeInt(label2data.size()); for (String label : label2data.keySet()) { w.writeNullTerminatedString(label.getBytes()); byte[] bytes = label2data.get(label); w.writeInt(bytes.length); w.write(bytes, 0, bytes.length); } DAAModifier.replaceBlock(daaHeader, BlockType.megan_aux_data, outs.getBytes(), outs.size()); } @Override public Map<String, byte[]> getAuxiliaryData() throws IOException { final Map<String, byte[]> label2data = new HashMap<>(); final byte[] block = DAAParser.getBlock(daaHeader, BlockType.megan_aux_data); if (block != null) { try (final InputReaderLittleEndian ins = new InputReaderLittleEndian(new InputStreamAdapter(new ByteInputStream(block, block.length)))) { final int numberOfLabels = ins.readInt(); for (int i = 0; i < numberOfLabels; i++) { final String label = ins.readNullTerminatedBytes(); final int size = ins.readInt(); final byte[] bytes = new byte[size]; final int length = ins.read_available(bytes, 0, size); if (length < size) { final byte[] tmp = new byte[length]; System.arraycopy(bytes, 0, tmp, 0, length); label2data.put(label, tmp); throw new IOException("buffer underflow"); } label2data.put(label, bytes); } } catch (IOException ex) { System.err.println("Incomplete aux block detected, will try to recover..."); // ignore any problems, megan should be able to recover from this } } return label2data; } public DAAHeader getDAAHeader() { return daaHeader; } public boolean isLongReads() { return longReads; } public void setLongReads(boolean longReads) { this.longReads = longReads; } public boolean isMeganized() { try { return DAAParser.isMeganizedDAAFile(fileName, true); } catch (Exception e) { return false; } } }
10,759
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClassificationBlockDAA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/daa/connector/ClassificationBlockDAA.java
/* * ClassificationBlockDAA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.daa.connector; import megan.data.IClassificationBlock; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * implements a classification block for DAA * Created by huson on 5/16/14. */ public class ClassificationBlockDAA implements IClassificationBlock { private final Map<Integer, Float> id2weight; private final Map<Integer, Integer> id2sum; private String classificationName; public ClassificationBlockDAA(String classificationName) { this.classificationName = classificationName; id2weight = new HashMap<>(); id2sum = new HashMap<>(); } public int getSum(Integer key) { var value = id2sum.get(key); return (value == null ? 0 : value); } public float getWeightedSum(Integer key) { var result = id2weight.get(key); if (result != null && result > 0) return result; else return getSum(key); } public void setSum(Integer key, int num) { id2sum.put(key, num); } @Override public void setWeightedSum(Integer key, float num) { id2weight.put(key, num); } public String getName() { return classificationName; } public void setName(String name) { classificationName = name; } public Set<Integer> getKeySet() { return id2sum.keySet(); } }
2,208
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DESeq.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/stats/DESeq.java
/* * DESeq.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.stats; import jloda.util.BitSetUtils; import java.util.*; /** * implementation of the DESeq method described in https://www.nature.com/articles/npre.2010.4282.1.pdf?origin=ppub * Daniel Huson, 7.2021 */ public class DESeq { /** * applies the DESeq analysis method * * @param class2counts for each class (either taxon or gene), the counts for all samples 1...m * @param condition1 which samples 1..m belong to first condition? * @param condition2 which samples 1..m belong to second condition? * @param pThreshold threshold for p value * @return result */ public static ArrayList<Row> apply(Map<String, Double[]> class2counts, BitSet condition1, BitSet condition2, double pThreshold) { if (condition1.cardinality() == 0 || condition2.cardinality() == 0 || BitSetUtils.intersection(condition1, condition2).cardinality() > 0) throw new IllegalArgumentException("Invalid conditions"); var samples = BitSetUtils.union(condition1, condition2); var sizes = estimateSizes(class2counts, samples); var counts1 = estimateCounts(class2counts, sizes, condition1); var counts2 = estimateCounts(class2counts, sizes, condition2); return null; } private static double[] estimateSizes(Map<String, Double[]> class2counts, BitSet samples) { var m = samples.cardinality(); var values = (ArrayList<Double>[]) new ArrayList[BitSetUtils.max(samples)]; for (var counts : class2counts.values()) { var denominator = 1.0; for (int s : BitSetUtils.members(samples)) { denominator *= counts[s]; } denominator = Math.pow(denominator, 1.0 / m); for (int s : BitSetUtils.members(samples)) { values[s].add(counts[s] / denominator); } } var result = new double[BitSetUtils.max(samples)]; for (int s : BitSetUtils.members(samples)) { var list = values[s]; list.sort(Double::compare); result[s] = list.get(list.size() / 2); } return result; } private static Map<String, Double> estimateCounts(Map<String, Double[]> class2counts, double[] sizes, BitSet condition) { var map = new HashMap<String, Double>(); for (var entry : class2counts.entrySet()) { var name = entry.getKey(); var counts = entry.getValue(); var sum = 0.0; for (var s : BitSetUtils.members(condition)) { sum += counts[s] / sizes[s]; } map.put(name, sum / condition.cardinality()); } return map; } public static class Row { private final String name; private final double foldValue; private final double pValue; public Row(String name, double foldValue, double pValue) { this.name = name; this.foldValue = foldValue; this.pValue = pValue; } public String getName() { return name; } public double getFoldValue() { return foldValue; } public double getpValue() { return pValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Row)) return false; Row row = (Row) o; return Double.compare(row.foldValue, foldValue) == 0 && Double.compare(row.pValue, pValue) == 0 && name.equals(row.name); } @Override public int hashCode() { return Objects.hash(name, foldValue, pValue); } } }
3,981
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SilvaLogFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/SilvaLogFileFilter.java
/* * SilvaLogFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A SILVA log file * Daniel Huson 4.2015 */ public class SilvaLogFileFilter extends FileFilterBase implements FilenameFilter { static private SilvaLogFileFilter instance; public static SilvaLogFileFilter getInstance() { if (instance == null) { instance = new SilvaLogFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private SilvaLogFileFilter() { add("txt"); add("log"); add("silva"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "SILVA log files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName)); return firstLine != null && firstLine.startsWith("Reading from fasta file"); } }
2,069
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
WindowUtilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/WindowUtilities.java
/* * WindowUtilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import javax.swing.*; import java.awt.*; /** * some Swing window utilities */ public class WindowUtilities { /** * bring to the front (using the swing thread) * */ public static void toFront(final Window window) { if (window != null) { Runnable runnable = () -> { window.setVisible(true); window.toFront(); }; if (SwingUtilities.isEventDispatchThread()) runnable.run(); else SwingUtilities.invokeLater(runnable); } } /** * bring to the front (using the swing thread) * */ public static void toFront(final JFrame frame) { // if (SwingUtilities.isEventDispatchThread()) // System.err.println("HellO!"); if (frame != null) { final Runnable runnable = () -> { frame.setVisible(true); frame.setState(JFrame.NORMAL); frame.toFront(); frame.requestFocus(); }; if (SwingUtilities.isEventDispatchThread()) runnable.run(); else SwingUtilities.invokeLater(runnable); } } }
2,056
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DAAFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/DAAFileFilter.java
/* * DAAFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import megan.daa.io.DAAParser; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * A DAA file filter * Daniel Huson 18.2015 */ public class DAAFileFilter extends FileFilterBase implements FilenameFilter { static private DAAFileFilter instance; public static DAAFileFilter getInstance() { if (instance == null) { instance = new DAAFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private DAAFileFilter() { add("daa"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "DAA files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; try { return DAAParser.isMeganizedDAAFile((new File(directory, fileName)).getPath(), false); } catch (IOException e) { return false; } } }
2,048
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExportStamp.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/ExportStamp.java
/* * ExportStamp.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.graph.NodeSet; import jloda.util.CanceledException; import jloda.util.CollectionUtils; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.classification.Classification; import megan.core.Director; import megan.viewer.ClassificationViewer; import megan.viewer.TaxonomicLevels; import megan.viewer.TaxonomyData; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; /** * Exports selected nodes in stamp profile * Created by huson on 1/13/16. */ public class ExportStamp { public static final String[] ranks = {TaxonomicLevels.Domain, TaxonomicLevels.Phylum, TaxonomicLevels.Class, TaxonomicLevels.Order, TaxonomicLevels.Family, TaxonomicLevels.Genus, TaxonomicLevels.Species }; public static final char[] letters = {'k', 'p', 'c', 'o', 'f', 'g', 's'}; /** * apply the exporter * * @return lines exported */ public static int apply(Director dir, String cName, File file, boolean allLevels, ProgressListener progressListener) throws IOException, CanceledException { final ClassificationViewer viewer = (ClassificationViewer) dir.getViewerByClassName(cName); final boolean taxonomy = cName.equalsIgnoreCase(Classification.Taxonomy); if (viewer == null) throw new IOException(cName + " Viewer not open"); final NodeSet selectedNodes = viewer.getSelectedNodes(); if (selectedNodes.size() == 0) { throw new IOException("No nodes selected"); } System.err.println("Writing file: " + file); progressListener.setSubtask("Processing " + cName + " nodes"); progressListener.setMaximum(selectedNodes.size()); progressListener.setProgress(0); int maxRankIndex = 0; if (allLevels) { if (taxonomy) { maxRankIndex = determineMaxTaxonomicRankIndex(selectedNodes); System.err.println("Exporting " + (maxRankIndex + 1) + " taxonomic levels down to rank of '" + ranks[maxRankIndex] + "'"); } else { maxRankIndex = determineMaxFunctionalIndex(selectedNodes); System.err.println("Exporting " + (maxRankIndex + 1) + " functional levels"); } } final int numberOfLevels = maxRankIndex + 1; // header format: // Level_1 Observation Ids sample0 sample1 sample2... int numberOfRows = 0; int nodesSkipped = 0; final int numberOfColumns = dir.getDocument().getNumberOfSamples(); try (BufferedWriter w = new BufferedWriter(new FileWriter(file))) { // write header line: for (int i = 0; i < numberOfLevels; i++) w.write("Level_" + (i + 1) + "\t"); w.write("Observation Ids"); for (String sample : dir.getDocument().getSampleNames()) { w.write("\t" + sample); } w.write("\n"); for (Node v : selectedNodes) { final String name = viewer.getLabel(v); final Integer classId = (Integer) v.getInfo(); if (maxRankIndex > 1) { final String path = taxonomy ? makePath(v, maxRankIndex) : makeFunctionalPath(viewer, v, maxRankIndex); if (path != null) w.write(String.format("%s\tID%d", path, classId)); else { if (nodesSkipped < 5) System.err.println("Skipping node: " + name); else if (nodesSkipped == 5) System.err.println("Skipping more nodes..."); nodesSkipped++; continue; } } else w.write(String.format("%s\tID%d", name, classId)); NodeData data = viewer.getNodeData(v); if (v.getOutDegree() == 0) { for (int i = 0; i < numberOfColumns; i++) w.write("\t" + data.getSummarized(i)); } else { for (int i = 0; i < numberOfColumns; i++) w.write("\t" + data.getAssigned(i)); } w.write("\n"); numberOfRows++; } } System.err.println("Nodes skipped: " + nodesSkipped); return numberOfRows; } /** * get all ranks above, or null, if incomplete * * @return all ranks or null */ private static String makePath(final Node v, int rankIndex) { final ArrayList<String> list = new ArrayList<>(); // first fill in names that are missing and the end of the path, e.g. // if path only leads to Phylum Proteobacteria, then all levels below Proteobacteria are labeled "(Proteobacteria)" { int topRankIndex = -1; String topRankTaxonName = null; Node w = v; while (topRankIndex == -1) { final Integer taxonId = (Integer) w.getInfo(); final int rank = TaxonomyData.getTaxonomicRank(taxonId); if (rank != 0) { final String rankName = TaxonomicLevels.getName(rank); final int index = StringUtils.getIndex(rankName, ranks); if (index != -1) { topRankIndex = index; topRankTaxonName = TaxonomyData.getName2IdMap().get(taxonId); } } if (w.getInDegree() == 1) w = w.getFirstInEdge().getSource(); else break; } while (rankIndex > topRankIndex) { list.add(letters[rankIndex] + "__(" + topRankTaxonName + ")"); rankIndex--; } } Node w = v; while (rankIndex >= 0) { final Integer taxonId = (Integer) w.getInfo(); final int rank = TaxonomyData.getTaxonomicRank(taxonId); if (rank != 0) { final String rankName = TaxonomicLevels.getName(rank); final int index = StringUtils.getIndex(rankName, ranks); if (index >= 0) { String previousName = (list.size() > 0 ? list.get(list.size() - 1).substring(3) : null); while (rankIndex > index) { list.add(letters[rankIndex] + "__(" + previousName + ")"); // fill in missing intermediate ranks rankIndex--; } if (index == rankIndex) { list.add(letters[rankIndex] + "__" + TaxonomyData.getName2IdMap().get(taxonId)); rankIndex--; } } } if (w.getInDegree() == 1) w = w.getFirstInEdge().getSource(); else break; } if (rankIndex == -1) return StringUtils.toString(CollectionUtils.reverseList(list), "\t"); return null; } /** * determine the max taxonomic rank index * * @return max taxonomic level */ private static int determineMaxTaxonomicRankIndex(NodeSet selectedNodes) { int maxRankIndex = -1; for (Node v : selectedNodes) { int rank = TaxonomyData.getTaxonomicRank((Integer) v.getInfo()); if (rank != 0) { String rankName = TaxonomicLevels.getName(rank); int index = StringUtils.getIndex(rankName, ranks); if (index > maxRankIndex) maxRankIndex = index; } } return maxRankIndex; } /** * determine the number of levels * * @return number of levels */ private static int determineMaxFunctionalIndex(NodeSet selectedNodes) { int levels = 0; for (Node v : selectedNodes) { int distance2root = 0; while (true) { distance2root++; if (v.getFirstInEdge() != null) v = v.getFirstInEdge().getSource(); else break; } levels = Math.max(levels, distance2root); } return levels - 1; // substract 1 because we will suppress the root } /** * make a functional path * * @return path */ private static String makeFunctionalPath(ClassificationViewer viewer, Node v, int maxRankIndex) { final ArrayList<String> path = new ArrayList<>(maxRankIndex); while (true) { path.add(viewer.getLabel(v)); if (v.getFirstInEdge() != null) v = v.getFirstInEdge().getSource(); else break; if (v.getFirstInEdge() == null) break; // this node is the root and we want to suppress the root } final StringBuilder buf = new StringBuilder(); int missing = maxRankIndex - path.size(); buf.append(path.remove(path.size() - 1)); buf.append("\t-".repeat(Math.max(0, missing))); while (path.size() > 0) { buf.append("\t").append(path.remove(path.size() - 1)); } return buf.toString(); } }
10,366
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScalingType.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/ScalingType.java
/* * ScalingType.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; public enum ScalingType {LINEAR, LOG, SQRT, PERCENT, ZSCORE}
890
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/MeganFileFilter.java
/* * MeganFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import java.io.FilenameFilter; /** * The megan file filter * Daniel Huson 2.2006 */ public class MeganFileFilter extends FileFilterBase implements FilenameFilter { public MeganFileFilter() { add("meg"); add("megan"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "MEGAN files"; } }
1,280
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LastMAFFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/LastMAFFileFilter.java
/* * LastMAFFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A last file in MAF format filter * Daniel Huson 4.2015 */ public class LastMAFFileFilter extends FileFilterBase implements FilenameFilter { static private LastMAFFileFilter instance; public static LastMAFFileFilter getInstance() { if (instance == null) { instance = new LastMAFFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private LastMAFFileFilter() { add("txt"); add("lastout"); add("last"); add("out"); add("maf"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "Last MAF files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (fileName.startsWith("!!!")) // always allow this return true; if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(directory, fileName)); return firstLine != null && firstLine.startsWith("# LAST"); } }
2,201
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
XIntArray.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/XIntArray.java
/* * XIntArray.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import megan.io.OutputWriter; import java.io.IOException; import java.util.Arrays; /** * An extended array of integers * Daniel Huson 3/2015 */ public class XIntArray { private final int SEGMENT_BITS; private final int SEGMENT_SIZE; // always a power of 2 private final int SEGMENT_MASK; private int[][] segments; private long maxIndex = -1; private long numberOfNonZeroEntries = 0; /** * constructs a new array of initial size 0. If size is known, use other constructor */ public XIntArray() { this((byte) 0); } /** * constructs a new array of the given size * */ public XIntArray(long size) { this((byte) (Math.min(30, 1 + Math.max(10, (int) (Math.log(size) / Math.log(2)))))); int segment = (int) (size >>> SEGMENT_BITS); grow(segment + 1); } /** * constructs a new array using the given number of bits as segmentation key (in the range 10 to 30) * */ public XIntArray(byte bits) { segments = new int[0][]; SEGMENT_BITS = bits; SEGMENT_SIZE = (1 << (SEGMENT_BITS)); SEGMENT_MASK = SEGMENT_SIZE - 1; /* System.err.println("SEGMENT_BITS: " + SEGMENT_BITS); System.err.println("SEGMENT_MASK: " + Integer.toBinaryString(SEGMENT_MASK)); System.err.println("SEGMENT_SIZE: " + SEGMENT_SIZE); */ } /** * Zeros the array */ public void clear() { for (int[] segment : segments) { Arrays.fill(segment, 0); } maxIndex = -1; numberOfNonZeroEntries = 0; } /** * put a value * */ public void put(long index, int value) { final int segment = (int) (index >>> SEGMENT_BITS); final int position = (int) (index & SEGMENT_MASK); final int old = segments[segment][position]; if (old == 0) { if (value != 0) { segments[segment][position] = value; numberOfNonZeroEntries++; } } else { segments[segment][position] = value; if (value == 0) numberOfNonZeroEntries--; } maxIndex = Math.max(maxIndex, index); } /** * put a value, If the index is larger than current maxIndex(), increases length of array * */ public void putAndEnsureCapacity(long index, int value) { int segment = (int) (index >>> SEGMENT_BITS); int position = (int) (index & SEGMENT_MASK); if (segment >= segments.length) { grow(segment + 1); segments[segment][position] = value; if (value != 0) numberOfNonZeroEntries++; } else { final int old = segments[segment][position]; if (old == 0) { if (value != 0) { segments[segment][position] = value; numberOfNonZeroEntries++; } } else { segments[segment][position] = value; if (value == 0) numberOfNonZeroEntries--; } } maxIndex = Math.max(maxIndex, index); } /** * get a value, no checks, assumes that all entries have been set * * @return value */ private int get(long index) { final int segment = (int) (index >>> SEGMENT_BITS); if (segment >= segments.length) return 0; else return segments[segment][(int) (index & SEGMENT_MASK)]; } /** * gets a value, returns 0 if too big * * @return value or 0 */ public int getEvenIfTooBig(long index) { int segment = (int) (index >>> SEGMENT_BITS); if (segment >= segments.length) return 0; else return segments[segment][(int) (index & SEGMENT_MASK)]; } /** * resizes the array */ private void grow(int newLength) { if (newLength < segments.length) throw new IllegalArgumentException("grow(newLine=" + newLength + "): can't grow smaller"); else if (newLength > segments.length) { final int[][] tmp = new int[newLength][]; System.arraycopy(segments, 0, tmp, 0, segments.length); for (int i = segments.length; i < newLength; i++) { tmp[i] = new int[SEGMENT_SIZE]; } segments = tmp; } } /** * returns the first n values * * @return first n values as string */ public String toString(long n) { StringBuilder buf = new StringBuilder(); for (long i = 0; i < Math.min(n, length()); i++) { buf.append(" ").append(get(i)); } return buf.toString(); } public long getMaxIndex() { return maxIndex; } private long length() { return maxIndex + 1; } public long getNumberOfNonZeroEntries() { return numberOfNonZeroEntries; } /** * write to stream in binary * */ public void write(OutputWriter outs) throws IOException { for (long index = 0; index < maxIndex; index++) { outs.writeInt(get(index)); } } /* public static void main(String[] args) { XIntArray array = new XIntArray((byte) 30); for (int i = 0; i < 1000000000; i++) { array.putAndEnsureCapacity(i, i); } for (int i = 0; i < 1000000000; i++) { if (array.get(i) != i) System.err.println("Error: " + i + " != " + array.get(i)); } System.err.println("Segments: " + array.segments.length); } */ }
6,539
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastParsingUtils.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlastParsingUtils.java
/* * BlastParsingUtils.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.util.NumberUtils; import megan.alignment.Blast2Alignment; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.StringTokenizer; /** * methods to help parse blast strings * Daniel Huson, 3.2018 */ public class BlastParsingUtils { /** * removes all of string from the second occurrence of the given word onward * * @return truncated string */ public static String truncateBeforeSecondOccurrence(String text, String word) { int pos = text.indexOf(word); if (pos == -1) return text; pos = text.indexOf(word, pos + 1); if (pos == -1) return text; else return text.substring(0, pos); } /** * grab the total query string * * @return query string */ public static String grabQueryString(String text) throws IOException { BufferedReader r = new BufferedReader(new StringReader(text)); String aLine; StringBuilder buf = new StringBuilder(); boolean passedScore = false; while ((aLine = r.readLine()) != null) { aLine = aLine.trim(); if (aLine.startsWith("Score")) { if (!passedScore) passedScore = true; else break; } if (aLine.startsWith("Query")) { String[] words = aLine.split(" +"); buf.append(words[2]); } } return buf.toString().replaceAll("\n", "").replaceAll("\r", ""); } /** * grab the total subject string * * @return subject string */ public static String grabSubjectString(String text) throws IOException { BufferedReader r = new BufferedReader(new StringReader(text)); String aLine; StringBuilder buf = new StringBuilder(); boolean passedScore = false; while ((aLine = r.readLine()) != null) { aLine = aLine.trim(); if (aLine.startsWith("Score")) { if (!passedScore) passedScore = true; else break; } if (aLine.startsWith("Sbjct")) { String[] words = aLine.split(" +"); buf.append(words[2]); } } return buf.toString().replaceAll("\n", "").replaceAll("\r", ""); } /** * grab the next token after the one in key * * @return next token */ public static String grabNext(String text, String key, String key2) { int pos = text.indexOf(key); int length = key.length(); if (pos == -1 && key2 != null) { pos = text.indexOf(key2); length = key2.length(); } if (pos == -1) return null; else return new StringTokenizer(text.substring(pos + length).trim()).nextToken(); } /** * grab the next three tokens after the one in key * * @return next token */ public static String[] grabNext3(String text, String key, String key2) { int pos = text.indexOf(key); int length = key.length(); if (pos == -1 && key2 != null) { pos = text.indexOf(key2); length = key2.length(); } if (pos == -1) return null; else { String[] result = new String[3]; StringTokenizer st = new StringTokenizer(text.substring(pos + length).trim()); for (int i = 0; i < 3; i++) { if (st.hasMoreTokens()) result[i] = st.nextToken(); else return null; // ran out of tokens, return null } return result; } } /** * grab the last token of the last line that contains the given key and is passed the first occurrence of "Score" * * @return token */ public static String grabLastInLinePassedScore(String text, String key) throws IOException { int scorePos = text.indexOf("Score"); if (scorePos == -1) throw new IOException("Token not found: 'Score'"); int end = text.lastIndexOf(key); if (end == -1) throw new IOException("Token not found: '" + key + "'"); if (end < scorePos) throw new IOException("Token not found before 'Score': '" + key + "'"); end = text.indexOf("\n", end); if (end == -1) end = text.length() - 1; // skip other preceding white space while (end > 0 && Character.isWhitespace(text.charAt(end))) end--; // end is now last letter of token int start = end; // find white space before last token: while (start > 0 && !Character.isWhitespace(text.charAt(start))) start--; start += 1; // start is now first letter of token return text.substring(start, end + 1); } /** * guesses the blast type * * @return blast type */ public static String guessBlastType(String blastText) { if (blastText == null || !blastText.contains("Query")) return Blast2Alignment.UNKNOWN; if (blastText.contains("Frame=") || (blastText.contains("Frame ="))) return Blast2Alignment.BLASTX; if (blastText.contains("Strand=") || blastText.contains("Strand =")) return Blast2Alignment.BLASTN; return Blast2Alignment.BLASTP; } /** * remove the header from a blast text (but keeping Length statement, if present) * * @return headerless blastText */ public static String removeReferenceHeaderFromBlastMatch(String blastText) { int index = blastText.indexOf("Length"); if (index == -1) index = blastText.indexOf("Score"); if (index > 0) return blastText.substring(index); else return blastText; } public static int getStartSubject(String text) { return NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Sbjct:", "Sbjct")); } public static int getEndSubject(String text) throws IOException { return NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Sbjct")); } }
7,174
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastPTextFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlastPTextFileFilter.java
/* * BlastPTextFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A BlastText file in text format filter * Daniel Huson 4.2015 */ public class BlastPTextFileFilter extends FileFilterBase implements FilenameFilter { static private BlastPTextFileFilter instance; public static BlastPTextFileFilter getInstance() { if (instance == null) { instance = new BlastPTextFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private BlastPTextFileFilter() { add("txt"); add("blastp"); add("blastout"); add("blast"); add("out"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "BLASTP text files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (fileName.startsWith("!!!")) // always allow this return true; if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName)); return firstLine != null && firstLine.startsWith("BLASTP"); } }
2,222
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
JPanelWithFXStageAndRoot.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/JPanelWithFXStageAndRoot.java
/* * JPanelWithFXStageAndRoot.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import javafx.scene.Node; import javafx.stage.Stage; import jloda.fx.util.IHasJavaFXStageAndRoot; import javax.swing.*; public class JPanelWithFXStageAndRoot extends JPanel implements IHasJavaFXStageAndRoot { private final Node root; private final Stage stage; public JPanelWithFXStageAndRoot(Node root, Stage stage) { super(); this.root = root; this.stage = stage; } @Override public Node getJavaFXRoot() { return root; } @Override public Stage getJavaFXStage() { return stage; } }
1,410
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DiversityIndex.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/DiversityIndex.java
/* * DiversityIndex.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.graph.Node; import jloda.util.progress.ProgressListener; import megan.viewer.ClassificationViewer; import megan.viewer.ViewerBase; import java.io.IOException; /** * compute different diversity indices * Daniel Huson, 4.2012 */ public class DiversityIndex { public static final String SHANNON = "Shannon"; public static final String SIMPSON_RECIPROCAL = "SimpsonReciprocal"; private static final double LOG2 = Math.log(2); /** * compute the Shannon-Weaver diversity index in bits * * @return index in bits */ public static String computeShannonWeaver(ViewerBase viewer, ProgressListener progressListener) throws IOException { if (viewer instanceof ClassificationViewer) return toString(viewer.getDocument().getSampleNamesAsArray(), computeShannonWeaver((ClassificationViewer) viewer, progressListener)); else return null; } /** * compute the Shannon-Weaver diversity index in bits * * @return index in bits */ private static double[] computeShannonWeaver(ClassificationViewer viewer, ProgressListener progressListener) throws IOException { progressListener.setMaximum(2L * viewer.getSelectedNodes().size()); progressListener.setProgress(0); int numberOfDatasets = viewer.getDocument().getNumberOfSamples(); double[] total = new double[numberOfDatasets]; for (Node v : viewer.getSelectedNodes()) { float[] summarized = viewer.getNodeData(v).getSummarized(); for (int i = 0; i < summarized.length; i++) total[i] += summarized[i]; progressListener.incrementProgress(); } double[] result = new double[numberOfDatasets]; for (int i = 0; i < result.length; i++) result[0] = 0d; for (Node v : viewer.getSelectedNodes()) { float[] summarized = viewer.getNodeData(v).getSummarized(); for (int i = 0; i < summarized.length; i++) { if (summarized[i] > 0) { double p = summarized[i] / total[i]; result[i] += p * Math.log(p) / LOG2; } } progressListener.incrementProgress(); } for (int i = 0; i < result.length; i++) result[i] = -result[i]; return result; } /** * compute the Shannon-Weaver diversity index in bits * * @return index in bits */ public static String computeSimpsonReciprocal(ViewerBase viewer, ProgressListener progressListener) throws IOException { if (viewer instanceof ClassificationViewer) return toString(viewer.getDocument().getSampleNamesAsArray(), computeSimpsonReciprocal((ClassificationViewer) viewer, progressListener)); else return null; } /** * compute the Shannon-Weaver diversity index in bits * * @return index in bits */ private static double[] computeSimpsonReciprocal(ClassificationViewer viewer, ProgressListener progressListener) throws IOException { progressListener.setMaximum(2L * viewer.getSelectedNodes().size()); progressListener.setProgress(0); int numberOfDatasets = viewer.getDocument().getNumberOfSamples(); double[] total = new double[numberOfDatasets]; for (Node v : viewer.getSelectedNodes()) { float[] summarized = viewer.getNodeData(v).getSummarized(); for (int i = 0; i < summarized.length; i++) total[i] += summarized[i]; progressListener.incrementProgress(); } double[] result = new double[numberOfDatasets]; for (Node v : viewer.getSelectedNodes()) { float[] summarized = viewer.getNodeData(v).getSummarized(); for (int i = 0; i < summarized.length; i++) { double p = summarized[i] / total[i]; result[i] += p * p; } progressListener.incrementProgress(); } for (int i = 0; i < result.length; i++) result[i] = result[i] > 0 ? 1.0 / result[i] : 0; return result; } /** * write numbers as string * * @return string */ private static String toString(String[] sampleNames, double[] values) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < sampleNames.length; i++) { buf.append(String.format("%s\t%.3f\n", sampleNames[i], i < values.length ? (values[i] + 0.00001) : 0)); } return buf.toString(); } }
5,435
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastTabFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlastTabFileFilter.java
/* * BlastTabFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A BlastText file in text format filter * Daniel Huson 4.2015 */ public class BlastTabFileFilter extends FileFilterBase implements FilenameFilter { static private BlastTabFileFilter instance; public static BlastTabFileFilter getInstance() { if (instance == null) { instance = new BlastTabFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private BlastTabFileFilter() { add("txt"); add("blastn"); add("blastx"); add("blastp"); add("blastout"); add("blast"); add("blasttab"); add("out"); add("tab"); add("tabout"); add("m8"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "BLAST tab files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName), "#", 1000); return firstLine != null && (firstLine.split("\t").length == 12 || firstLine.split("\t").length == 13); } }
2,310
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MothurFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/MothurFileFilter.java
/* * MothurFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * Mothur file filter * Daniel Huson 4.2015 */ public class MothurFileFilter extends FileFilterBase implements FilenameFilter { static private MothurFileFilter instance; public static MothurFileFilter getInstance() { if (instance == null) { instance = new MothurFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private MothurFileFilter() { add("txt"); add("mothur"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "Mothur files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; String line = FileUtils.getFirstLineFromFile(new File(fileName)); return line != null && line.split("\t").length == 2 && line.endsWith(";"); } }
2,030
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GraphicsUtilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/GraphicsUtilities.java
/* * GraphicsUtilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Node; import javafx.scene.image.ImageView; import jloda.swing.graphview.NodeShapeIcon; import jloda.util.NodeShape; import megan.core.Document; import java.awt.*; import java.awt.image.BufferedImage; /** * some graphics utilities * Created by huson on 11/27/15. */ public class GraphicsUtilities { /** * creates an icon to use with this sample for JavaFX * * @return icon */ public static Node makeSampleIconFX(Document doc, String sample, boolean setColor, boolean setShape, int size) { return new ImageView(SwingFXUtils.toFXImage(makeSampleIconSwing(doc, sample, setColor, setShape, size), null)); } /** * creates an icon to use with this sample for Swing * */ public static java.awt.image.BufferedImage makeSampleIconSwing(Document doc, String sample, boolean setColor, boolean setShape, int size) { Color color = null; if (setColor) { color = doc.getSampleAttributeTable().getSampleColor(sample); if (color == null) color = doc.getChartColorManager().getSampleColor(sample); } NodeShape shape = NodeShape.valueOfIgnoreCase(doc.getSampleAttributeTable().getSampleShape(sample)); if (!setShape || shape == null) shape = NodeShape.Rectangle; return (BufferedImage) new NodeShapeIcon(shape, size, color).getImage(); } }
2,285
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastNTextFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlastNTextFileFilter.java
/* * BlastNTextFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A BlastText file in text format filter * Daniel Huson 4.2015 */ public class BlastNTextFileFilter extends FileFilterBase implements FilenameFilter { static private BlastNTextFileFilter instance; public static BlastNTextFileFilter getInstance() { if (instance == null) { instance = new BlastNTextFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private BlastNTextFileFilter() { add("txt"); add("blastn"); add("blastout"); add("blast"); add("out"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "BLASTN text files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (fileName.startsWith("!!!")) // always allow this return true; if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName)); return firstLine != null && firstLine.startsWith("BLASTN"); } }
2,222
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExchangeabilityStatistics.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/ExchangeabilityStatistics.java
/* * ExchangeabilityStatistics.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; /** * some simple calculations in the context of Exchangeability Statistics */ class ExchangeabilityStatistics { /** * computes probility to see a split of taxa alignments along a read * Example: A A A A | B B B B * What is that probability that exactly a alignments to taxon A are then followed by b alignments to taxon B * */ public static double getProbability(int a, int b) { return 2.0 / binomialCoefficient(a + b, b); } /** * compute a binomial coefficient * */ private static long binomialCoefficient(int n, int k) { double result = 1; for (int i = 1; i <= k; i++) { result *= (double) (n + 1 - i) / (double) i; } return Math.round(result); } }
1,612
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganizedDAAFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/MeganizedDAAFileFilter.java
/* * MeganizedDAAFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import megan.daa.io.DAAParser; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * A DAA file filter * Daniel Huson 18.2015 */ public class MeganizedDAAFileFilter extends FileFilterBase implements FilenameFilter { static private MeganizedDAAFileFilter instance; public static MeganizedDAAFileFilter getInstance() { if (instance == null) { instance = new MeganizedDAAFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private MeganizedDAAFileFilter() { add("daa"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "DAA files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; try { return DAAParser.isMeganizedDAAFile((new File(directory, fileName)).getPath(), true); } catch (IOException e) { return false; } } }
2,101
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorUtilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/ColorUtilities.java
/* * ColorUtilities.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import java.awt.*; /** * Some utilities for colors * Daniel Huson, 12.2015 */ class ColorUtilities { /** * interpolate colors * Source: http://stackoverflow.com/questions/340209/generate-colors-between-red-and-green-for-a-power-meter * * @param p number between 0 and 1 * @return color */ public static Color interpolateHSB(Color start, Color end, float p) { float[] startHSB = Color.RGBtoHSB(start.getRed(), start.getGreen(), start.getBlue(), null); float[] endHSB = Color.RGBtoHSB(end.getRed(), end.getGreen(), end.getBlue(), null); float brightness = (startHSB[2] + endHSB[2]) / 2; float saturation = (startHSB[1] + endHSB[1]) / 2; float hueMax; float hueMin; if (startHSB[0] > endHSB[0]) { hueMax = startHSB[0]; hueMin = endHSB[0]; } else { hueMin = startHSB[0]; hueMax = endHSB[0]; } float hue = ((hueMax - hueMin) * p) + hueMin; return Color.getHSBColor(hue, saturation, brightness); } public static Color interpolateRGB(Color start, Color end, float p) { if (p <= 0.5) { final float a = 2 * (0.5f - p); final float b = (int) (2f * p * 255f); return new Color( (int) (a * start.getRed() + b), (int) (a * start.getGreen() + b), (int) (a * start.getBlue() + b), (start.getAlpha() + end.getAlpha()) / 2); } else { final float a = 2 * (p - 0.5f); final float b = (int) (2f * (1f - p) * 255f); return new Color( (int) (a * end.getRed() + b), (int) (a * end.getGreen() + b), (int) (a * end.getBlue() + b), (start.getAlpha() + end.getAlpha()) / 2); } /* final float a=(p>=0.5?1:1-2*p); // p=0: a=1, p>=0.5: a=0 final float b=(p<=0.5?1:2*(p-0.5f)); // p<=0.5: b=0, p==1: b=1 return new Color((int)(a*start.getRed()+b*end.getRed()), (int)(a*start.getGreen()+b*end.getGreen()), (int)(a*start.getBlue()+b*end.getBlue()), (start.getAlpha()+end.getAlpha())/2); */ } }
3,141
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TableCellListener.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/TableCellListener.java
/* * TableCellListener.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import javax.swing.*; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /* * This class listens for changes made to the data in the table via the * TableCellEditor. When editing is started, the value of the cell is saved * When editing is stopped the new value is saved. When the oold and new * values are different, then the provided Action is invoked. * * The source of the Action is a TableCellListener instance. * author: unknown */ public class TableCellListener implements PropertyChangeListener, Runnable { private final JTable table; private Action action; private int row; private int column; private Object oldValue; private Object newValue; /** * Create a TableCellListener. * * @param table the table to be monitored for data changes * @param action the Action to invoke when cell data is changed */ public TableCellListener(JTable table, Action action) { this.table = table; this.action = action; this.table.addPropertyChangeListener(this); } /** * Create a TableCellListener with a copy of all the data relevant to * the replace of data for a given cell. * * @param row the row of the changed cell * @param column the column of the changed cell * @param oldValue the old data of the changed cell * @param newValue the new data of the changed cell */ private TableCellListener(JTable table, int row, int column, Object oldValue, Object newValue) { this.table = table; this.row = row; this.column = column; this.oldValue = oldValue; this.newValue = newValue; } /** * Get the column that was last edited. * * @return the column that was edited */ private int getColumn() { return column; } /** * Get the new value in the cell. * * @return the new value in the cell */ private Object getNewValue() { return newValue; } /** * Get the old value of the cell. * * @return the old value of the cell */ private Object getOldValue() { return oldValue; } /** * Get the row that was last edited. * * @return the row that was edited */ private int getRow() { return row; } /** * Get the table of the cell that was changed. * * @return the table of the cell that was changed */ private JTable getTable() { return table; } // // Implement the PropertyChangeListener interface // public void propertyChange(PropertyChangeEvent e) { // A cell has started/stopped editing if ("tableCellEditor".equals(e.getPropertyName())) { if (table.isEditing()) { processEditingStarted(); } else { processEditingStopped(); } } } /* * Save information of the cell about to be edited */ private void processEditingStarted() { // The invokeLater is necessary because the editing row and editing // column of the table have not been set when the "tableCellEditor" // PropertyChangeEvent is fired. // This results in the "run" method being invoked SwingUtilities.invokeLater(this); } /* * See above. */ public void run() { row = table.convertRowIndexToModel(table.getEditingRow()); // row = table.getEditingRow(); column = table.convertColumnIndexToModel(table.getEditingColumn()); oldValue = table.getModel().getValueAt(row, column); newValue = null; } /* * Update the Cell history when necessary */ private void processEditingStopped() { if (row >= table.getRowCount() || column >= table.getColumnCount()) return; newValue = table.getModel().getValueAt(row, column); // The data has changed, invoke the supplied Action if (!newValue.equals(oldValue)) { // Make a copy of the data in case another cell starts editing // while processing this replace TableCellListener tcl = new TableCellListener( getTable(), getRow(), getColumn(), getOldValue(), getNewValue()); ActionEvent event = new ActionEvent( tcl, ActionEvent.ACTION_PERFORMED, ""); action.actionPerformed(event); } } }
5,430
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlosumMatrix.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlosumMatrix.java
/* * BlosumMatrix.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * A blosum matrix * Daniel Huson, 11.2011 */ public class BlosumMatrix { private final int[][] matrix; private static BlosumMatrix BLOSUM90; private static BlosumMatrix BLOSUM80; private static BlosumMatrix BLOSUM62; private static BlosumMatrix BLOSUM50; private static BlosumMatrix BLOSUM45; private final static String BLOSUM90_INPUT = "A R N D C Q E G H I L K M F P S T W Y V B J Z X * \n" + "A 5 -2 -2 -3 -1 -1 -1 0 -2 -2 -2 -1 -2 -3 -1 1 0 -4 -3 -1 -2 -2 -1 -1 -6 \n" + "R -2 6 -1 -3 -5 1 -1 -3 0 -4 -3 2 -2 -4 -3 -1 -2 -4 -3 -3 -2 -3 0 -1 -6 \n" + "N -2 -1 7 1 -4 0 -1 -1 0 -4 -4 0 -3 -4 -3 0 0 -5 -3 -4 5 -4 -1 -1 -6 \n" + "D -3 -3 1 7 -5 -1 1 -2 -2 -5 -5 -1 -4 -5 -3 -1 -2 -6 -4 -5 5 -5 1 -1 -6 \n" + "C -1 -5 -4 -5 9 -4 -6 -4 -5 -2 -2 -4 -2 -3 -4 -2 -2 -4 -4 -2 -4 -2 -5 -1 -6 \n" + "Q -1 1 0 -1 -4 7 2 -3 1 -4 -3 1 0 -4 -2 -1 -1 -3 -3 -3 -1 -3 5 -1 -6 \n" + "E -1 -1 -1 1 -6 2 6 -3 -1 -4 -4 0 -3 -5 -2 -1 -1 -5 -4 -3 1 -4 5 -1 -6 \n" + "G 0 -3 -1 -2 -4 -3 -3 6 -3 -5 -5 -2 -4 -5 -3 -1 -3 -4 -5 -5 -2 -5 -3 -1 -6 \n" + "H -2 0 0 -2 -5 1 -1 -3 8 -4 -4 -1 -3 -2 -3 -2 -2 -3 1 -4 -1 -4 0 -1 -6 \n" + "I -2 -4 -4 -5 -2 -4 -4 -5 -4 5 1 -4 1 -1 -4 -3 -1 -4 -2 3 -5 3 -4 -1 -6 \n" + "L -2 -3 -4 -5 -2 -3 -4 -5 -4 1 5 -3 2 0 -4 -3 -2 -3 -2 0 -5 4 -4 -1 -6 \n" + "K -1 2 0 -1 -4 1 0 -2 -1 -4 -3 6 -2 -4 -2 -1 -1 -5 -3 -3 -1 -3 1 -1 -6 \n" + "M -2 -2 -3 -4 -2 0 -3 -4 -3 1 2 -2 7 -1 -3 -2 -1 -2 -2 0 -4 2 -2 -1 -6 \n" + "F -3 -4 -4 -5 -3 -4 -5 -5 -2 -1 0 -4 -1 7 -4 -3 -3 0 3 -2 -4 0 -4 -1 -6 \n" + "P -1 -3 -3 -3 -4 -2 -2 -3 -3 -4 -4 -2 -3 -4 8 -2 -2 -5 -4 -3 -3 -4 -2 -1 -6 \n" + "S 1 -1 0 -1 -2 -1 -1 -1 -2 -3 -3 -1 -2 -3 -2 5 1 -4 -3 -2 0 -3 -1 -1 -6 \n" + "T 0 -2 0 -2 -2 -1 -1 -3 -2 -1 -2 -1 -1 -3 -2 1 6 -4 -2 -1 -1 -2 -1 -1 -6 \n" + "W -4 -4 -5 -6 -4 -3 -5 -4 -3 -4 -3 -5 -2 0 -5 -4 -4 11 2 -3 -6 -3 -4 -1 -6 \n" + "Y -3 -3 -3 -4 -4 -3 -4 -5 1 -2 -2 -3 -2 3 -4 -3 -2 2 8 -3 -4 -2 -3 -1 -6 \n" + "V -1 -3 -4 -5 -2 -3 -3 -5 -4 3 0 -3 0 -2 -3 -2 -1 -3 -3 5 -4 1 -3 -1 -6 \n" + "B -2 -2 5 5 -4 -1 1 -2 -1 -5 -5 -1 -4 -4 -3 0 -1 -6 -4 -4 5 -5 0 -1 -6 \n" + "J -2 -3 -4 -5 -2 -3 -4 -5 -4 3 4 -3 2 0 -4 -3 -2 -3 -2 1 -5 4 -4 -1 -6 \n" + "Z -1 0 -1 1 -5 5 5 -3 0 -4 -4 1 -2 -4 -2 -1 -1 -4 -3 -3 0 -4 5 -1 -6 \n" + "X -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -6 \n" + "* -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 1 \n"; private final static String BLOSUM80_INPUT = "A R N D C Q E G H I L K M F P S T W Y V B J Z X * \n" + "A 5 -2 -2 -2 -1 -1 -1 0 -2 -2 -2 -1 -1 -3 -1 1 0 -3 -2 0 -2 -2 -1 -1 -6 \n" + "R -2 6 -1 -2 -4 1 -1 -3 0 -3 -3 2 -2 -4 -2 -1 -1 -4 -3 -3 -1 -3 0 -1 -6 \n" + "N -2 -1 6 1 -3 0 -1 -1 0 -4 -4 0 -3 -4 -3 0 0 -4 -3 -4 5 -4 0 -1 -6 \n" + "D -2 -2 1 6 -4 -1 1 -2 -2 -4 -5 -1 -4 -4 -2 -1 -1 -6 -4 -4 5 -5 1 -1 -6 \n" + "C -1 -4 -3 -4 9 -4 -5 -4 -4 -2 -2 -4 -2 -3 -4 -2 -1 -3 -3 -1 -4 -2 -4 -1 -6 \n" + "Q -1 1 0 -1 -4 6 2 -2 1 -3 -3 1 0 -4 -2 0 -1 -3 -2 -3 0 -3 4 -1 -6 \n" + "E -1 -1 -1 1 -5 2 6 -3 0 -4 -4 1 -2 -4 -2 0 -1 -4 -3 -3 1 -4 5 -1 -6 \n" + "G 0 -3 -1 -2 -4 -2 -3 6 -3 -5 -4 -2 -4 -4 -3 -1 -2 -4 -4 -4 -1 -5 -3 -1 -6 \n" + "H -2 0 0 -2 -4 1 0 -3 8 -4 -3 -1 -2 -2 -3 -1 -2 -3 2 -4 -1 -4 0 -1 -6 \n" + "I -2 -3 -4 -4 -2 -3 -4 -5 -4 5 1 -3 1 -1 -4 -3 -1 -3 -2 3 -4 3 -4 -1 -6 \n" + "L -2 -3 -4 -5 -2 -3 -4 -4 -3 1 4 -3 2 0 -3 -3 -2 -2 -2 1 -4 3 -3 -1 -6 \n" + "K -1 2 0 -1 -4 1 1 -2 -1 -3 -3 5 -2 -4 -1 -1 -1 -4 -3 -3 -1 -3 1 -1 -6 \n" + "M -1 -2 -3 -4 -2 0 -2 -4 -2 1 2 -2 6 0 -3 -2 -1 -2 -2 1 -3 2 -1 -1 -6 \n" + "F -3 -4 -4 -4 -3 -4 -4 -4 -2 -1 0 -4 0 6 -4 -3 -2 0 3 -1 -4 0 -4 -1 -6 \n" + "P -1 -2 -3 -2 -4 -2 -2 -3 -3 -4 -3 -1 -3 -4 8 -1 -2 -5 -4 -3 -2 -4 -2 -1 -6 \n" + "S 1 -1 0 -1 -2 0 0 -1 -1 -3 -3 -1 -2 -3 -1 5 1 -4 -2 -2 0 -3 0 -1 -6 \n" + "T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -2 -1 -1 -2 -2 1 5 -4 -2 0 -1 -1 -1 -1 -6 \n" + "W -3 -4 -4 -6 -3 -3 -4 -4 -3 -3 -2 -4 -2 0 -5 -4 -4 11 2 -3 -5 -3 -3 -1 -6 \n" + "Y -2 -3 -3 -4 -3 -2 -3 -4 2 -2 -2 -3 -2 3 -4 -2 -2 2 7 -2 -3 -2 -3 -1 -6 \n" + "V 0 -3 -4 -4 -1 -3 -3 -4 -4 3 1 -3 1 -1 -3 -2 0 -3 -2 4 -4 2 -3 -1 -6 \n" + "B -2 -1 5 5 -4 0 1 -1 -1 -4 -4 -1 -3 -4 -2 0 -1 -5 -3 -4 5 -4 0 -1 -6 \n" + "J -2 -3 -4 -5 -2 -3 -4 -5 -4 3 3 -3 2 0 -4 -3 -1 -3 -2 2 -4 3 -3 -1 -6 \n" + "Z -1 0 0 1 -4 4 5 -3 0 -4 -3 1 -1 -4 -2 0 -1 -3 -3 -3 0 -3 5 -1 -6 \n" + "X -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -6 \n" + "* -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 1 \n"; private final static String BLOSUM62_INPUT = "A R N D C Q E G H I L K M F P S T W Y V B Z X *\n" + "A 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4 \n" + "R -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4 \n" + "N -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4 \n" + "D -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4 \n" + "C 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4 \n" + "Q -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4 \n" + "E -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 \n" + "G 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4 \n" + "H -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4 \n" + "I -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4 \n" + "L -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4 \n" + "K -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4 \n" + "M -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4 \n" + "F -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4 \n" + "P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4 \n" + "S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4 \n" + "T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4 \n" + "W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4 \n" + "Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4 \n" + "V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4 \n" + "B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4 \n" + "Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 \n" + "X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4 \n" + "* -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1 \n"; private final static String BLOSUM50_INPUT = "A R N D C Q E G H I L K M F P S T W Y V B Z X * \n" + "A 5 -2 -1 -2 -1 -1 -1 0 -2 -1 -2 -1 -1 -3 -1 1 0 -3 -2 0 -2 -1 -1 -5 \n" + "R -2 7 -1 -2 -4 1 0 -3 0 -4 -3 3 -2 -3 -3 -1 -1 -3 -1 -3 -1 0 -1 -5 \n" + "N -1 -1 7 2 -2 0 0 0 1 -3 -4 0 -2 -4 -2 1 0 -4 -2 -3 4 0 -1 -5 \n" + "D -2 -2 2 8 -4 0 2 -1 -1 -4 -4 -1 -4 -5 -1 0 -1 -5 -3 -4 5 1 -1 -5 \n" + "C -1 -4 -2 -4 13 -3 -3 -3 -3 -2 -2 -3 -2 -2 -4 -1 -1 -5 -3 -1 -3 -3 -2 -5 \n" + "Q -1 1 0 0 -3 7 2 -2 1 -3 -2 2 0 -4 -1 0 -1 -1 -1 -3 0 4 -1 -5 \n" + "E -1 0 0 2 -3 2 6 -3 0 -4 -3 1 -2 -3 -1 -1 -1 -3 -2 -3 1 5 -1 -5 \n" + "G 0 -3 0 -1 -3 -2 -3 8 -2 -4 -4 -2 -3 -4 -2 0 -2 -3 -3 -4 -1 -2 -2 -5 \n" + "H -2 0 1 -1 -3 1 0 -2 10 -4 -3 0 -1 -1 -2 -1 -2 -3 2 -4 0 0 -1 -5 \n" + "I -1 -4 -3 -4 -2 -3 -4 -4 -4 5 2 -3 2 0 -3 -3 -1 -3 -1 4 -4 -3 -1 -5 \n" + "L -2 -3 -4 -4 -2 -2 -3 -4 -3 2 5 -3 3 1 -4 -3 -1 -2 -1 1 -4 -3 -1 -5 \n" + "K -1 3 0 -1 -3 2 1 -2 0 -3 -3 6 -2 -4 -1 0 -1 -3 -2 -3 0 1 -1 -5 \n" + "M -1 -2 -2 -4 -2 0 -2 -3 -1 2 3 -2 7 0 -3 -2 -1 -1 0 1 -3 -1 -1 -5 \n" + "F -3 -3 -4 -5 -2 -4 -3 -4 -1 0 1 -4 0 8 -4 -3 -2 1 4 -1 -4 -4 -2 -5 \n" + "P -1 -3 -2 -1 -4 -1 -1 -2 -2 -3 -4 -1 -3 -4 10 -1 -1 -4 -3 -3 -2 -1 -2 -5 \n" + "S 1 -1 1 0 -1 0 -1 0 -1 -3 -3 0 -2 -3 -1 5 2 -4 -2 -2 0 0 -1 -5 \n" + "T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 2 5 -3 -2 0 0 -1 0 -5 \n" + "W -3 -3 -4 -5 -5 -1 -3 -3 -3 -3 -2 -3 -1 1 -4 -4 -3 15 2 -3 -5 -2 -3 -5 \n" + "Y -2 -1 -2 -3 -3 -1 -2 -3 2 -1 -1 -2 0 4 -3 -2 -2 2 8 -1 -3 -2 -1 -5 \n" + "V 0 -3 -3 -4 -1 -3 -3 -4 -4 4 1 -3 1 -1 -3 -2 0 -3 -1 5 -4 -3 -1 -5 \n" + "B -2 -1 4 5 -3 0 1 -1 0 -4 -4 0 -3 -4 -2 0 0 -5 -3 -4 5 2 -1 -5 \n" + "Z -1 0 0 1 -3 4 5 -2 0 -3 -3 1 -1 -4 -1 0 -1 -2 -2 -3 2 5 -1 -5 \n" + "X -1 -1 -1 -1 -2 -1 -1 -2 -1 -1 -1 -1 -1 -2 -2 -1 0 -3 -1 -1 -1 -1 -1 -5 \n" + "* -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 1 \n"; private final static String BLOSUM45_INPUT = "A R N D C Q E G H I L K M F P S T W Y V B J Z X * \n" + "A 5 -2 -1 -2 -1 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -2 -2 0 -1 -1 -1 -1 -5 \n" + "R -2 7 0 -1 -3 1 0 -2 0 -3 -2 3 -1 -2 -2 -1 -1 -2 -1 -2 -1 -3 1 -1 -5 \n" + "N -1 0 6 2 -2 0 0 0 1 -2 -3 0 -2 -2 -2 1 0 -4 -2 -3 5 -3 0 -1 -5 \n" + "D -2 -1 2 7 -3 0 2 -1 0 -4 -3 0 -3 -4 -1 0 -1 -4 -2 -3 6 -3 1 -1 -5 \n" + "C -1 -3 -2 -3 12 -3 -3 -3 -3 -3 -2 -3 -2 -2 -4 -1 -1 -5 -3 -1 -2 -2 -3 -1 -5 \n" + "Q -1 1 0 0 -3 6 2 -2 1 -2 -2 1 0 -4 -1 0 -1 -2 -1 -3 0 -2 4 -1 -5 \n" + "E -1 0 0 2 -3 2 6 -2 0 -3 -2 1 -2 -3 0 0 -1 -3 -2 -3 1 -3 5 -1 -5 \n" + "G 0 -2 0 -1 -3 -2 -2 7 -2 -4 -3 -2 -2 -3 -2 0 -2 -2 -3 -3 -1 -4 -2 -1 -5 \n" + "H -2 0 1 0 -3 1 0 -2 10 -3 -2 -1 0 -2 -2 -1 -2 -3 2 -3 0 -2 0 -1 -5 \n" + "I -1 -3 -2 -4 -3 -2 -3 -4 -3 5 2 -3 2 0 -2 -2 -1 -2 0 3 -3 4 -3 -1 -5 \n" + "L -1 -2 -3 -3 -2 -2 -2 -3 -2 2 5 -3 2 1 -3 -3 -1 -2 0 1 -3 4 -2 -1 -5 \n" + "K -1 3 0 0 -3 1 1 -2 -1 -3 -3 5 -1 -3 -1 -1 -1 -2 -1 -2 0 -3 1 -1 -5 \n" + "M -1 -1 -2 -3 -2 0 -2 -2 0 2 2 -1 6 0 -2 -2 -1 -2 0 1 -2 2 -1 -1 -5 \n" + "F -2 -2 -2 -4 -2 -4 -3 -3 -2 0 1 -3 0 8 -3 -2 -1 1 3 0 -3 1 -3 -1 -5 \n" + "P -1 -2 -2 -1 -4 -1 0 -2 -2 -2 -3 -1 -2 -3 9 -1 -1 -3 -3 -3 -2 -3 -1 -1 -5 \n" + "S 1 -1 1 0 -1 0 0 0 -1 -2 -3 -1 -2 -2 -1 4 2 -4 -2 -1 0 -2 0 -1 -5 \n" + "T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -1 -1 2 5 -3 -1 0 0 -1 -1 -1 -5 \n" + "W -2 -2 -4 -4 -5 -2 -3 -2 -3 -2 -2 -2 -2 1 -3 -4 -3 15 3 -3 -4 -2 -2 -1 -5 \n" + "Y -2 -1 -2 -2 -3 -1 -2 -3 2 0 0 -1 0 3 -3 -2 -1 3 8 -1 -2 0 -2 -1 -5 \n" + "V 0 -2 -3 -3 -1 -3 -3 -3 -3 3 1 -2 1 0 -3 -1 0 -3 -1 5 -3 2 -3 -1 -5 \n" + "B -1 -1 5 6 -2 0 1 -1 0 -3 -3 0 -2 -3 -2 0 0 -4 -2 -3 5 -3 1 -1 -5 \n" + "J -1 -3 -3 -3 -2 -2 -3 -4 -2 4 4 -3 2 1 -3 -2 -1 -2 0 2 -3 4 -2 -1 -5 \n" + "Z -1 1 0 1 -3 4 5 -2 0 -3 -2 1 -1 -3 -1 0 -1 -2 -2 -3 1 -2 5 -1 -5 \n" + "X -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -5 \n" + "* -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 1 \n"; /** * constructor */ public BlosumMatrix() { matrix = new int[128][128]; for (int[] row : matrix) { Arrays.fill(row, 0, row.length, -20); } } /** * get the score for two letters * * @return score, or -20, if matrix not defined for (a,b) */ public int getScore(byte a, byte b) { return matrix[a][b]; } public static BlosumMatrix get(String which) throws IOException { if (which.equalsIgnoreCase("BLOSUM90")) return getBlosum90(); else if (which.equalsIgnoreCase("BLOSUM80")) return getBlosum80(); else if (which.equalsIgnoreCase("BLOSUM62")) return getBlosum62(); else if (which.equalsIgnoreCase("BLOSUM50")) return getBlosum50(); else if (which.equalsIgnoreCase("BLOSUM45")) return getBlosum45(); throw new IOException("Unrecognized BLOSUM matrix: " + which); } /** * get the blosum 90 matrix * * @return blosum 90 */ private static BlosumMatrix getBlosum90() { try { if (BLOSUM90 == null) { BLOSUM90 = new BlosumMatrix(); BLOSUM90.load(new StringReader(BLOSUM90_INPUT)); } return BLOSUM90; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * get the blosum 80 matrix * * @return blosum 80 */ private static BlosumMatrix getBlosum80() { try { if (BLOSUM80 == null) { BLOSUM80 = new BlosumMatrix(); BLOSUM80.load(new StringReader(BLOSUM80_INPUT)); } return BLOSUM80; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * get the blosum 62 matrix * * @return blosum 62 */ public static BlosumMatrix getBlosum62() { try { if (BLOSUM62 == null) { BLOSUM62 = new BlosumMatrix(); BLOSUM62.load(new StringReader(BLOSUM62_INPUT)); } return BLOSUM62; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * get the blosum 50 matrix * * @return blosum 50 */ private static BlosumMatrix getBlosum50() { try { if (BLOSUM50 == null) { BLOSUM50 = new BlosumMatrix(); BLOSUM50.load(new StringReader(BLOSUM50_INPUT)); } return BLOSUM50; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * get the blosum 45 matrix * * @return blosum 45 */ private static BlosumMatrix getBlosum45() { try { if (BLOSUM45 == null) { BLOSUM45 = new BlosumMatrix(); BLOSUM45.load(new StringReader(BLOSUM45_INPUT)); } return BLOSUM45; } catch (Exception ex) { throw new RuntimeException(ex); } } /** * load a matrix * */ private void load(Reader r0) throws IOException { BufferedReader r = new BufferedReader(r0); char[] mapPos2Char = null; String aLine; int cols = 0; while ((aLine = r.readLine()) != null) { aLine = aLine.trim(); if (aLine.length() == 0 || aLine.startsWith("#")) continue; if (mapPos2Char == null) // must be first line listing all letters { String[] tokens = aLine.split(" "); cols = tokens.length; if (tokens.length < 20) throw new IOException("Expected >=20 tokens, got: " + tokens.length + " in line: " + aLine); List<String> list = new LinkedList<>(Arrays.asList(tokens)); int count = 0; mapPos2Char = new char[list.size()]; for (String label : list) { char c = Character.toUpperCase(label.charAt(0)); mapPos2Char[count++] = c; } } else // a definition line { String[] tokens = aLine.split(" "); if (tokens.length != cols + 1) throw new IOException("Expected " + (cols + 1) + " tokens, got: " + tokens.length + " in line: " + aLine); char c = Character.toUpperCase(tokens[0].charAt(0)); for (int i = 1; i < tokens.length; i++) { int value = Integer.parseInt(tokens[i]); char d = mapPos2Char[i - 1]; matrix[c][d] = value; } } } } }
19,334
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAMFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/SAMFileFilter.java
/* * SAMFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A sam file filter * Daniel Huson 10.2014 */ public class SAMFileFilter extends FileFilterBase implements FilenameFilter { static private SAMFileFilter instance; public static SAMFileFilter getInstance() { if (instance == null) { instance = new SAMFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private SAMFileFilter() { add("sam"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "SAM files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName)); return firstLine != null && (firstLine.startsWith("@HD") || firstLine.startsWith("@PG") || firstLine.startsWith("@SQ")); } }
2,037
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastXTextFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BlastXTextFileFilter.java
/* * BlastXTextFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import java.io.File; import java.io.FilenameFilter; /** * A BlastText file in text format filter * Daniel Huson 4.2015 */ public class BlastXTextFileFilter extends FileFilterBase implements FilenameFilter { static private BlastXTextFileFilter instance; public static BlastXTextFileFilter getInstance() { if (instance == null) { instance = new BlastXTextFileFilter(); instance.setAllowGZipped(true); instance.setAllowZipped(true); } return instance; } private BlastXTextFileFilter() { add("txt"); add("blastx"); add("blastout"); add("blast"); add("out"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "BLASTX text files"; } /** * is file acceptable? * * @return true if acceptable */ @Override public boolean accept(File directory, String fileName) { if (fileName.startsWith("!!!")) // always allow this return true; if (!super.accept(directory, fileName)) return false; String firstLine = FileUtils.getFirstLineFromFile(new File(fileName)); return firstLine != null && firstLine.startsWith("BLASTX"); } }
2,222
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BiomFileFilter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/util/BiomFileFilter.java
/* * BiomFileFilter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.util; import jloda.swing.util.FileFilterBase; import jloda.util.FileUtils; import jloda.util.StringUtils; import java.io.File; import java.io.FilenameFilter; /** * The biom file filter * Daniel Huson 9.2017 */ public class BiomFileFilter extends FileFilterBase implements FilenameFilter { public enum Version {V1, V2, All} private final Version version; /** * default constructor. Accepts all versions */ public BiomFileFilter() { this(Version.All); } /** * constructor * * @param v version to accept */ public BiomFileFilter(Version v) { this.version = v; add("biom"); if (version == Version.V1 || version == Version.All) { add("biom1"); //add("txt"); } if (version == Version.V2 || version == Version.All) add("biom2"); } /** * @return description of file matching the filter */ public String getBriefDescription() { return "BIOM files"; } @Override public boolean accept(File dir, String name) { if (super.accept(dir, name)) { final byte[] bytes = FileUtils.getFirstBytesFromFile(new File(dir, name), 4); boolean isV2 = (bytes != null && bytes[0] != '{' && StringUtils.toString(bytes).contains("ノHDF")); return (version == Version.All || (version == Version.V1 && !isV2) || (version == Version.V2 && isV2)); } return false; } public static boolean isBiom1File(String file) { return new BiomFileFilter(Version.V1).accept(file); } public static boolean isBiom2File(String file) { return new BiomFileFilter(Version.V2).accept(file); } public static boolean isBiomFile(String file) { return new BiomFileFilter(Version.All).accept(file); } }
2,643
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z