From 6ffcf85ecb3a59181ef75a41d679952cf085f457 Mon Sep 17 00:00:00 2001 From: "cmzmasek@gmail.com" Date: Thu, 5 Jun 2014 17:28:04 +0000 Subject: [PATCH] added URL tree reading back --- .../src/org/forester/archaeopteryx/Constants.java | 4 +- .../src/org/forester/archaeopteryx/MainFrame.java | 3731 ++++++------- .../archaeopteryx/MainFrameApplication.java | 5558 ++++++++++---------- .../org/forester/phylogeny/PhylogenyMethods.java | 3598 ++++++------- .../src/org/forester/util/ForesterConstants.java | 4 +- 5 files changed, 6493 insertions(+), 6402 deletions(-) diff --git a/forester/java/src/org/forester/archaeopteryx/Constants.java b/forester/java/src/org/forester/archaeopteryx/Constants.java index 038f965..6172d3e 100644 --- a/forester/java/src/org/forester/archaeopteryx/Constants.java +++ b/forester/java/src/org/forester/archaeopteryx/Constants.java @@ -42,8 +42,8 @@ public final class Constants { public final static boolean __SYNTH_LF = false; // TODO remove me public final static boolean ALLOW_DDBJ_BLAST = false; public final static String PRG_NAME = "Archaeopteryx"; - final static String VERSION = "0.989 beta"; - final static String PRG_DATE = "140514"; + final static String VERSION = "0.9891 beta"; + final static String PRG_DATE = "140605"; final static String DEFAULT_CONFIGURATION_FILE_NAME = "_aptx_configuration_file"; final static String[] DEFAULT_FONT_CHOICES = { "Arial", "Helvetica", "Verdana", "Tahoma", "Dialog", "Lucida Sans", "SansSerif", "Sans-serif", "Sans" }; diff --git a/forester/java/src/org/forester/archaeopteryx/MainFrame.java b/forester/java/src/org/forester/archaeopteryx/MainFrame.java index 4bac494..377c999 100644 --- a/forester/java/src/org/forester/archaeopteryx/MainFrame.java +++ b/forester/java/src/org/forester/archaeopteryx/MainFrame.java @@ -1,1865 +1,1866 @@ -// $Id: -// FORESTER -- software libraries and applications -// for evolutionary biology research and applications. -// -// Copyright (C) 2008-2010 Christian M. Zmasek -// All rights reserved -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -// -// Contact: phylosoft @ gmail . com -// WWW: https://sites.google.com/site/cmzmasek/home/software/forester - -package org.forester.archaeopteryx; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.NoSuchElementException; -import java.util.Set; - -import javax.swing.Box; -import javax.swing.JApplet; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.JTextField; -import javax.swing.SwingUtilities; - -import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE; -import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION; -import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE; -import org.forester.archaeopteryx.tools.InferenceManager; -import org.forester.archaeopteryx.tools.ProcessPool; -import org.forester.archaeopteryx.tools.ProcessRunning; -import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION; -import org.forester.phylogeny.Phylogeny; -import org.forester.phylogeny.PhylogenyMethods; -import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY; -import org.forester.phylogeny.PhylogenyNode; -import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE; -import org.forester.phylogeny.data.Annotation; -import org.forester.phylogeny.data.NodeVisualData.NodeFill; -import org.forester.phylogeny.data.NodeVisualData.NodeShape; -import org.forester.sdi.GSDI; -import org.forester.sdi.GSDIR; -import org.forester.sdi.SDIException; -import org.forester.util.ForesterConstants; -import org.forester.util.ForesterUtil; - -public abstract class MainFrame extends JFrame implements ActionListener { - - static final String USE_MOUSEWHEEL_SHIFT_TO_ROTATE = "In this display type, use mousewheel + Shift to rotate [or A and S]"; - static final String PHYLOXML_REF_TOOL_TIP = Constants.PHYLOXML_REFERENCE; //TODO //FIXME - static final String APTX_REF_TOOL_TIP = Constants.APTX_REFERENCE; - private static final long serialVersionUID = 3655000897845508358L; - final static Font menu_font = new Font( Configuration.getDefaultFontFamilyName(), - Font.PLAIN, - 10 ); - static final String TYPE_MENU_HEADER = "Type"; - static final String RECTANGULAR_TYPE_CBMI_LABEL = "Rectangular"; - static final String EURO_TYPE_CBMI_LABEL = "Euro Type"; - static final String CURVED_TYPE_CBMI_LABEL = "Curved"; - static final String TRIANGULAR_TYPE_CBMI_LABEL = "Triangular"; - static final String CONVEX_TYPE_CBMI_LABEL = "Convex"; - static final String ROUNDED_TYPE_CBMI_LABEL = "Rounded"; - static final String UNROOTED_TYPE_CBMI_LABEL = "Unrooted (alpha)"; //TODO - static final String CIRCULAR_TYPE_CBMI_LABEL = "Circular (alpha)"; //TODO - static final String OPTIONS_HEADER = "Options"; - static final String SEARCH_SUBHEADER = "Search:"; - static final String DISPLAY_SUBHEADER = "Display:"; - static final String SEARCH_TERMS_ONLY_LABEL = "Match Complete Terms Only"; - static final String SEARCH_CASE_SENSITIVE_LABEL = "Case Sensitive"; - static final String INVERSE_SEARCH_RESULT_LABEL = "Negate Result"; - static final String DISPLAY_BRANCH_LENGTH_VALUES_LABEL = "Branch Length Values"; - static final String COLOR_BY_TAXONOMIC_GROUP = "Colorize by Taxonomic Group"; - static final String DISPLAY_SCALE_LABEL = "Scale"; - static final String NON_LINED_UP_CLADOGRAMS_LABEL = "Non-Lined Up Cladograms"; - static final String UNIFORM_CLADOGRAMS_LABEL = "Total Node Sum Dependent Cladograms"; - static final String LABEL_DIRECTION_LABEL = "Radial Labels"; - static final String LABEL_DIRECTION_TIP = "To use radial node labels in radial and unrooted display types"; - static final String SCREEN_ANTIALIAS_LABEL = "Antialias"; - static final String COLOR_LABELS_LABEL = "Colorize Labels Same as Parent Branch"; - static final String BG_GRAD_LABEL = "Background Color Gradient"; - static final String DISPLAY_NODE_BOXES_LABEL_EXT = "External Node Shapes"; - static final String DISPLAY_NODE_BOXES_LABEL_INT = "Internal Node Shapes"; - static final String SHOW_OVERVIEW_LABEL = "Overview"; - static final String FONT_SIZE_MENU_LABEL = "Font Size"; - static final String NONUNIFORM_CLADOGRAMS_LABEL = "External Node Sum Dependent Cladograms"; - static final String SHOW_DOMAIN_LABELS_LABEL = "Domain Labels"; - static final String SHOW_ANN_REF_SOURCE_LABEL = "Seq Annotation Ref Sources"; - static final String COLOR_LABELS_TIP = "To use parent branch colors for node labels as well, need to turn off taxonomy dependent colorization and turn on branch colorization for this to become apparent"; - static final String ABBREV_SN_LABEL = "Abbreviate Scientific Taxonomic Names"; - static final String TAXONOMY_COLORIZE_NODE_SHAPES_LABEL = "Colorize Node Shapes According to Taxonomy"; - static final String CYCLE_NODE_SHAPE_LABEL = "Cycle Node Shapes"; - static final String CYCLE_NODE_FILL_LABEL = "Cycle Node Fill Type"; - static final String CHOOSE_NODE_SIZE_LABEL = "Choose Node Shape Size"; - static final String SHOW_CONF_STDDEV_LABEL = "Confidence Standard Deviations"; - static final String USE_BRACKETS_FOR_CONF_IN_NH_LABEL = "Use Brackets for Confidence Values"; - static final String USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL = "Use Internal Node Names for Confidence Values"; - static final String SHOW_BASIC_TREE_INFORMATION_LABEL = "Basic Tree Information"; - JMenuBar _jmenubar; - JMenu _file_jmenu; - JMenu _tools_menu; - JMenu _view_jmenu; - JMenu _options_jmenu; - JMenu _font_size_menu; - JMenu _help_jmenu; - JMenuItem[] _load_phylogeny_from_webservice_menu_items; - // Analysis menu - JMenu _analysis_menu; - JMenuItem _load_species_tree_item; - JMenuItem _gsdi_item; - JMenuItem _gsdir_item; - JMenuItem _lineage_inference; - // file menu: - JMenuItem _open_item; - JMenuItem _save_item; - JMenuItem _save_all_item; - JMenuItem _close_item; - JMenuItem _exit_item; - JMenuItem _new_item; - // tools menu: - JMenuItem _midpoint_root_item; - JMenuItem _taxcolor_item; - JMenuItem _confcolor_item; - JMenuItem _color_rank_jmi; - JMenuItem _collapse_species_specific_subtrees; - JMenuItem _collapse_below_threshold; //TODO implememt me - JMenuItem _obtain_detailed_taxonomic_information_jmi; - JMenuItem _obtain_detailed_taxonomic_information_deleting_jmi; - JMenuItem _obtain_seq_information_jmi; - JMenuItem _move_node_names_to_tax_sn_jmi; - JMenuItem _move_node_names_to_seq_names_jmi; - JMenuItem _extract_tax_code_from_node_names_jmi; - JMenuItem _annotate_item; - JMenuItem _remove_branch_color_item; - JMenuItem _remove_visual_styles_item; - // font size menu: - JMenuItem _super_tiny_fonts_item; - JMenuItem _tiny_fonts_item; - JMenuItem _small_fonts_item; - JMenuItem _medium_fonts_item; - JMenuItem _large_fonts_item; - // options menu: - // _ screen and print - JMenuItem _choose_font_mi; - JMenuItem _switch_colors_mi; - JCheckBoxMenuItem _label_direction_cbmi; - // _ screen display - JCheckBoxMenuItem _screen_antialias_cbmi; - JCheckBoxMenuItem _background_gradient_cbmi; - JRadioButtonMenuItem _non_lined_up_cladograms_rbmi; - JRadioButtonMenuItem _uniform_cladograms_rbmi; - JRadioButtonMenuItem _ext_node_dependent_cladogram_rbmi; - JCheckBoxMenuItem _show_branch_length_values_cbmi; - JCheckBoxMenuItem _color_by_taxonomic_group_cbmi; - JCheckBoxMenuItem _show_scale_cbmi; //TODO fix me - JCheckBoxMenuItem _show_overview_cbmi; - JCheckBoxMenuItem _show_domain_labels; - JCheckBoxMenuItem _show_annotation_ref_source; - JCheckBoxMenuItem _abbreviate_scientific_names; - JCheckBoxMenuItem _color_labels_same_as_parent_branch; - JMenuItem _overview_placment_mi; - JMenuItem _choose_minimal_confidence_mi; - JCheckBoxMenuItem _show_default_node_shapes_internal_cbmi; - JCheckBoxMenuItem _show_default_node_shapes_external_cbmi; - JMenuItem _cycle_node_shape_mi; - JMenuItem _cycle_node_fill_mi; - JMenuItem _choose_node_size_mi; - JCheckBoxMenuItem _show_confidence_stddev_cbmi; - // _ print - JCheckBoxMenuItem _graphics_export_visible_only_cbmi; - JCheckBoxMenuItem _antialias_print_cbmi; - JCheckBoxMenuItem _print_black_and_white_cbmi; - JCheckBoxMenuItem _print_using_actual_size_cbmi; - JCheckBoxMenuItem _graphics_export_using_actual_size_cbmi; - JMenuItem _print_size_mi; - JMenuItem _choose_pdf_width_mi; - // _ parsing - JCheckBoxMenuItem _internal_number_are_confidence_for_nh_parsing_cbmi; - JRadioButtonMenuItem _extract_taxonomy_no_rbmi; - JRadioButtonMenuItem _extract_taxonomy_agressive_rbmi; - JRadioButtonMenuItem _extract_taxonomy_pfam_strict_rbmi; - JRadioButtonMenuItem _extract_taxonomy_pfam_relaxed_rbmi; - JCheckBoxMenuItem _replace_underscores_cbmi; - JCheckBoxMenuItem _allow_errors_in_distance_to_parent_cbmi; - JCheckBoxMenuItem _use_brackets_for_conf_in_nh_export_cbmi; - JCheckBoxMenuItem _use_internal_names_for_conf_in_nh_export_cbmi; - // _ search - JCheckBoxMenuItem _search_case_senstive_cbmi; - JCheckBoxMenuItem _search_whole_words_only_cbmi; - JCheckBoxMenuItem _inverse_search_result_cbmi; - // type menu: - JMenu _type_menu; - JCheckBoxMenuItem _rectangular_type_cbmi; - JCheckBoxMenuItem _triangular_type_cbmi; - JCheckBoxMenuItem _curved_type_cbmi; - JCheckBoxMenuItem _convex_type_cbmi; - JCheckBoxMenuItem _euro_type_cbmi; - JCheckBoxMenuItem _rounded_type_cbmi; - JCheckBoxMenuItem _unrooted_type_cbmi; - JCheckBoxMenuItem _circular_type_cbmi; - // view as text menu: - JMenuItem _view_as_NH_item; - JMenuItem _view_as_XML_item; - JMenuItem _view_as_nexus_item; - JMenuItem _display_basic_information_item; - // help menu: - JMenuItem _about_item; - JMenuItem _help_item; - JMenuItem _website_item; - JMenuItem _phyloxml_website_item; - JMenuItem _phyloxml_ref_item; - JMenuItem _aptx_ref_item; - // process menu: - JMenu _process_menu; - // Handy pointers to child components: - MainPanel _mainpanel; - Container _contentpane; - final LinkedList _textframes = new LinkedList(); ; - Configuration _configuration; - Options _options; - private Phylogeny _species_tree; - InferenceManager _inference_manager; - final ProcessPool _process_pool; - private String _previous_node_annotation_ref; - - MainFrame() { - _process_pool = ProcessPool.createInstance(); - } - - /** - * Action performed. - */ - @Override - public void actionPerformed( final ActionEvent e ) { - final Object o = e.getSource(); - boolean is_applet = false; - JApplet applet = null; - if ( getCurrentTreePanel() != null ) { - is_applet = getCurrentTreePanel().isApplet(); - if ( is_applet ) { - applet = getCurrentTreePanel().obtainApplet(); - } - } - if ( o == _exit_item ) { - close(); - } - else if ( o == _gsdi_item ) { - if ( isSubtreeDisplayed() ) { - return; - } - executeGSDI(); - } - else if ( o == _gsdir_item ) { - if ( isSubtreeDisplayed() ) { - return; - } - executeGSDIR(); - } - else if ( o == _taxcolor_item ) { - taxColor(); - } - else if ( o == _confcolor_item ) { - confColor(); - } - else if ( o == _color_rank_jmi ) { - colorRank(); - } - else if ( o == _collapse_species_specific_subtrees ) { - if ( isSubtreeDisplayed() ) { - return; - } - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().collapseSpeciesSpecificSubtrees(); - } - } - else if ( o == _remove_branch_color_item ) { - if ( isSubtreeDisplayed() ) { - return; - } - removeBranchColors(); - } - else if ( o == _remove_visual_styles_item ) { - if ( isSubtreeDisplayed() ) { - return; - } - removeVisualStyles(); - } - else if ( o == _midpoint_root_item ) { - if ( isSubtreeDisplayed() ) { - return; - } - midpointRoot(); - } - else if ( o == _annotate_item ) { - annotateSequences(); - } - else if ( o == _switch_colors_mi ) { - switchColors(); - } - else if ( o == _display_basic_information_item ) { - displayBasicInformation( getCurrentTreePanel().getTreeFile() ); - } - else if ( o == _view_as_NH_item ) { - viewAsNH(); - } - else if ( o == _view_as_XML_item ) { - viewAsXML(); - } - else if ( o == _view_as_nexus_item ) { - viewAsNexus(); - } - else if ( o == _super_tiny_fonts_item ) { - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().setSuperTinyFonts(); - getCurrentTreePanel().repaint(); - } - } - else if ( o == _tiny_fonts_item ) { - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().setTinyFonts(); - getCurrentTreePanel().repaint(); - } - } - else if ( o == _small_fonts_item ) { - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().setSmallFonts(); - getCurrentTreePanel().repaint(); - } - } - else if ( o == _medium_fonts_item ) { - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().setMediumFonts(); - getCurrentTreePanel().repaint(); - } - } - else if ( o == _large_fonts_item ) { - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().setLargeFonts(); - getCurrentTreePanel().repaint(); - } - } - else if ( o == _choose_font_mi ) { - chooseFont(); - } - else if ( o == _choose_minimal_confidence_mi ) { - chooseMinimalConfidence(); - } - else if ( o == _choose_node_size_mi ) { - chooseNodeSize( getOptions(), this ); - } - else if ( o == _overview_placment_mi ) { - MainFrame.cycleOverview( getOptions(), getCurrentTreePanel() ); - } - else if ( o == _cycle_node_fill_mi ) { - MainFrame.cycleNodeFill( getOptions(), getCurrentTreePanel() ); - } - else if ( o == _cycle_node_shape_mi ) { - MainFrame.cycleNodeShape( getOptions(), getCurrentTreePanel() ); - } - else if ( o == _screen_antialias_cbmi ) { - updateOptions( getOptions() ); - updateScreenTextAntialias( getMainPanel().getTreePanels() ); - } - else if ( o == _background_gradient_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _show_domain_labels ) { - updateOptions( getOptions() ); - } - else if ( o == _show_annotation_ref_source ) { - updateOptions( getOptions() ); - } - else if ( o == _abbreviate_scientific_names ) { - updateOptions( getOptions() ); - } - else if ( o == _color_labels_same_as_parent_branch ) { - updateOptions( getOptions() ); - } - else if ( o == _show_default_node_shapes_internal_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _show_default_node_shapes_external_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _non_lined_up_cladograms_rbmi ) { - updateOptions( getOptions() ); - showWhole(); - } - else if ( o == _uniform_cladograms_rbmi ) { - updateOptions( getOptions() ); - showWhole(); - } - else if ( o == _ext_node_dependent_cladogram_rbmi ) { - updateOptions( getOptions() ); - showWhole(); - } - else if ( o == _search_case_senstive_cbmi ) { - updateOptions( getOptions() ); - getMainPanel().getControlPanel().search0(); - getMainPanel().getControlPanel().search1(); - } - else if ( o == _search_whole_words_only_cbmi ) { - updateOptions( getOptions() ); - getMainPanel().getControlPanel().search0(); - getMainPanel().getControlPanel().search1(); - } - else if ( o == _inverse_search_result_cbmi ) { - updateOptions( getOptions() ); - getMainPanel().getControlPanel().search0(); - getMainPanel().getControlPanel().search1(); - } - else if ( o == _show_scale_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _show_branch_length_values_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _color_by_taxonomic_group_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _show_confidence_stddev_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _use_brackets_for_conf_in_nh_export_cbmi ) { - if ( _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) { - _use_internal_names_for_conf_in_nh_export_cbmi.setSelected( false ); - } - updateOptions( getOptions() ); - } - else if ( o == _use_internal_names_for_conf_in_nh_export_cbmi ) { - if ( _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) { - _use_brackets_for_conf_in_nh_export_cbmi.setSelected( false ); - } - updateOptions( getOptions() ); - } - else if ( o == _label_direction_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _show_overview_cbmi ) { - updateOptions( getOptions() ); - if ( getCurrentTreePanel() != null ) { - getCurrentTreePanel().updateOvSizes(); - } - } - else if ( ( o == _rectangular_type_cbmi ) || ( o == _triangular_type_cbmi ) || ( o == _curved_type_cbmi ) - || ( o == _convex_type_cbmi ) || ( o == _euro_type_cbmi ) || ( o == _rounded_type_cbmi ) - || ( o == _unrooted_type_cbmi ) || ( o == _circular_type_cbmi ) ) { - typeChanged( o ); - } - else if ( o == _about_item ) { - about(); - } - else if ( o == _help_item ) { - help(); - } - else if ( o == _website_item ) { - try { - AptxUtil.openWebsite( Constants.APTX_WEB_SITE, is_applet, applet ); - } - catch ( final IOException e1 ) { - ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); - } - } - else if ( o == _phyloxml_website_item ) { - try { - AptxUtil.openWebsite( Constants.PHYLOXML_WEB_SITE, is_applet, applet ); - } - catch ( final IOException e1 ) { - ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); - } - } - else if ( o == _aptx_ref_item ) { - try { - AptxUtil.openWebsite( Constants.APTX_REFERENCE_URL, is_applet, applet ); - } - catch ( final IOException e1 ) { - ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); - } - } - else if ( o == _phyloxml_ref_item ) { - try { - AptxUtil.openWebsite( Constants.PHYLOXML_REFERENCE_URL, is_applet, applet ); - } - catch ( final IOException e1 ) { - ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); - } - } - else { - if ( _load_phylogeny_from_webservice_menu_items != null ) { - for( int i = 0; i < _load_phylogeny_from_webservice_menu_items.length; ++i ) { - if ( o == _load_phylogeny_from_webservice_menu_items[ i ] ) { - readPhylogeniesFromWebservice( i ); - } - } - } - } - _contentpane.repaint(); - } - - public Configuration getConfiguration() { - return _configuration; - } - - /** - * This method returns the current external node data which - * has been selected by the user by clicking the "Return ..." - * menu item. This method is expected to be called from Javascript or - * something like it. - * - * @return current external node data as String - */ - public String getCurrentExternalNodesDataBuffer() { - return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString(); - } - - public int getCurrentExternalNodesDataBufferChangeCounter() { - return getCurrentTreePanel().getCurrentExternalNodesDataBufferChangeCounter(); - } - - public int getCurrentExternalNodesDataBufferLength() { - return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString().length(); - } - - public InferenceManager getInferenceManager() { - return _inference_manager; - } - - public MainPanel getMainPanel() { - return _mainpanel; - } - - public Options getOptions() { - return _options; - } - - public ProcessPool getProcessPool() { - return _process_pool; - } - - public void showTextFrame( final String s, final String title ) { - checkTextFrames(); - _textframes.addLast( TextFrame.instantiate( s, title, _textframes ) ); - } - - public void showWhole() { - _mainpanel.getControlPanel().showWhole(); - } - - public void updateProcessMenu() { - // In general Swing is not thread safe. - // See "Swing's Threading Policy". - SwingUtilities.invokeLater( new Runnable() { - - @Override - public void run() { - doUpdateProcessMenu(); - } - } ); - } - - void activateSaveAllIfNeeded() { - if ( ( getMainPanel().getTabbedPane() != null ) && ( getMainPanel().getTabbedPane().getTabCount() > 1 ) ) { - _save_all_item.setEnabled( true ); - } - else { - _save_all_item.setEnabled( false ); - } - } - - void buildFileMenu() { - _file_jmenu = createMenu( "File", getConfiguration() ); - _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) ); - customizeJMenuItem( _exit_item ); - _jmenubar.add( _file_jmenu ); - } - - void buildFontSizeMenu() { - _font_size_menu = createMenu( FONT_SIZE_MENU_LABEL, getConfiguration() ); - _font_size_menu.add( _super_tiny_fonts_item = new JMenuItem( "Super Tiny Fonts" ) ); - _font_size_menu.add( _tiny_fonts_item = new JMenuItem( "Tiny Fonts" ) ); - _font_size_menu.add( _small_fonts_item = new JMenuItem( "Small Fonts" ) ); - _font_size_menu.add( _medium_fonts_item = new JMenuItem( "Medium Fonts" ) ); - _font_size_menu.add( _large_fonts_item = new JMenuItem( "Large Fonts" ) ); - customizeJMenuItem( _super_tiny_fonts_item ); - customizeJMenuItem( _tiny_fonts_item ); - customizeJMenuItem( _small_fonts_item ); - customizeJMenuItem( _medium_fonts_item ); - customizeJMenuItem( _large_fonts_item ); - _jmenubar.add( _font_size_menu ); - } - - void buildHelpMenu() { - _help_jmenu = createMenu( "Help", getConfiguration() ); - _help_jmenu.add( _help_item = new JMenuItem( "Help" ) ); - _help_jmenu.add( _website_item = new JMenuItem( "Archaeopteryx Home" ) ); - _aptx_ref_item = new JMenuItem( "Archaeopteryx Reference" ); - _help_jmenu.add( _phyloxml_website_item = new JMenuItem( "phyloXML Home" ) ); - _help_jmenu.add( _phyloxml_ref_item = new JMenuItem( "phyloXML Reference" ) ); - _help_jmenu.addSeparator(); - _help_jmenu.add( _about_item = new JMenuItem( "About" ) ); - customizeJMenuItem( _help_item ); - customizeJMenuItem( _website_item ); - customizeJMenuItem( _phyloxml_website_item ); - customizeJMenuItem( _aptx_ref_item ); - customizeJMenuItem( _phyloxml_ref_item ); - customizeJMenuItem( _about_item ); - _phyloxml_ref_item.setToolTipText( PHYLOXML_REF_TOOL_TIP ); - _aptx_ref_item.setToolTipText( APTX_REF_TOOL_TIP ); - _jmenubar.add( _help_jmenu ); - } - - void buildTypeMenu() { - _type_menu = createMenu( TYPE_MENU_HEADER, getConfiguration() ); - _type_menu.add( _rectangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.RECTANGULAR_TYPE_CBMI_LABEL ) ); - _type_menu.add( _euro_type_cbmi = new JCheckBoxMenuItem( MainFrame.EURO_TYPE_CBMI_LABEL ) ); - _type_menu.add( _rounded_type_cbmi = new JCheckBoxMenuItem( MainFrame.ROUNDED_TYPE_CBMI_LABEL ) ); - _type_menu.add( _curved_type_cbmi = new JCheckBoxMenuItem( MainFrame.CURVED_TYPE_CBMI_LABEL ) ); - _type_menu.add( _triangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.TRIANGULAR_TYPE_CBMI_LABEL ) ); - _type_menu.add( _convex_type_cbmi = new JCheckBoxMenuItem( MainFrame.CONVEX_TYPE_CBMI_LABEL ) ); - _type_menu.add( _unrooted_type_cbmi = new JCheckBoxMenuItem( MainFrame.UNROOTED_TYPE_CBMI_LABEL ) ); - _type_menu.add( _circular_type_cbmi = new JCheckBoxMenuItem( MainFrame.CIRCULAR_TYPE_CBMI_LABEL ) ); - customizeCheckBoxMenuItem( _rectangular_type_cbmi, false ); - customizeCheckBoxMenuItem( _triangular_type_cbmi, false ); - customizeCheckBoxMenuItem( _euro_type_cbmi, false ); - customizeCheckBoxMenuItem( _rounded_type_cbmi, false ); - customizeCheckBoxMenuItem( _curved_type_cbmi, false ); - customizeCheckBoxMenuItem( _convex_type_cbmi, false ); - customizeCheckBoxMenuItem( _unrooted_type_cbmi, false ); - customizeCheckBoxMenuItem( _circular_type_cbmi, false ); - _unrooted_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE ); - _circular_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE ); - initializeTypeMenu( getOptions() ); - _jmenubar.add( _type_menu ); - } - - void buildViewMenu() { - _view_jmenu = createMenu( "View", getConfiguration() ); - _view_jmenu.add( _display_basic_information_item = new JMenuItem( SHOW_BASIC_TREE_INFORMATION_LABEL ) ); - _view_jmenu.addSeparator(); - _view_jmenu.add( _view_as_XML_item = new JMenuItem( "as phyloXML" ) ); - _view_jmenu.add( _view_as_NH_item = new JMenuItem( "as Newick" ) ); - _view_jmenu.add( _view_as_nexus_item = new JMenuItem( "as Nexus" ) ); - customizeJMenuItem( _display_basic_information_item ); - customizeJMenuItem( _view_as_NH_item ); - customizeJMenuItem( _view_as_XML_item ); - customizeJMenuItem( _view_as_nexus_item ); - _jmenubar.add( _view_jmenu ); - } - - void checkTextFrames() { - if ( _textframes.size() > 5 ) { - try { - if ( _textframes.getFirst() != null ) { - _textframes.getFirst().removeMe(); - } - else { - _textframes.removeFirst(); - } - } - catch ( final NoSuchElementException e ) { - // Ignore. - } - } - } - - void close() { - removeAllTextFrames(); - if ( _mainpanel != null ) { - _mainpanel.terminate(); - } - if ( _contentpane != null ) { - _contentpane.removeAll(); - } - setVisible( false ); - dispose(); - } - - void colorRank() { - if ( _mainpanel.getCurrentTreePanel() != null ) { - final String[] ranks = AptxUtil.getAllPossibleRanks(); - final String rank = ( String ) JOptionPane - .showInputDialog( this, - "What rank should the colorization be based on", - "Rank Selection", - JOptionPane.QUESTION_MESSAGE, - null, - ranks, - null ); - if ( !ForesterUtil.isEmpty( rank ) ) { - _mainpanel.getCurrentTreePanel().colorRank( rank ); - } - } - } - - void confColor() { - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().confColor(); - } - } - - void customizeCheckBoxMenuItem( final JCheckBoxMenuItem item, final boolean is_selected ) { - if ( item != null ) { - item.setFont( MainFrame.menu_font ); - if ( !getConfiguration().isUseNativeUI() ) { - item.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); - item.setForeground( getConfiguration().getGuiMenuTextColor() ); - } - item.setSelected( is_selected ); - item.addActionListener( this ); - } - } - - JMenuItem customizeJMenuItem( final JMenuItem jmi ) { - if ( jmi != null ) { - jmi.setFont( MainFrame.menu_font ); - if ( !getConfiguration().isUseNativeUI() ) { - jmi.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); - jmi.setForeground( getConfiguration().getGuiMenuTextColor() ); - } - jmi.addActionListener( this ); - } - return jmi; - } - - void customizeRadioButtonMenuItem( final JRadioButtonMenuItem item, final boolean is_selected ) { - if ( item != null ) { - item.setFont( MainFrame.menu_font ); - if ( !getConfiguration().isUseNativeUI() ) { - item.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); - item.setForeground( getConfiguration().getGuiMenuTextColor() ); - } - item.setSelected( is_selected ); - item.addActionListener( this ); - } - } - - void displayBasicInformation( final File treefile ) { - if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { - String title = "Basic Information"; - if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { - title = title + " for \"" + _mainpanel.getCurrentPhylogeny().getName() + "\""; - } - showTextFrame( AptxUtil.createBasicInformation( _mainpanel.getCurrentPhylogeny(), treefile ), title ); - } - } - - void exceptionOccuredDuringOpenFile( final Exception e ) { - try { - _mainpanel.getCurrentTreePanel().setArrowCursor(); - } - catch ( final Exception ex ) { - // Do nothing. - } - JOptionPane.showMessageDialog( this, - ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ), - "Error during File|Open", - JOptionPane.ERROR_MESSAGE ); - } - - void exceptionOccuredDuringSaveAs( final Exception e ) { - try { - _mainpanel.getCurrentTreePanel().setArrowCursor(); - } - catch ( final Exception ex ) { - // Do nothing. - } - JOptionPane.showMessageDialog( this, "Exception" + e, "Error during File|SaveAs", JOptionPane.ERROR_MESSAGE ); - } - - void executeGSDI() { - if ( !isOKforSDI( false, true ) ) { - return; - } - if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) { - JOptionPane.showMessageDialog( this, - "Gene tree is not rooted.", - "Cannot execute GSDI", - JOptionPane.ERROR_MESSAGE ); - return; - } - final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy(); - gene_tree.setAllNodesToNotCollapse(); - gene_tree.recalculateNumberOfExternalDescendants( false ); - GSDI gsdi = null; - final Phylogeny species_tree = getSpeciesTree().copy(); - try { - gsdi = new GSDI( gene_tree, species_tree, false, true, true, true ); - } - catch ( final SDIException e ) { - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Error during GSDI", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final Exception e ) { - AptxUtil.unexpectedException( e ); - return; - } - gene_tree.setRerootable( false ); - gene_tree.clearHashIdToNodeMap(); - gene_tree.recalculateNumberOfExternalDescendants( true ); - _mainpanel.addPhylogenyInNewTab( gene_tree, getConfiguration(), "gene tree", null ); - getMainPanel().getControlPanel().setShowEvents( true ); - showWhole(); - final int selected = _mainpanel.getTabbedPane().getSelectedIndex(); - _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null ); - showWhole(); - _mainpanel.getTabbedPane().setSelectedIndex( selected ); - showWhole(); - _mainpanel.getCurrentTreePanel().setEdited( true ); - final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree ); - if ( gsdi.getStrippedExternalGeneTreeNodes().size() > 0 ) { - JOptionPane.showMessageDialog( this, - "Duplications: " + gsdi.getDuplicationsSum() + "\n" - + "Potential duplications: " - + gsdi.getSpeciationOrDuplicationEventsSum() + "\n" - + "Speciations: " + gsdi.getSpeciationsSum() + "\n" - + "Stripped gene tree nodes: " - + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n" - + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n" - + "Number of polytomies in species tree used: " + poly + "\n", - "GSDI successfully completed", - JOptionPane.WARNING_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, - "Duplications: " + gsdi.getDuplicationsSum() + "\n" - + "Potential duplications: " - + gsdi.getSpeciationOrDuplicationEventsSum() + "\n" - + "Speciations: " + gsdi.getSpeciationsSum() + "\n" - + "Stripped gene tree nodes: " - + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n" - + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n" - + "Number of polytomies in species tree used: " + poly + "\n", - "GSDI successfully completed", - JOptionPane.INFORMATION_MESSAGE ); - } - } - - void executeGSDIR() { - if ( !isOKforSDI( false, false ) ) { - return; - } - final int p = PhylogenyMethods.countNumberOfPolytomies( _mainpanel.getCurrentPhylogeny() ); - if ( ( p > 0 ) - && !( ( p == 1 ) && ( _mainpanel.getCurrentPhylogeny().getRoot().getNumberOfDescendants() == 3 ) ) ) { - JOptionPane.showMessageDialog( this, - "Gene tree is not completely binary", - "Cannot execute GSDI", - JOptionPane.ERROR_MESSAGE ); - return; - } - final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy(); - gene_tree.setAllNodesToNotCollapse(); - gene_tree.recalculateNumberOfExternalDescendants( false ); - GSDIR gsdir = null; - final Phylogeny species_tree = getSpeciesTree().copy(); - try { - gsdir = new GSDIR( gene_tree, species_tree, true, true, true ); - } - catch ( final SDIException e ) { - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Error during GSDIR", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final Exception e ) { - AptxUtil.unexpectedException( e ); - return; - } - final Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTree(); - result_gene_tree.setRerootable( false ); - result_gene_tree.clearHashIdToNodeMap(); - result_gene_tree.recalculateNumberOfExternalDescendants( true ); - PhylogenyMethods.orderAppearance( result_gene_tree.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME ); - _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null ); - getMainPanel().getControlPanel().setShowEvents( true ); - showWhole(); - final int selected = _mainpanel.getTabbedPane().getSelectedIndex(); - _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null ); - showWhole(); - _mainpanel.getTabbedPane().setSelectedIndex( selected ); - showWhole(); - _mainpanel.getCurrentTreePanel().setEdited( true ); - final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree ); - if ( gsdir.getStrippedExternalGeneTreeNodes().size() > 0 ) { - JOptionPane.showMessageDialog( this, - "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n" - + "Speciations: " + gsdir.getSpeciationsSum() + "\n" - + "Stripped gene tree nodes: " - + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n" - + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n" - + "Number of polytomies in species tree used: " + poly + "\n", - "GSDIR successfully completed", - JOptionPane.WARNING_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, - "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n" - + "Speciations: " + gsdir.getSpeciationsSum() + "\n" - + "Stripped gene tree nodes: " - + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n" - + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n" - + "Number of polytomies in species tree used: " + poly + "\n", - "GSDIR successfully completed", - JOptionPane.INFORMATION_MESSAGE ); - } - } - - boolean GAndSDoHaveMoreThanOneSpeciesInComman( final Phylogeny gene_tree ) { - if ( ( gene_tree == null ) || gene_tree.isEmpty() ) { - JOptionPane.showMessageDialog( this, - "Gene tree and species tree have no species in common.", - "Error during SDI", - JOptionPane.ERROR_MESSAGE ); - return false; - } - else if ( gene_tree.getNumberOfExternalNodes() < 2 ) { - JOptionPane.showMessageDialog( this, - "Gene tree and species tree have only one species in common.", - "Error during SDI", - JOptionPane.ERROR_MESSAGE ); - return false; - } - else { - return true; - } - } - - TreePanel getCurrentTreePanel() { - return getMainPanel().getCurrentTreePanel(); - } - - JMenu getHelpMenu() { - return _help_jmenu; - } - - JCheckBoxMenuItem getlabelDirectionCbmi() { - return _label_direction_cbmi; - } - - JMenuBar getMenuBarOfMainFrame() { - return _jmenubar; - } - - final Phylogeny getSpeciesTree() { - return _species_tree; - } - - void help() { - final StringBuilder sb = new StringBuilder(); - sb.append( "Display options\n" ); - sb.append( "-------------------\n" ); - sb.append( "Use the checkboxes to select types of information to display on the tree.\n\n" ); - sb.append( "Clickable tree nodes\n" ); - sb.append( "--------------------\n" ); - sb.append( "Tree nodes can be clicked, the action is determined by the 'click on node to' menu\n" ); - sb.append( "or by right clicking:\n" ); - sb.append( "o Display Node Data -- display information for a node\n" ); - sb.append( "o Collapse/Uncollapse -- collapse and uncollapse subtree from clicked node\n" ); - sb.append( "o Root/Reroot -- change tree root to clicked node\n" ); - sb.append( "o Sub/Super Tree -- toggle between subtree from clicked node and whole tree\n" ); - sb.append( "o Swap Descendants -- switch descendant on either side of clicked node\n" ); - sb.append( "o Colorize Subtree -- color a subtree\n" ); - sb.append( "o Open Sequence Web -- launch a web browser to display sequence information\n" ); - sb.append( "o Open Taxonomy Web -- launch a web browser to display taxonomy information\n" ); - sb.append( "- there may be additional choices depending on this particular setup\n\n" ); - sb.append( "Right clicking on a node always displays the information of a node.\n\n" ); - sb.append( "Zooming\n" ); - sb.append( "---------\n" ); - sb.append( "The mouse wheel and the plus and minus keys control zooming.\n" ); - sb.append( "Mouse wheel+Ctrl changes the text size.\n" ); - sb.append( "Mouse wheel+Shift controls zooming in vertical direction only.\n" ); - sb.append( "Use the buttons on the control panel to zoom the tree in and out, horizontally or vertically.\n" ); - sb.append( "The entire tree can be fitted into the window by clicking the \"F\" button, or by pressing F, Delete, or Home.\n" ); - sb.append( "The up, down, left, and right keys can be used to move the visible part (if zoomed in).\n" ); - sb.append( "Up, down, left, and right+Shift can be used to control zooming horizontally and vertically.\n" ); - sb.append( "Plus and minus keys+Ctrl change the text size; F+Ctrl, Delete+Ctrl, or Home+Ctrl resets it.\n\n" ); - sb.append( "Quick tree manipulation:\n" ); - sb.append( "------------------------\n" ); - sb.append( "Order Subtrees -- order the tree by branch length\n" ); - sb.append( "Uncollapse All -- uncollapse any and all collapsed branches\n\n" ); - sb.append( "Memory problems (Java heap space error)\n" ); - sb.append( "---------------------------------------\n" ); - sb.append( "Since the Java default memory allocation is quite small, it might by necessary (for trees\n" ); - sb.append( "with more than approximately 5000 external nodes) to increase the memory which Java can use, with\n" ); - sb.append( "the '-Xmx' Java command line option. For example:\n" ); - sb.append( "java -Xmx1024m -cp path\\to\\forester.jar org.forester.archaeopteryx.Archaeopteryx\n\n" ); - // + "General remarks\n" - // + "---------------\n" - // + - // "o The application version permits copying to the clipboard \n" - // + - // " in the \"View\"|\"View as ...\" frame (either by control-c or button press).\n" - // + - // "o Changes made to a subtree affect this subtree and its subtrees,\n" - // + " but not any of its parent tree(s).\n" - // + - // "o Archaeopteryx tries to detect whether the numerical values in a NH tree\n" - // + - // " are likely to be bootstrap values instead of branch length values.\n\n" - // + - // " Remarks regarding SDI (Speciation Duplication Inference):\n" - // + - // "o Each external node of the gene tree (in display) needs to be associated with\n" - // + - // " a species: either directly through the \"Species\" field, or the species\n" - // + - // " is part of the sequence name in the form \"XXXX_SPECIES\"\n" - // + - // " (e.g. \"ACON_DROME\" or \"ACON_DROME/123-4489\" which is also acceptable).\n" - // + - // "o A species tree for each species of the gene tree needs to be loaded with\n" - // + - // " \"SDI\"|\"Load species tree\" prior the SDI execution.\n" - // + - // "o !External nodes of the gene tree associated with species not present in\n" - // + - // " the species tree are REMOVED prior to SDI execution!\n" - // + - // "o Both the gene tree and the species tree must be completely binary.\n" - // + - // "o Duplications and speciations are a function of the position of the root.\n" - // + - // " Hence, after each manual \"Root/Reroot\"ing some duplications will be\n" - // + " incorrect and need to be inferred again\n" - // + - // " with: \"SDI\"|\"SDI (Speciation Duplication Inference)\n\n" - sb.append( "phyloXML\n" ); - sb.append( "-------------------\n" ); - sb.append( "Reference: " + Constants.PHYLOXML_REFERENCE + "\n" ); - sb.append( "Website: " + Constants.PHYLOXML_WEB_SITE + "\n" ); - sb.append( "Version: " + ForesterConstants.PHYLO_XML_VERSION + "\n" ); - sb.append( "\n" ); - sb.append( "For more information: https://sites.google.com/site/cmzmasek/home/software/archaeopteryx\n" ); - sb.append( "Email: " + Constants.AUTHOR_EMAIL + "\n\n" ); - TextFrame.instantiate( sb.toString(), "Help", _textframes ); - } - - void initializeTypeMenu( final Options options ) { - setTypeMenuToAllUnselected(); - switch ( options.getPhylogenyGraphicsType() ) { - case CONVEX: - _convex_type_cbmi.setSelected( true ); - break; - case CURVED: - _curved_type_cbmi.setSelected( true ); - break; - case EURO_STYLE: - _euro_type_cbmi.setSelected( true ); - break; - case ROUNDED: - _rounded_type_cbmi.setSelected( true ); - break; - case TRIANGULAR: - _triangular_type_cbmi.setSelected( true ); - break; - case UNROOTED: - _unrooted_type_cbmi.setSelected( true ); - break; - case CIRCULAR: - _circular_type_cbmi.setSelected( true ); - break; - default: - _rectangular_type_cbmi.setSelected( true ); - break; - } - } - - boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) { - if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) { - return false; - } - else if ( ( getSpeciesTree() == null ) || getSpeciesTree().isEmpty() ) { - JOptionPane.showMessageDialog( this, - "No species tree loaded", - "Cannot execute GSDI", - JOptionPane.ERROR_MESSAGE ); - return false; - } - else if ( species_tree_has_to_binary && !getSpeciesTree().isCompletelyBinary() ) { - JOptionPane.showMessageDialog( this, - "Species tree is not completely binary", - "Cannot execute GSDI", - JOptionPane.ERROR_MESSAGE ); - return false; - } - else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) { - JOptionPane.showMessageDialog( this, - "Gene tree is not completely binary", - "Cannot execute GSDI", - JOptionPane.ERROR_MESSAGE ); - return false; - } - else { - return true; - } - } - - boolean isSubtreeDisplayed() { - if ( getCurrentTreePanel() != null ) { - if ( getCurrentTreePanel().isCurrentTreeIsSubtree() ) { - JOptionPane - .showMessageDialog( this, - "This operation can only be performed on a complete tree, not on the currently displayed sub-tree only.", - "Operation can not be exectuted on a sub-tree", - JOptionPane.WARNING_MESSAGE ); - return true; - } - } - return false; - } - - void midpointRoot() { - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().midpointRoot(); - } - } - - void readPhylogeniesFromWebservice( final int i ) { - final UrlTreeReader reader = new UrlTreeReader( this, i ); - new Thread( reader ).start(); - } - - void removeAllTextFrames() { - for( final TextFrame tf : _textframes ) { - if ( tf != null ) { - tf.close(); - } - } - _textframes.clear(); - } - - void setConfiguration( final Configuration configuration ) { - _configuration = configuration; - } - - void setInferenceManager( final InferenceManager i ) { - _inference_manager = i; - } - - void setOptions( final Options options ) { - _options = options; - } - - void setSelectedTypeInTypeMenu( final PHYLOGENY_GRAPHICS_TYPE type ) { - setTypeMenuToAllUnselected(); - switch ( type ) { - case CIRCULAR: - _circular_type_cbmi.setSelected( true ); - break; - case CONVEX: - _convex_type_cbmi.setSelected( true ); - break; - case CURVED: - _curved_type_cbmi.setSelected( true ); - break; - case EURO_STYLE: - _euro_type_cbmi.setSelected( true ); - break; - case ROUNDED: - _rounded_type_cbmi.setSelected( true ); - break; - case RECTANGULAR: - _rectangular_type_cbmi.setSelected( true ); - break; - case TRIANGULAR: - _triangular_type_cbmi.setSelected( true ); - break; - case UNROOTED: - _unrooted_type_cbmi.setSelected( true ); - break; - default: - throw new IllegalArgumentException( "unknown type: " + type ); - } - } - - final void setSpeciesTree( final Phylogeny species_tree ) { - _species_tree = species_tree; - } - - void setTypeMenuToAllUnselected() { - _convex_type_cbmi.setSelected( false ); - _curved_type_cbmi.setSelected( false ); - _euro_type_cbmi.setSelected( false ); - _rounded_type_cbmi.setSelected( false ); - _triangular_type_cbmi.setSelected( false ); - _rectangular_type_cbmi.setSelected( false ); - _unrooted_type_cbmi.setSelected( false ); - _circular_type_cbmi.setSelected( false ); - } - - void switchColors() { - final TreeColorSet colorset = _mainpanel.getTreeColorSet(); - final ColorSchemeChooser csc = new ColorSchemeChooser( getMainPanel(), colorset ); - csc.setVisible( true ); - } - - void taxColor() { - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().taxColor(); - } - } - - void typeChanged( final Object o ) { - updateTypeCheckboxes( getOptions(), o ); - updateOptions( getOptions() ); - if ( getCurrentTreePanel() != null ) { - final PHYLOGENY_GRAPHICS_TYPE previous_type = getCurrentTreePanel().getPhylogenyGraphicsType(); - final PHYLOGENY_GRAPHICS_TYPE new_type = getOptions().getPhylogenyGraphicsType(); - if ( ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) - || ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) - || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) - || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) ) { - getCurrentTreePanel().getControlPanel().showWhole(); - } - if ( getCurrentTreePanel().isPhyHasBranchLengths() && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) { - getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( true ); - } - else { - getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( false ); - } - getCurrentTreePanel().setPhylogenyGraphicsType( getOptions().getPhylogenyGraphicsType() ); - updateScreenTextAntialias( getMainPanel().getTreePanels() ); - if ( getCurrentTreePanel().getControlPanel().getDynamicallyHideData() != null ) { - if ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) { - getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( false ); - } - else { - getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( true ); - } - } - } - } - - void updateOptions( final Options options ) { - options.setAntialiasScreen( ( _screen_antialias_cbmi != null ) && _screen_antialias_cbmi.isSelected() ); - options.setBackgroundColorGradient( ( _background_gradient_cbmi != null ) - && _background_gradient_cbmi.isSelected() ); - options.setShowDomainLabels( ( _show_domain_labels != null ) && _show_domain_labels.isSelected() ); - options.setShowAnnotationRefSource( ( _show_annotation_ref_source != null ) - && _show_annotation_ref_source.isSelected() ); - options.setAbbreviateScientificTaxonNames( ( _abbreviate_scientific_names != null ) - && _abbreviate_scientific_names.isSelected() ); - options.setColorLabelsSameAsParentBranch( ( _color_labels_same_as_parent_branch != null ) - && _color_labels_same_as_parent_branch.isSelected() ); - options.setShowDefaultNodeShapesInternal( ( _show_default_node_shapes_internal_cbmi != null ) - && _show_default_node_shapes_internal_cbmi.isSelected() ); - options.setShowDefaultNodeShapesExternal( ( _show_default_node_shapes_external_cbmi != null ) - && _show_default_node_shapes_external_cbmi.isSelected() ); - if ( ( _non_lined_up_cladograms_rbmi != null ) && ( _non_lined_up_cladograms_rbmi.isSelected() ) ) { - options.setCladogramType( CLADOGRAM_TYPE.NON_LINED_UP ); - } - else if ( ( _uniform_cladograms_rbmi != null ) && ( _uniform_cladograms_rbmi.isSelected() ) ) { - options.setCladogramType( CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP ); - } - else if ( ( _ext_node_dependent_cladogram_rbmi != null ) && ( _ext_node_dependent_cladogram_rbmi.isSelected() ) ) { - options.setCladogramType( CLADOGRAM_TYPE.EXT_NODE_SUM_DEP ); - } - options.setSearchCaseSensitive( ( _search_case_senstive_cbmi != null ) - && _search_case_senstive_cbmi.isSelected() ); - if ( ( _show_scale_cbmi != null ) && _show_scale_cbmi.isEnabled() ) { - options.setShowScale( _show_scale_cbmi.isSelected() ); - } - if ( _label_direction_cbmi != null ) { - if ( _label_direction_cbmi.isSelected() ) { - options.setNodeLabelDirection( NODE_LABEL_DIRECTION.RADIAL ); - } - else { - options.setNodeLabelDirection( NODE_LABEL_DIRECTION.HORIZONTAL ); - } - } - options.setShowOverview( ( _show_overview_cbmi != null ) && _show_overview_cbmi.isSelected() ); - options.setShowConfidenceStddev( ( _show_confidence_stddev_cbmi != null ) - && _show_confidence_stddev_cbmi.isSelected() ); - if ( ( _show_branch_length_values_cbmi != null ) && _show_branch_length_values_cbmi.isEnabled() ) { - options.setShowBranchLengthValues( _show_branch_length_values_cbmi.isSelected() ); - } - if ( ( _color_by_taxonomic_group_cbmi != null ) && _color_by_taxonomic_group_cbmi.isEnabled() ) { - options.setColorByTaxonomicGroup( _color_by_taxonomic_group_cbmi.isSelected() ); - } - options.setPrintUsingActualSize( ( _print_using_actual_size_cbmi != null ) - && ( _print_using_actual_size_cbmi.isSelected() ) ); - options.setGraphicsExportUsingActualSize( ( _graphics_export_using_actual_size_cbmi != null ) - && ( _graphics_export_using_actual_size_cbmi.isSelected() ) ); - options.setAntialiasPrint( ( _antialias_print_cbmi != null ) && _antialias_print_cbmi.isSelected() ); - if ( ( _use_brackets_for_conf_in_nh_export_cbmi != null ) - && _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) { - options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ); - } - else if ( ( _use_internal_names_for_conf_in_nh_export_cbmi != null ) - && _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) { - options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ); - } - else { - options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE ); - } - options.setPrintBlackAndWhite( ( _print_black_and_white_cbmi != null ) - && _print_black_and_white_cbmi.isSelected() ); - options.setInternalNumberAreConfidenceForNhParsing( ( _internal_number_are_confidence_for_nh_parsing_cbmi != null ) - && _internal_number_are_confidence_for_nh_parsing_cbmi.isSelected() ); - if ( ( _extract_taxonomy_pfam_strict_rbmi != null ) && _extract_taxonomy_pfam_strict_rbmi.isSelected() ) { - options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ); - } - else if ( ( _extract_taxonomy_pfam_relaxed_rbmi != null ) && _extract_taxonomy_pfam_relaxed_rbmi.isSelected() ) { - options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED ); - } - else if ( ( _extract_taxonomy_agressive_rbmi != null ) && _extract_taxonomy_agressive_rbmi.isSelected() ) { - options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE ); - } - else if ( ( _extract_taxonomy_no_rbmi != null ) && _extract_taxonomy_no_rbmi.isSelected() ) { - options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.NO ); - } - options.setReplaceUnderscoresInNhParsing( ( _replace_underscores_cbmi != null ) - && _replace_underscores_cbmi.isSelected() ); - options.setAllowErrorsInDistanceToParent( ( _allow_errors_in_distance_to_parent_cbmi != null ) - && _allow_errors_in_distance_to_parent_cbmi.isSelected() ); - options.setMatchWholeTermsOnly( ( _search_whole_words_only_cbmi != null ) - && _search_whole_words_only_cbmi.isSelected() ); - options.setInverseSearchResult( ( _inverse_search_result_cbmi != null ) - && _inverse_search_result_cbmi.isSelected() ); - if ( _graphics_export_visible_only_cbmi != null ) { - options.setGraphicsExportVisibleOnly( _graphics_export_visible_only_cbmi.isSelected() ); - if ( _graphics_export_visible_only_cbmi.isSelected() && ( _graphics_export_using_actual_size_cbmi != null ) ) { - _graphics_export_using_actual_size_cbmi.setSelected( true ); - _graphics_export_using_actual_size_cbmi.setEnabled( false ); - } - else { - _graphics_export_using_actual_size_cbmi.setEnabled( true ); - } - } - if ( ( _rectangular_type_cbmi != null ) && _rectangular_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); - } - else if ( ( _triangular_type_cbmi != null ) && _triangular_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR ); - } - else if ( ( _curved_type_cbmi != null ) && _curved_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED ); - } - else if ( ( _convex_type_cbmi != null ) && _convex_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX ); - } - else if ( ( _euro_type_cbmi != null ) && _euro_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ); - } - else if ( ( _rounded_type_cbmi != null ) && _rounded_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED ); - } - else if ( ( _unrooted_type_cbmi != null ) && _unrooted_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED ); - } - else if ( ( _circular_type_cbmi != null ) && _circular_type_cbmi.isSelected() ) { - options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ); - } - } - - void updateTypeCheckboxes( final Options options, final Object o ) { - setTypeMenuToAllUnselected(); - ( ( JCheckBoxMenuItem ) o ).setSelected( true ); - } - - void viewAsNexus() { - if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { - String title = "Nexus"; - if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { - title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; - } - showTextFrame( _mainpanel.getCurrentPhylogeny().toNexus( getOptions().getNhConversionSupportValueStyle() ), - title ); - } - } - - void viewAsNH() { - if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { - String title = "New Hampshire"; - if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { - title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; - } - showTextFrame( _mainpanel.getCurrentPhylogeny().toNewHampshire( getOptions() - .getNhConversionSupportValueStyle() ), - title ); - } - } - - void viewAsXML() { - if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { - String title = "phyloXML"; - if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { - title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; - } - showTextFrame( _mainpanel.getCurrentPhylogeny().toPhyloXML( 0 ), title ); - } - } - - private void annotateSequences() { - if ( getCurrentTreePanel() != null ) { - final Set nodes = getCurrentTreePanel().getFoundNodes0(); - if ( ( nodes == null ) || nodes.isEmpty() ) { - JOptionPane - .showMessageDialog( this, - "Need to select nodes, either via direct selection or via the \"Search\" function", - "No nodes selected for annotation", - JOptionPane.ERROR_MESSAGE ); - return; - } - final Phylogeny phy = getMainPanel().getCurrentPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final JTextField ref_field = new JTextField( 10 ); - final JTextField desc_filed = new JTextField( 20 ); - ref_field.setText( ForesterUtil.isEmpty( getPreviousNodeAnnotationReference() ) ? "" - : getPreviousNodeAnnotationReference() ); - final JPanel my_panel = new JPanel(); - my_panel.add( new JLabel( "Reference " ) ); - my_panel.add( ref_field ); - my_panel.add( Box.createHorizontalStrut( 15 ) ); - my_panel.add( new JLabel( "Description " ) ); - my_panel.add( desc_filed ); - final int result = JOptionPane.showConfirmDialog( null, - my_panel, - "Enter the sequence annotation(s) for the " - + nodes.size() + " selected nodes", - JOptionPane.OK_CANCEL_OPTION ); - if ( result == JOptionPane.OK_OPTION ) { - String ref = ref_field.getText(); - String desc = desc_filed.getText(); - if ( !ForesterUtil.isEmpty( ref ) ) { - ref = ref.trim(); - ref = ref.replaceAll( "\\s+", " " ); - if ( ( ref.indexOf( ':' ) < 1 ) || ( ref.indexOf( ':' ) > ref.length() - 2 ) - || ( ref.length() < 3 ) ) { - JOptionPane.showMessageDialog( this, - "Reference needs to be in the form of \"GO:1234567\"", - "Illegal Format for Annotation Reference", - JOptionPane.ERROR_MESSAGE ); - return; - } - } - if ( ref != null ) { - setPreviousNodeAnnotationReference( ref ); - } - if ( desc != null ) { - desc = desc.trim(); - desc = desc.replaceAll( "\\s+", " " ); - } - if ( !ForesterUtil.isEmpty( ref ) || !ForesterUtil.isEmpty( desc ) ) { - for( final Long id : nodes ) { - final PhylogenyNode n = phy.getNode( id ); - ForesterUtil.ensurePresenceOfSequence( n ); - final Annotation ann = ForesterUtil.isEmpty( ref ) ? new Annotation() - : new Annotation( ref ); - if ( !ForesterUtil.isEmpty( desc ) ) { - ann.setDesc( desc ); - } - n.getNodeData().getSequence().addAnnotation( ann ); - } - } - getMainPanel().getControlPanel().showAnnotations(); - } - } - } - } - - private void chooseFont() { - final FontChooser fc = new FontChooser(); - fc.setFont( getMainPanel().getTreeFontSet().getLargeFont() ); - fc.showDialog( this, "Select the Base Font" ); - getMainPanel().getTreeFontSet().setBaseFont( fc.getFont() ); - } - - private void chooseMinimalConfidence() { - final String s = ( String ) JOptionPane - .showInputDialog( this, - "Please enter the minimum for confidence values to be displayed.\n" - + "[current value: " + getOptions().getMinConfidenceValue() + "]\n", - "Minimal Confidence Value", - JOptionPane.QUESTION_MESSAGE, - null, - null, - getOptions().getMinConfidenceValue() ); - if ( !ForesterUtil.isEmpty( s ) ) { - boolean success = true; - double m = 0.0; - final String m_str = s.trim(); - if ( !ForesterUtil.isEmpty( m_str ) ) { - try { - m = Double.parseDouble( m_str ); - } - catch ( final Exception ex ) { - success = false; - } - } - else { - success = false; - } - if ( success && ( m >= 0.0 ) ) { - getOptions().setMinConfidenceValue( m ); - } - } - } - - private void doUpdateProcessMenu() { - if ( _process_pool.size() > 0 ) { - if ( _process_menu == null ) { - _process_menu = createMenu( "", getConfiguration() ); - _process_menu.setForeground( Color.RED ); - } - _process_menu.removeAll(); - final String text = "processes running: " + _process_pool.size(); - _process_menu.setText( text ); - _jmenubar.add( _process_menu ); - for( int i = 0; i < _process_pool.size(); ++i ) { - final ProcessRunning p = _process_pool.getProcessByIndex( i ); - _process_menu.add( customizeJMenuItem( new JMenuItem( p.getName() + " [" + p.getStart() + "]" ) ) ); - } - } - else { - if ( _process_menu != null ) { - _process_menu.removeAll(); - _jmenubar.remove( _process_menu ); - } - } - _jmenubar.validate(); - _jmenubar.repaint(); - repaint(); - } - - private String getPreviousNodeAnnotationReference() { - return _previous_node_annotation_ref; - } - - private void removeBranchColors() { - if ( getMainPanel().getCurrentPhylogeny() != null ) { - AptxUtil.removeBranchColors( getMainPanel().getCurrentPhylogeny() ); - } - } - - private void removeVisualStyles() { - if ( getMainPanel().getCurrentPhylogeny() != null ) { - AptxUtil.removeVisualStyles( getMainPanel().getCurrentPhylogeny() ); - } - } - - private void setPreviousNodeAnnotationReference( final String previous_node_annotation_ref ) { - _previous_node_annotation_ref = previous_node_annotation_ref; - } - - /** - * Display the about box. - */ - static void about() { - final StringBuffer about = new StringBuffer( "Archaeopteryx\nVersion " + Constants.VERSION + "\n" ); - about.append( "Copyright (C) 2013 Christian M. Zmasek\n" ); - about.append( "All Rights Reserved\n" ); - about.append( "License: GNU Lesser General Public License (LGPL)\n" ); - about.append( "Last modified: " + Constants.PRG_DATE + "\n" ); - about.append( "Based on: " + ForesterUtil.getForesterLibraryInformation() + "\n" ); - about.append( "phyloXML version : " + ForesterConstants.PHYLO_XML_VERSION + "\n" ); - about.append( "phyloXML location: " + ForesterConstants.PHYLO_XML_LOCATION + "\n" ); - if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) { - about.append( "[your Java version: " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]\n" ); - } - if ( !ForesterUtil.isEmpty( ForesterUtil.OS_NAME ) && !ForesterUtil.isEmpty( ForesterUtil.OS_ARCH ) - && !ForesterUtil.isEmpty( ForesterUtil.OS_VERSION ) ) { - about.append( "[your OS: " + ForesterUtil.OS_NAME + " " + ForesterUtil.OS_ARCH + " " - + ForesterUtil.OS_VERSION + "]\n" ); - } - final Runtime rt = java.lang.Runtime.getRuntime(); - final long free_memory = rt.freeMemory() / 1000000; - final long total_memory = rt.totalMemory() / 1000000; - about.append( "[free memory: " + free_memory + "MB, total memory: " + total_memory + "MB]\n" ); - about.append( "[locale: " + Locale.getDefault() + "]\n" ); - about.append( "References:\n" ); - about.append( Constants.PHYLOXML_REFERENCE_SHORT + "\n" ); - about.append( "For more information & download:\n" ); - about.append( Constants.APTX_WEB_SITE + "\n" ); - about.append( "Comments: " + Constants.AUTHOR_EMAIL ); - JOptionPane.showMessageDialog( null, about, Constants.PRG_NAME, JOptionPane.PLAIN_MESSAGE ); - } - - static void chooseNodeSize( final Options options, final Component parent ) { - final String s = ( String ) JOptionPane.showInputDialog( parent, - "Please enter the default size for node shapes.\n" - + "[current value: " - + options.getDefaultNodeShapeSize() + "]\n", - "Node Shape Size", - JOptionPane.QUESTION_MESSAGE, - null, - null, - options.getDefaultNodeShapeSize() ); - if ( !ForesterUtil.isEmpty( s ) ) { - boolean success = true; - double m = 0.0; - final String m_str = s.trim(); - if ( !ForesterUtil.isEmpty( m_str ) ) { - try { - m = Double.parseDouble( m_str ); - } - catch ( final Exception ex ) { - success = false; - } - } - else { - success = false; - } - if ( success && ( m >= 0.0 ) ) { - final short size = ForesterUtil.roundToShort( m ); - if ( size >= 0.0 ) { - options.setDefaultNodeShapeSize( size ); - } - } - } - } - - static String createCurrentFontDesc( final TreeFontSet tree_font_set ) { - return tree_font_set.getLargeFont().getFamily() + " " + tree_font_set.getLargeFont().getSize(); - } - - static JMenu createMenu( final String title, final Configuration conf ) { - final JMenu jmenu = new JMenu( title ); - if ( !conf.isUseNativeUI() ) { - jmenu.setFont( MainFrame.menu_font ); - jmenu.setBackground( conf.getGuiMenuBackgroundColor() ); - jmenu.setForeground( conf.getGuiMenuTextColor() ); - } - return jmenu; - } - - static JMenuItem customizeMenuItemAsLabel( final JMenuItem label, final Configuration configuration ) { - label.setFont( MainFrame.menu_font.deriveFont( Font.BOLD ) ); - if ( !configuration.isUseNativeUI() ) { - label.setBackground( configuration.getGuiMenuBackgroundColor() ); - label.setForeground( configuration.getGuiMenuTextColor() ); - label.setOpaque( true ); - } - label.setSelected( false ); - label.setEnabled( false ); - return label; - } - - static void cycleNodeFill( final Options op, final TreePanel tree_panel ) { - switch ( op.getDefaultNodeFill() ) { - case GRADIENT: - op.setDefaultNodeFill( NodeFill.SOLID ); - break; - case NONE: - op.setDefaultNodeFill( NodeFill.GRADIENT ); - break; - case SOLID: - op.setDefaultNodeFill( NodeFill.NONE ); - break; - default: - throw new RuntimeException( "unknown fill: " + op.getDefaultNodeFill() ); - } - } - - static void cycleNodeShape( final Options op, final TreePanel tree_panel ) { - switch ( op.getDefaultNodeShape() ) { - case CIRCLE: - op.setDefaultNodeShape( NodeShape.RECTANGLE ); - break; - case RECTANGLE: - op.setDefaultNodeShape( NodeShape.CIRCLE ); - break; - default: - throw new RuntimeException( "unknown shape: " + op.getDefaultNodeShape() ); - } - } - - static void cycleOverview( final Options op, final TreePanel tree_panel ) { - switch ( op.getOvPlacement() ) { - case LOWER_LEFT: - op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_LEFT ); - break; - case LOWER_RIGHT: - op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_LEFT ); - break; - case UPPER_LEFT: - op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_RIGHT ); - break; - case UPPER_RIGHT: - op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_RIGHT ); - break; - default: - throw new RuntimeException( "unknown placement: " + op.getOvPlacement() ); - } - if ( tree_panel != null ) { - tree_panel.updateOvSettings(); - } - } - - static void setCycleNodeFillMenuItem( final JMenuItem mi, final Options options ) { - if ( ( options != null ) && ( options.getDefaultNodeFill() != null ) ) { - mi.setText( "Cycle Node Shape Fill Type... (current: " - + options.getDefaultNodeFill().toString().toLowerCase() + ")" ); - } - else { - mi.setText( "Cycle Node Shape Fill Type..." ); - } - } - - static void setCycleNodeShapeMenuItem( final JMenuItem mi, final Options options ) { - if ( ( options != null ) && ( options.getDefaultNodeShape() != null ) ) { - mi.setText( "Cycle Node Shape Fill Type... (current: " - + options.getDefaultNodeShape().toString().toLowerCase() + ")" ); - } - else { - mi.setText( "Cycle Node Shape Fill Type..." ); - } - } - - static void setOvPlacementColorChooseMenuItem( final JMenuItem mi, final Options options ) { - if ( ( options != null ) && ( options.getOvPlacement() != null ) ) { - mi.setText( "Cycle Overview Placement... (current: " + options.getOvPlacement() + ")" ); - } - else { - mi.setText( "Cycle Overview Placement..." ); - } - } - - static void setTextColorChooseMenuItem( final JMenuItem mi, final TreePanel tree_panel ) { - if ( ( tree_panel != null ) && ( tree_panel.getTreeColorSet() != null ) ) { - mi.setText( "Select Color Scheme... (current: " + tree_panel.getTreeColorSet().getCurrentColorSchemeName() - + ")" ); - } - else { - mi.setText( "Select Color Scheme..." ); - } - } - - static void setTextForFontChooserMenuItem( final JMenuItem mi, final String font_desc ) { - mi.setText( "Select Default Font... (current: " + font_desc + ")" ); - } - - static void setTextMinSupportMenuItem( final JMenuItem mi, final Options options, final TreePanel current_tree_panel ) { - if ( ( current_tree_panel == null ) || ( current_tree_panel.getPhylogeny() == null ) ) { - mi.setEnabled( true ); - } - else if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( current_tree_panel.getPhylogeny() ) ) { - mi.setEnabled( true ); - } - else { - mi.setEnabled( false ); - } - mi.setText( "Enter Min Confidence Value... (current: " + options.getMinConfidenceValue() + ")" ); - } - - static void setTextNodeSizeMenuItem( final JMenuItem mi, final Options options ) { - mi.setText( "Enter Default Node Shape Size... (current: " + options.getDefaultNodeShapeSize() + ")" ); - } - - static void updateOptionsMenuDependingOnPhylogenyType( final MainPanel main_panel, - final JCheckBoxMenuItem scale, - final JCheckBoxMenuItem branch_lengths, - final JRadioButtonMenuItem non_lined_up, - final JRadioButtonMenuItem uniform_clado, - final JRadioButtonMenuItem nonuniform_clado, - final JCheckBoxMenuItem label_direction_cbmi ) { - final TreePanel tree_panel = main_panel.getCurrentTreePanel(); - final ControlPanel control = main_panel.getControlPanel(); - final Options options = main_panel.getOptions(); - scale.setSelected( options.isShowScale() ); - branch_lengths.setSelected( options.isShowBranchLengthValues() ); - // non_lined_up.setSelected( options.isNonLinedUpCladogram() ); - if ( ( tree_panel != null ) && ( !tree_panel.isPhyHasBranchLengths() ) ) { - scale.setSelected( false ); - scale.setEnabled( false ); - branch_lengths.setSelected( false ); - branch_lengths.setEnabled( false ); - } - else if ( ( tree_panel != null ) && !control.isDrawPhylogram() ) { - scale.setSelected( false ); - scale.setEnabled( false ); - branch_lengths.setEnabled( true ); - } - else { - scale.setEnabled( true ); - branch_lengths.setEnabled( true ); - } - if ( ( tree_panel != null ) - && ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) - && ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) && ( tree_panel - .getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) ) ) { - branch_lengths.setSelected( false ); - branch_lengths.setEnabled( false ); - } - if ( tree_panel != null ) { - if ( ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) - || ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) { - non_lined_up.setEnabled( false ); - uniform_clado.setEnabled( false ); - nonuniform_clado.setEnabled( false ); - } - else { - non_lined_up.setEnabled( true ); - uniform_clado.setEnabled( true ); - nonuniform_clado.setEnabled( true ); - } - } - else { - if ( ( tree_panel != null ) - && ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) && ( tree_panel - .getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) ) ) { - branch_lengths.setSelected( false ); - branch_lengths.setEnabled( false ); - } - if ( ( tree_panel != null ) - && ( ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) || ( tree_panel - .getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) ) { - non_lined_up.setEnabled( false ); - } - else { - // non_lined_up.setSelected( options.isNonLinedUpCladogram() ); - non_lined_up.setEnabled( true ); - } - } - label_direction_cbmi.setEnabled( true ); - if ( tree_panel != null ) { - if ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) - && ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) { - label_direction_cbmi.setEnabled( false ); - } - if ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) { - scale.setSelected( false ); - scale.setEnabled( false ); - } - } - } - - static void updateScreenTextAntialias( final List treepanels ) { - for( final TreePanel tree_panel : treepanels ) { - tree_panel.setTextAntialias(); - } - } -} +// $Id: +// FORESTER -- software libraries and applications +// for evolutionary biology research and applications. +// +// Copyright (C) 2008-2010 Christian M. Zmasek +// All rights reserved +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +// +// Contact: phylosoft @ gmail . com +// WWW: https://sites.google.com/site/cmzmasek/home/software/forester + +package org.forester.archaeopteryx; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.NoSuchElementException; +import java.util.Set; + +import javax.swing.Box; +import javax.swing.JApplet; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; + +import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE; +import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION; +import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE; +import org.forester.archaeopteryx.tools.InferenceManager; +import org.forester.archaeopteryx.tools.ProcessPool; +import org.forester.archaeopteryx.tools.ProcessRunning; +import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION; +import org.forester.phylogeny.Phylogeny; +import org.forester.phylogeny.PhylogenyMethods; +import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY; +import org.forester.phylogeny.PhylogenyNode; +import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE; +import org.forester.phylogeny.data.Annotation; +import org.forester.phylogeny.data.NodeVisualData.NodeFill; +import org.forester.phylogeny.data.NodeVisualData.NodeShape; +import org.forester.sdi.GSDI; +import org.forester.sdi.GSDIR; +import org.forester.sdi.SDIException; +import org.forester.util.ForesterConstants; +import org.forester.util.ForesterUtil; + +public abstract class MainFrame extends JFrame implements ActionListener { + + static final String USE_MOUSEWHEEL_SHIFT_TO_ROTATE = "In this display type, use mousewheel + Shift to rotate [or A and S]"; + static final String PHYLOXML_REF_TOOL_TIP = Constants.PHYLOXML_REFERENCE; //TODO //FIXME + static final String APTX_REF_TOOL_TIP = Constants.APTX_REFERENCE; + private static final long serialVersionUID = 3655000897845508358L; + final static Font menu_font = new Font( Configuration.getDefaultFontFamilyName(), + Font.PLAIN, + 10 ); + static final String TYPE_MENU_HEADER = "Type"; + static final String RECTANGULAR_TYPE_CBMI_LABEL = "Rectangular"; + static final String EURO_TYPE_CBMI_LABEL = "Euro Type"; + static final String CURVED_TYPE_CBMI_LABEL = "Curved"; + static final String TRIANGULAR_TYPE_CBMI_LABEL = "Triangular"; + static final String CONVEX_TYPE_CBMI_LABEL = "Convex"; + static final String ROUNDED_TYPE_CBMI_LABEL = "Rounded"; + static final String UNROOTED_TYPE_CBMI_LABEL = "Unrooted (alpha)"; //TODO + static final String CIRCULAR_TYPE_CBMI_LABEL = "Circular (alpha)"; //TODO + static final String OPTIONS_HEADER = "Options"; + static final String SEARCH_SUBHEADER = "Search:"; + static final String DISPLAY_SUBHEADER = "Display:"; + static final String SEARCH_TERMS_ONLY_LABEL = "Match Complete Terms Only"; + static final String SEARCH_CASE_SENSITIVE_LABEL = "Case Sensitive"; + static final String INVERSE_SEARCH_RESULT_LABEL = "Negate Result"; + static final String DISPLAY_BRANCH_LENGTH_VALUES_LABEL = "Branch Length Values"; + static final String COLOR_BY_TAXONOMIC_GROUP = "Colorize by Taxonomic Group"; + static final String DISPLAY_SCALE_LABEL = "Scale"; + static final String NON_LINED_UP_CLADOGRAMS_LABEL = "Non-Lined Up Cladograms"; + static final String UNIFORM_CLADOGRAMS_LABEL = "Total Node Sum Dependent Cladograms"; + static final String LABEL_DIRECTION_LABEL = "Radial Labels"; + static final String LABEL_DIRECTION_TIP = "To use radial node labels in radial and unrooted display types"; + static final String SCREEN_ANTIALIAS_LABEL = "Antialias"; + static final String COLOR_LABELS_LABEL = "Colorize Labels Same as Parent Branch"; + static final String BG_GRAD_LABEL = "Background Color Gradient"; + static final String DISPLAY_NODE_BOXES_LABEL_EXT = "External Node Shapes"; + static final String DISPLAY_NODE_BOXES_LABEL_INT = "Internal Node Shapes"; + static final String SHOW_OVERVIEW_LABEL = "Overview"; + static final String FONT_SIZE_MENU_LABEL = "Font Size"; + static final String NONUNIFORM_CLADOGRAMS_LABEL = "External Node Sum Dependent Cladograms"; + static final String SHOW_DOMAIN_LABELS_LABEL = "Domain Labels"; + static final String SHOW_ANN_REF_SOURCE_LABEL = "Seq Annotation Ref Sources"; + static final String COLOR_LABELS_TIP = "To use parent branch colors for node labels as well, need to turn off taxonomy dependent colorization and turn on branch colorization for this to become apparent"; + static final String ABBREV_SN_LABEL = "Abbreviate Scientific Taxonomic Names"; + static final String TAXONOMY_COLORIZE_NODE_SHAPES_LABEL = "Colorize Node Shapes According to Taxonomy"; + static final String CYCLE_NODE_SHAPE_LABEL = "Cycle Node Shapes"; + static final String CYCLE_NODE_FILL_LABEL = "Cycle Node Fill Type"; + static final String CHOOSE_NODE_SIZE_LABEL = "Choose Node Shape Size"; + static final String SHOW_CONF_STDDEV_LABEL = "Confidence Standard Deviations"; + static final String USE_BRACKETS_FOR_CONF_IN_NH_LABEL = "Use Brackets for Confidence Values"; + static final String USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL = "Use Internal Node Names for Confidence Values"; + static final String SHOW_BASIC_TREE_INFORMATION_LABEL = "Basic Tree Information"; + JMenuBar _jmenubar; + JMenu _file_jmenu; + JMenu _tools_menu; + JMenu _view_jmenu; + JMenu _options_jmenu; + JMenu _font_size_menu; + JMenu _help_jmenu; + JMenuItem[] _load_phylogeny_from_webservice_menu_items; + // Analysis menu + JMenu _analysis_menu; + JMenuItem _load_species_tree_item; + JMenuItem _gsdi_item; + JMenuItem _gsdir_item; + JMenuItem _lineage_inference; + // file menu: + JMenuItem _open_item; + JMenuItem _open_url_item; + JMenuItem _save_item; + JMenuItem _save_all_item; + JMenuItem _close_item; + JMenuItem _exit_item; + JMenuItem _new_item; + // tools menu: + JMenuItem _midpoint_root_item; + JMenuItem _taxcolor_item; + JMenuItem _confcolor_item; + JMenuItem _color_rank_jmi; + JMenuItem _collapse_species_specific_subtrees; + JMenuItem _collapse_below_threshold; //TODO implememt me + JMenuItem _obtain_detailed_taxonomic_information_jmi; + JMenuItem _obtain_detailed_taxonomic_information_deleting_jmi; + JMenuItem _obtain_seq_information_jmi; + JMenuItem _move_node_names_to_tax_sn_jmi; + JMenuItem _move_node_names_to_seq_names_jmi; + JMenuItem _extract_tax_code_from_node_names_jmi; + JMenuItem _annotate_item; + JMenuItem _remove_branch_color_item; + JMenuItem _remove_visual_styles_item; + // font size menu: + JMenuItem _super_tiny_fonts_item; + JMenuItem _tiny_fonts_item; + JMenuItem _small_fonts_item; + JMenuItem _medium_fonts_item; + JMenuItem _large_fonts_item; + // options menu: + // _ screen and print + JMenuItem _choose_font_mi; + JMenuItem _switch_colors_mi; + JCheckBoxMenuItem _label_direction_cbmi; + // _ screen display + JCheckBoxMenuItem _screen_antialias_cbmi; + JCheckBoxMenuItem _background_gradient_cbmi; + JRadioButtonMenuItem _non_lined_up_cladograms_rbmi; + JRadioButtonMenuItem _uniform_cladograms_rbmi; + JRadioButtonMenuItem _ext_node_dependent_cladogram_rbmi; + JCheckBoxMenuItem _show_branch_length_values_cbmi; + JCheckBoxMenuItem _color_by_taxonomic_group_cbmi; + JCheckBoxMenuItem _show_scale_cbmi; //TODO fix me + JCheckBoxMenuItem _show_overview_cbmi; + JCheckBoxMenuItem _show_domain_labels; + JCheckBoxMenuItem _show_annotation_ref_source; + JCheckBoxMenuItem _abbreviate_scientific_names; + JCheckBoxMenuItem _color_labels_same_as_parent_branch; + JMenuItem _overview_placment_mi; + JMenuItem _choose_minimal_confidence_mi; + JCheckBoxMenuItem _show_default_node_shapes_internal_cbmi; + JCheckBoxMenuItem _show_default_node_shapes_external_cbmi; + JMenuItem _cycle_node_shape_mi; + JMenuItem _cycle_node_fill_mi; + JMenuItem _choose_node_size_mi; + JCheckBoxMenuItem _show_confidence_stddev_cbmi; + // _ print + JCheckBoxMenuItem _graphics_export_visible_only_cbmi; + JCheckBoxMenuItem _antialias_print_cbmi; + JCheckBoxMenuItem _print_black_and_white_cbmi; + JCheckBoxMenuItem _print_using_actual_size_cbmi; + JCheckBoxMenuItem _graphics_export_using_actual_size_cbmi; + JMenuItem _print_size_mi; + JMenuItem _choose_pdf_width_mi; + // _ parsing + JCheckBoxMenuItem _internal_number_are_confidence_for_nh_parsing_cbmi; + JRadioButtonMenuItem _extract_taxonomy_no_rbmi; + JRadioButtonMenuItem _extract_taxonomy_agressive_rbmi; + JRadioButtonMenuItem _extract_taxonomy_pfam_strict_rbmi; + JRadioButtonMenuItem _extract_taxonomy_pfam_relaxed_rbmi; + JCheckBoxMenuItem _replace_underscores_cbmi; + JCheckBoxMenuItem _allow_errors_in_distance_to_parent_cbmi; + JCheckBoxMenuItem _use_brackets_for_conf_in_nh_export_cbmi; + JCheckBoxMenuItem _use_internal_names_for_conf_in_nh_export_cbmi; + // _ search + JCheckBoxMenuItem _search_case_senstive_cbmi; + JCheckBoxMenuItem _search_whole_words_only_cbmi; + JCheckBoxMenuItem _inverse_search_result_cbmi; + // type menu: + JMenu _type_menu; + JCheckBoxMenuItem _rectangular_type_cbmi; + JCheckBoxMenuItem _triangular_type_cbmi; + JCheckBoxMenuItem _curved_type_cbmi; + JCheckBoxMenuItem _convex_type_cbmi; + JCheckBoxMenuItem _euro_type_cbmi; + JCheckBoxMenuItem _rounded_type_cbmi; + JCheckBoxMenuItem _unrooted_type_cbmi; + JCheckBoxMenuItem _circular_type_cbmi; + // view as text menu: + JMenuItem _view_as_NH_item; + JMenuItem _view_as_XML_item; + JMenuItem _view_as_nexus_item; + JMenuItem _display_basic_information_item; + // help menu: + JMenuItem _about_item; + JMenuItem _help_item; + JMenuItem _website_item; + JMenuItem _phyloxml_website_item; + JMenuItem _phyloxml_ref_item; + JMenuItem _aptx_ref_item; + // process menu: + JMenu _process_menu; + // Handy pointers to child components: + MainPanel _mainpanel; + Container _contentpane; + final LinkedList _textframes = new LinkedList(); ; + Configuration _configuration; + Options _options; + private Phylogeny _species_tree; + InferenceManager _inference_manager; + final ProcessPool _process_pool; + private String _previous_node_annotation_ref; + + MainFrame() { + _process_pool = ProcessPool.createInstance(); + } + + /** + * Action performed. + */ + @Override + public void actionPerformed( final ActionEvent e ) { + final Object o = e.getSource(); + boolean is_applet = false; + JApplet applet = null; + if ( getCurrentTreePanel() != null ) { + is_applet = getCurrentTreePanel().isApplet(); + if ( is_applet ) { + applet = getCurrentTreePanel().obtainApplet(); + } + } + if ( o == _exit_item ) { + close(); + } + else if ( o == _gsdi_item ) { + if ( isSubtreeDisplayed() ) { + return; + } + executeGSDI(); + } + else if ( o == _gsdir_item ) { + if ( isSubtreeDisplayed() ) { + return; + } + executeGSDIR(); + } + else if ( o == _taxcolor_item ) { + taxColor(); + } + else if ( o == _confcolor_item ) { + confColor(); + } + else if ( o == _color_rank_jmi ) { + colorRank(); + } + else if ( o == _collapse_species_specific_subtrees ) { + if ( isSubtreeDisplayed() ) { + return; + } + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().collapseSpeciesSpecificSubtrees(); + } + } + else if ( o == _remove_branch_color_item ) { + if ( isSubtreeDisplayed() ) { + return; + } + removeBranchColors(); + } + else if ( o == _remove_visual_styles_item ) { + if ( isSubtreeDisplayed() ) { + return; + } + removeVisualStyles(); + } + else if ( o == _midpoint_root_item ) { + if ( isSubtreeDisplayed() ) { + return; + } + midpointRoot(); + } + else if ( o == _annotate_item ) { + annotateSequences(); + } + else if ( o == _switch_colors_mi ) { + switchColors(); + } + else if ( o == _display_basic_information_item ) { + displayBasicInformation( getCurrentTreePanel().getTreeFile() ); + } + else if ( o == _view_as_NH_item ) { + viewAsNH(); + } + else if ( o == _view_as_XML_item ) { + viewAsXML(); + } + else if ( o == _view_as_nexus_item ) { + viewAsNexus(); + } + else if ( o == _super_tiny_fonts_item ) { + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().setSuperTinyFonts(); + getCurrentTreePanel().repaint(); + } + } + else if ( o == _tiny_fonts_item ) { + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().setTinyFonts(); + getCurrentTreePanel().repaint(); + } + } + else if ( o == _small_fonts_item ) { + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().setSmallFonts(); + getCurrentTreePanel().repaint(); + } + } + else if ( o == _medium_fonts_item ) { + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().setMediumFonts(); + getCurrentTreePanel().repaint(); + } + } + else if ( o == _large_fonts_item ) { + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().setLargeFonts(); + getCurrentTreePanel().repaint(); + } + } + else if ( o == _choose_font_mi ) { + chooseFont(); + } + else if ( o == _choose_minimal_confidence_mi ) { + chooseMinimalConfidence(); + } + else if ( o == _choose_node_size_mi ) { + chooseNodeSize( getOptions(), this ); + } + else if ( o == _overview_placment_mi ) { + MainFrame.cycleOverview( getOptions(), getCurrentTreePanel() ); + } + else if ( o == _cycle_node_fill_mi ) { + MainFrame.cycleNodeFill( getOptions(), getCurrentTreePanel() ); + } + else if ( o == _cycle_node_shape_mi ) { + MainFrame.cycleNodeShape( getOptions(), getCurrentTreePanel() ); + } + else if ( o == _screen_antialias_cbmi ) { + updateOptions( getOptions() ); + updateScreenTextAntialias( getMainPanel().getTreePanels() ); + } + else if ( o == _background_gradient_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _show_domain_labels ) { + updateOptions( getOptions() ); + } + else if ( o == _show_annotation_ref_source ) { + updateOptions( getOptions() ); + } + else if ( o == _abbreviate_scientific_names ) { + updateOptions( getOptions() ); + } + else if ( o == _color_labels_same_as_parent_branch ) { + updateOptions( getOptions() ); + } + else if ( o == _show_default_node_shapes_internal_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _show_default_node_shapes_external_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _non_lined_up_cladograms_rbmi ) { + updateOptions( getOptions() ); + showWhole(); + } + else if ( o == _uniform_cladograms_rbmi ) { + updateOptions( getOptions() ); + showWhole(); + } + else if ( o == _ext_node_dependent_cladogram_rbmi ) { + updateOptions( getOptions() ); + showWhole(); + } + else if ( o == _search_case_senstive_cbmi ) { + updateOptions( getOptions() ); + getMainPanel().getControlPanel().search0(); + getMainPanel().getControlPanel().search1(); + } + else if ( o == _search_whole_words_only_cbmi ) { + updateOptions( getOptions() ); + getMainPanel().getControlPanel().search0(); + getMainPanel().getControlPanel().search1(); + } + else if ( o == _inverse_search_result_cbmi ) { + updateOptions( getOptions() ); + getMainPanel().getControlPanel().search0(); + getMainPanel().getControlPanel().search1(); + } + else if ( o == _show_scale_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _show_branch_length_values_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _color_by_taxonomic_group_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _show_confidence_stddev_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _use_brackets_for_conf_in_nh_export_cbmi ) { + if ( _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) { + _use_internal_names_for_conf_in_nh_export_cbmi.setSelected( false ); + } + updateOptions( getOptions() ); + } + else if ( o == _use_internal_names_for_conf_in_nh_export_cbmi ) { + if ( _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) { + _use_brackets_for_conf_in_nh_export_cbmi.setSelected( false ); + } + updateOptions( getOptions() ); + } + else if ( o == _label_direction_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _show_overview_cbmi ) { + updateOptions( getOptions() ); + if ( getCurrentTreePanel() != null ) { + getCurrentTreePanel().updateOvSizes(); + } + } + else if ( ( o == _rectangular_type_cbmi ) || ( o == _triangular_type_cbmi ) || ( o == _curved_type_cbmi ) + || ( o == _convex_type_cbmi ) || ( o == _euro_type_cbmi ) || ( o == _rounded_type_cbmi ) + || ( o == _unrooted_type_cbmi ) || ( o == _circular_type_cbmi ) ) { + typeChanged( o ); + } + else if ( o == _about_item ) { + about(); + } + else if ( o == _help_item ) { + help(); + } + else if ( o == _website_item ) { + try { + AptxUtil.openWebsite( Constants.APTX_WEB_SITE, is_applet, applet ); + } + catch ( final IOException e1 ) { + ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); + } + } + else if ( o == _phyloxml_website_item ) { + try { + AptxUtil.openWebsite( Constants.PHYLOXML_WEB_SITE, is_applet, applet ); + } + catch ( final IOException e1 ) { + ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); + } + } + else if ( o == _aptx_ref_item ) { + try { + AptxUtil.openWebsite( Constants.APTX_REFERENCE_URL, is_applet, applet ); + } + catch ( final IOException e1 ) { + ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); + } + } + else if ( o == _phyloxml_ref_item ) { + try { + AptxUtil.openWebsite( Constants.PHYLOXML_REFERENCE_URL, is_applet, applet ); + } + catch ( final IOException e1 ) { + ForesterUtil.printErrorMessage( Constants.PRG_NAME, e1.toString() ); + } + } + else { + if ( _load_phylogeny_from_webservice_menu_items != null ) { + for( int i = 0; i < _load_phylogeny_from_webservice_menu_items.length; ++i ) { + if ( o == _load_phylogeny_from_webservice_menu_items[ i ] ) { + readPhylogeniesFromWebservice( i ); + } + } + } + } + _contentpane.repaint(); + } + + public Configuration getConfiguration() { + return _configuration; + } + + /** + * This method returns the current external node data which + * has been selected by the user by clicking the "Return ..." + * menu item. This method is expected to be called from Javascript or + * something like it. + * + * @return current external node data as String + */ + public String getCurrentExternalNodesDataBuffer() { + return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString(); + } + + public int getCurrentExternalNodesDataBufferChangeCounter() { + return getCurrentTreePanel().getCurrentExternalNodesDataBufferChangeCounter(); + } + + public int getCurrentExternalNodesDataBufferLength() { + return getCurrentTreePanel().getCurrentExternalNodesDataBufferAsString().length(); + } + + public InferenceManager getInferenceManager() { + return _inference_manager; + } + + public MainPanel getMainPanel() { + return _mainpanel; + } + + public Options getOptions() { + return _options; + } + + public ProcessPool getProcessPool() { + return _process_pool; + } + + public void showTextFrame( final String s, final String title ) { + checkTextFrames(); + _textframes.addLast( TextFrame.instantiate( s, title, _textframes ) ); + } + + public void showWhole() { + _mainpanel.getControlPanel().showWhole(); + } + + public void updateProcessMenu() { + // In general Swing is not thread safe. + // See "Swing's Threading Policy". + SwingUtilities.invokeLater( new Runnable() { + + @Override + public void run() { + doUpdateProcessMenu(); + } + } ); + } + + void activateSaveAllIfNeeded() { + if ( ( getMainPanel().getTabbedPane() != null ) && ( getMainPanel().getTabbedPane().getTabCount() > 1 ) ) { + _save_all_item.setEnabled( true ); + } + else { + _save_all_item.setEnabled( false ); + } + } + + void buildFileMenu() { + _file_jmenu = createMenu( "File", getConfiguration() ); + _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) ); + customizeJMenuItem( _exit_item ); + _jmenubar.add( _file_jmenu ); + } + + void buildFontSizeMenu() { + _font_size_menu = createMenu( FONT_SIZE_MENU_LABEL, getConfiguration() ); + _font_size_menu.add( _super_tiny_fonts_item = new JMenuItem( "Super Tiny Fonts" ) ); + _font_size_menu.add( _tiny_fonts_item = new JMenuItem( "Tiny Fonts" ) ); + _font_size_menu.add( _small_fonts_item = new JMenuItem( "Small Fonts" ) ); + _font_size_menu.add( _medium_fonts_item = new JMenuItem( "Medium Fonts" ) ); + _font_size_menu.add( _large_fonts_item = new JMenuItem( "Large Fonts" ) ); + customizeJMenuItem( _super_tiny_fonts_item ); + customizeJMenuItem( _tiny_fonts_item ); + customizeJMenuItem( _small_fonts_item ); + customizeJMenuItem( _medium_fonts_item ); + customizeJMenuItem( _large_fonts_item ); + _jmenubar.add( _font_size_menu ); + } + + void buildHelpMenu() { + _help_jmenu = createMenu( "Help", getConfiguration() ); + _help_jmenu.add( _help_item = new JMenuItem( "Help" ) ); + _help_jmenu.add( _website_item = new JMenuItem( "Archaeopteryx Home" ) ); + _aptx_ref_item = new JMenuItem( "Archaeopteryx Reference" ); + _help_jmenu.add( _phyloxml_website_item = new JMenuItem( "phyloXML Home" ) ); + _help_jmenu.add( _phyloxml_ref_item = new JMenuItem( "phyloXML Reference" ) ); + _help_jmenu.addSeparator(); + _help_jmenu.add( _about_item = new JMenuItem( "About" ) ); + customizeJMenuItem( _help_item ); + customizeJMenuItem( _website_item ); + customizeJMenuItem( _phyloxml_website_item ); + customizeJMenuItem( _aptx_ref_item ); + customizeJMenuItem( _phyloxml_ref_item ); + customizeJMenuItem( _about_item ); + _phyloxml_ref_item.setToolTipText( PHYLOXML_REF_TOOL_TIP ); + _aptx_ref_item.setToolTipText( APTX_REF_TOOL_TIP ); + _jmenubar.add( _help_jmenu ); + } + + void buildTypeMenu() { + _type_menu = createMenu( TYPE_MENU_HEADER, getConfiguration() ); + _type_menu.add( _rectangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.RECTANGULAR_TYPE_CBMI_LABEL ) ); + _type_menu.add( _euro_type_cbmi = new JCheckBoxMenuItem( MainFrame.EURO_TYPE_CBMI_LABEL ) ); + _type_menu.add( _rounded_type_cbmi = new JCheckBoxMenuItem( MainFrame.ROUNDED_TYPE_CBMI_LABEL ) ); + _type_menu.add( _curved_type_cbmi = new JCheckBoxMenuItem( MainFrame.CURVED_TYPE_CBMI_LABEL ) ); + _type_menu.add( _triangular_type_cbmi = new JCheckBoxMenuItem( MainFrame.TRIANGULAR_TYPE_CBMI_LABEL ) ); + _type_menu.add( _convex_type_cbmi = new JCheckBoxMenuItem( MainFrame.CONVEX_TYPE_CBMI_LABEL ) ); + _type_menu.add( _unrooted_type_cbmi = new JCheckBoxMenuItem( MainFrame.UNROOTED_TYPE_CBMI_LABEL ) ); + _type_menu.add( _circular_type_cbmi = new JCheckBoxMenuItem( MainFrame.CIRCULAR_TYPE_CBMI_LABEL ) ); + customizeCheckBoxMenuItem( _rectangular_type_cbmi, false ); + customizeCheckBoxMenuItem( _triangular_type_cbmi, false ); + customizeCheckBoxMenuItem( _euro_type_cbmi, false ); + customizeCheckBoxMenuItem( _rounded_type_cbmi, false ); + customizeCheckBoxMenuItem( _curved_type_cbmi, false ); + customizeCheckBoxMenuItem( _convex_type_cbmi, false ); + customizeCheckBoxMenuItem( _unrooted_type_cbmi, false ); + customizeCheckBoxMenuItem( _circular_type_cbmi, false ); + _unrooted_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE ); + _circular_type_cbmi.setToolTipText( MainFrame.USE_MOUSEWHEEL_SHIFT_TO_ROTATE ); + initializeTypeMenu( getOptions() ); + _jmenubar.add( _type_menu ); + } + + void buildViewMenu() { + _view_jmenu = createMenu( "View", getConfiguration() ); + _view_jmenu.add( _display_basic_information_item = new JMenuItem( SHOW_BASIC_TREE_INFORMATION_LABEL ) ); + _view_jmenu.addSeparator(); + _view_jmenu.add( _view_as_XML_item = new JMenuItem( "as phyloXML" ) ); + _view_jmenu.add( _view_as_NH_item = new JMenuItem( "as Newick" ) ); + _view_jmenu.add( _view_as_nexus_item = new JMenuItem( "as Nexus" ) ); + customizeJMenuItem( _display_basic_information_item ); + customizeJMenuItem( _view_as_NH_item ); + customizeJMenuItem( _view_as_XML_item ); + customizeJMenuItem( _view_as_nexus_item ); + _jmenubar.add( _view_jmenu ); + } + + void checkTextFrames() { + if ( _textframes.size() > 5 ) { + try { + if ( _textframes.getFirst() != null ) { + _textframes.getFirst().removeMe(); + } + else { + _textframes.removeFirst(); + } + } + catch ( final NoSuchElementException e ) { + // Ignore. + } + } + } + + void close() { + removeAllTextFrames(); + if ( _mainpanel != null ) { + _mainpanel.terminate(); + } + if ( _contentpane != null ) { + _contentpane.removeAll(); + } + setVisible( false ); + dispose(); + } + + void colorRank() { + if ( _mainpanel.getCurrentTreePanel() != null ) { + final String[] ranks = AptxUtil.getAllPossibleRanks(); + final String rank = ( String ) JOptionPane + .showInputDialog( this, + "What rank should the colorization be based on", + "Rank Selection", + JOptionPane.QUESTION_MESSAGE, + null, + ranks, + null ); + if ( !ForesterUtil.isEmpty( rank ) ) { + _mainpanel.getCurrentTreePanel().colorRank( rank ); + } + } + } + + void confColor() { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().confColor(); + } + } + + void customizeCheckBoxMenuItem( final JCheckBoxMenuItem item, final boolean is_selected ) { + if ( item != null ) { + item.setFont( MainFrame.menu_font ); + if ( !getConfiguration().isUseNativeUI() ) { + item.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); + item.setForeground( getConfiguration().getGuiMenuTextColor() ); + } + item.setSelected( is_selected ); + item.addActionListener( this ); + } + } + + JMenuItem customizeJMenuItem( final JMenuItem jmi ) { + if ( jmi != null ) { + jmi.setFont( MainFrame.menu_font ); + if ( !getConfiguration().isUseNativeUI() ) { + jmi.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); + jmi.setForeground( getConfiguration().getGuiMenuTextColor() ); + } + jmi.addActionListener( this ); + } + return jmi; + } + + void customizeRadioButtonMenuItem( final JRadioButtonMenuItem item, final boolean is_selected ) { + if ( item != null ) { + item.setFont( MainFrame.menu_font ); + if ( !getConfiguration().isUseNativeUI() ) { + item.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); + item.setForeground( getConfiguration().getGuiMenuTextColor() ); + } + item.setSelected( is_selected ); + item.addActionListener( this ); + } + } + + void displayBasicInformation( final File treefile ) { + if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { + String title = "Basic Information"; + if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { + title = title + " for \"" + _mainpanel.getCurrentPhylogeny().getName() + "\""; + } + showTextFrame( AptxUtil.createBasicInformation( _mainpanel.getCurrentPhylogeny(), treefile ), title ); + } + } + + void exceptionOccuredDuringOpenFile( final Exception e ) { + try { + _mainpanel.getCurrentTreePanel().setArrowCursor(); + } + catch ( final Exception ex ) { + // Do nothing. + } + JOptionPane.showMessageDialog( this, + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ), + "Error during File|Open", + JOptionPane.ERROR_MESSAGE ); + } + + void exceptionOccuredDuringSaveAs( final Exception e ) { + try { + _mainpanel.getCurrentTreePanel().setArrowCursor(); + } + catch ( final Exception ex ) { + // Do nothing. + } + JOptionPane.showMessageDialog( this, "Exception" + e, "Error during File|SaveAs", JOptionPane.ERROR_MESSAGE ); + } + + void executeGSDI() { + if ( !isOKforSDI( false, true ) ) { + return; + } + if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) { + JOptionPane.showMessageDialog( this, + "Gene tree is not rooted.", + "Cannot execute GSDI", + JOptionPane.ERROR_MESSAGE ); + return; + } + final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy(); + gene_tree.setAllNodesToNotCollapse(); + gene_tree.recalculateNumberOfExternalDescendants( false ); + GSDI gsdi = null; + final Phylogeny species_tree = getSpeciesTree().copy(); + try { + gsdi = new GSDI( gene_tree, species_tree, false, true, true, true ); + } + catch ( final SDIException e ) { + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Error during GSDI", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final Exception e ) { + AptxUtil.unexpectedException( e ); + return; + } + gene_tree.setRerootable( false ); + gene_tree.clearHashIdToNodeMap(); + gene_tree.recalculateNumberOfExternalDescendants( true ); + _mainpanel.addPhylogenyInNewTab( gene_tree, getConfiguration(), "gene tree", null ); + getMainPanel().getControlPanel().setShowEvents( true ); + showWhole(); + final int selected = _mainpanel.getTabbedPane().getSelectedIndex(); + _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null ); + showWhole(); + _mainpanel.getTabbedPane().setSelectedIndex( selected ); + showWhole(); + _mainpanel.getCurrentTreePanel().setEdited( true ); + final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree ); + if ( gsdi.getStrippedExternalGeneTreeNodes().size() > 0 ) { + JOptionPane.showMessageDialog( this, + "Duplications: " + gsdi.getDuplicationsSum() + "\n" + + "Potential duplications: " + + gsdi.getSpeciationOrDuplicationEventsSum() + "\n" + + "Speciations: " + gsdi.getSpeciationsSum() + "\n" + + "Stripped gene tree nodes: " + + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n" + + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n" + + "Number of polytomies in species tree used: " + poly + "\n", + "GSDI successfully completed", + JOptionPane.WARNING_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, + "Duplications: " + gsdi.getDuplicationsSum() + "\n" + + "Potential duplications: " + + gsdi.getSpeciationOrDuplicationEventsSum() + "\n" + + "Speciations: " + gsdi.getSpeciationsSum() + "\n" + + "Stripped gene tree nodes: " + + gsdi.getStrippedExternalGeneTreeNodes().size() + "\n" + + "Taxonomy linkage based on: " + gsdi.getTaxCompBase() + "\n" + + "Number of polytomies in species tree used: " + poly + "\n", + "GSDI successfully completed", + JOptionPane.INFORMATION_MESSAGE ); + } + } + + void executeGSDIR() { + if ( !isOKforSDI( false, false ) ) { + return; + } + final int p = PhylogenyMethods.countNumberOfPolytomies( _mainpanel.getCurrentPhylogeny() ); + if ( ( p > 0 ) + && !( ( p == 1 ) && ( _mainpanel.getCurrentPhylogeny().getRoot().getNumberOfDescendants() == 3 ) ) ) { + JOptionPane.showMessageDialog( this, + "Gene tree is not completely binary", + "Cannot execute GSDI", + JOptionPane.ERROR_MESSAGE ); + return; + } + final Phylogeny gene_tree = _mainpanel.getCurrentPhylogeny().copy(); + gene_tree.setAllNodesToNotCollapse(); + gene_tree.recalculateNumberOfExternalDescendants( false ); + GSDIR gsdir = null; + final Phylogeny species_tree = getSpeciesTree().copy(); + try { + gsdir = new GSDIR( gene_tree, species_tree, true, true, true ); + } + catch ( final SDIException e ) { + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Error during GSDIR", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final Exception e ) { + AptxUtil.unexpectedException( e ); + return; + } + final Phylogeny result_gene_tree = gsdir.getMinDuplicationsSumGeneTree(); + result_gene_tree.setRerootable( false ); + result_gene_tree.clearHashIdToNodeMap(); + result_gene_tree.recalculateNumberOfExternalDescendants( true ); + PhylogenyMethods.orderAppearance( result_gene_tree.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.NODE_NAME ); + _mainpanel.addPhylogenyInNewTab( result_gene_tree, getConfiguration(), "gene tree", null ); + getMainPanel().getControlPanel().setShowEvents( true ); + showWhole(); + final int selected = _mainpanel.getTabbedPane().getSelectedIndex(); + _mainpanel.addPhylogenyInNewTab( species_tree, getConfiguration(), "species tree", null ); + showWhole(); + _mainpanel.getTabbedPane().setSelectedIndex( selected ); + showWhole(); + _mainpanel.getCurrentTreePanel().setEdited( true ); + final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree ); + if ( gsdir.getStrippedExternalGeneTreeNodes().size() > 0 ) { + JOptionPane.showMessageDialog( this, + "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n" + + "Speciations: " + gsdir.getSpeciationsSum() + "\n" + + "Stripped gene tree nodes: " + + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n" + + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n" + + "Number of polytomies in species tree used: " + poly + "\n", + "GSDIR successfully completed", + JOptionPane.WARNING_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, + "Minimal duplications: " + gsdir.getMinDuplicationsSum() + "\n" + + "Speciations: " + gsdir.getSpeciationsSum() + "\n" + + "Stripped gene tree nodes: " + + gsdir.getStrippedExternalGeneTreeNodes().size() + "\n" + + "Taxonomy linkage based on: " + gsdir.getTaxCompBase() + "\n" + + "Number of polytomies in species tree used: " + poly + "\n", + "GSDIR successfully completed", + JOptionPane.INFORMATION_MESSAGE ); + } + } + + boolean GAndSDoHaveMoreThanOneSpeciesInComman( final Phylogeny gene_tree ) { + if ( ( gene_tree == null ) || gene_tree.isEmpty() ) { + JOptionPane.showMessageDialog( this, + "Gene tree and species tree have no species in common.", + "Error during SDI", + JOptionPane.ERROR_MESSAGE ); + return false; + } + else if ( gene_tree.getNumberOfExternalNodes() < 2 ) { + JOptionPane.showMessageDialog( this, + "Gene tree and species tree have only one species in common.", + "Error during SDI", + JOptionPane.ERROR_MESSAGE ); + return false; + } + else { + return true; + } + } + + TreePanel getCurrentTreePanel() { + return getMainPanel().getCurrentTreePanel(); + } + + JMenu getHelpMenu() { + return _help_jmenu; + } + + JCheckBoxMenuItem getlabelDirectionCbmi() { + return _label_direction_cbmi; + } + + JMenuBar getMenuBarOfMainFrame() { + return _jmenubar; + } + + final Phylogeny getSpeciesTree() { + return _species_tree; + } + + void help() { + final StringBuilder sb = new StringBuilder(); + sb.append( "Display options\n" ); + sb.append( "-------------------\n" ); + sb.append( "Use the checkboxes to select types of information to display on the tree.\n\n" ); + sb.append( "Clickable tree nodes\n" ); + sb.append( "--------------------\n" ); + sb.append( "Tree nodes can be clicked, the action is determined by the 'click on node to' menu\n" ); + sb.append( "or by right clicking:\n" ); + sb.append( "o Display Node Data -- display information for a node\n" ); + sb.append( "o Collapse/Uncollapse -- collapse and uncollapse subtree from clicked node\n" ); + sb.append( "o Root/Reroot -- change tree root to clicked node\n" ); + sb.append( "o Sub/Super Tree -- toggle between subtree from clicked node and whole tree\n" ); + sb.append( "o Swap Descendants -- switch descendant on either side of clicked node\n" ); + sb.append( "o Colorize Subtree -- color a subtree\n" ); + sb.append( "o Open Sequence Web -- launch a web browser to display sequence information\n" ); + sb.append( "o Open Taxonomy Web -- launch a web browser to display taxonomy information\n" ); + sb.append( "- there may be additional choices depending on this particular setup\n\n" ); + sb.append( "Right clicking on a node always displays the information of a node.\n\n" ); + sb.append( "Zooming\n" ); + sb.append( "---------\n" ); + sb.append( "The mouse wheel and the plus and minus keys control zooming.\n" ); + sb.append( "Mouse wheel+Ctrl changes the text size.\n" ); + sb.append( "Mouse wheel+Shift controls zooming in vertical direction only.\n" ); + sb.append( "Use the buttons on the control panel to zoom the tree in and out, horizontally or vertically.\n" ); + sb.append( "The entire tree can be fitted into the window by clicking the \"F\" button, or by pressing F, Delete, or Home.\n" ); + sb.append( "The up, down, left, and right keys can be used to move the visible part (if zoomed in).\n" ); + sb.append( "Up, down, left, and right+Shift can be used to control zooming horizontally and vertically.\n" ); + sb.append( "Plus and minus keys+Ctrl change the text size; F+Ctrl, Delete+Ctrl, or Home+Ctrl resets it.\n\n" ); + sb.append( "Quick tree manipulation:\n" ); + sb.append( "------------------------\n" ); + sb.append( "Order Subtrees -- order the tree by branch length\n" ); + sb.append( "Uncollapse All -- uncollapse any and all collapsed branches\n\n" ); + sb.append( "Memory problems (Java heap space error)\n" ); + sb.append( "---------------------------------------\n" ); + sb.append( "Since the Java default memory allocation is quite small, it might by necessary (for trees\n" ); + sb.append( "with more than approximately 5000 external nodes) to increase the memory which Java can use, with\n" ); + sb.append( "the '-Xmx' Java command line option. For example:\n" ); + sb.append( "java -Xmx1024m -cp path\\to\\forester.jar org.forester.archaeopteryx.Archaeopteryx\n\n" ); + // + "General remarks\n" + // + "---------------\n" + // + + // "o The application version permits copying to the clipboard \n" + // + + // " in the \"View\"|\"View as ...\" frame (either by control-c or button press).\n" + // + + // "o Changes made to a subtree affect this subtree and its subtrees,\n" + // + " but not any of its parent tree(s).\n" + // + + // "o Archaeopteryx tries to detect whether the numerical values in a NH tree\n" + // + + // " are likely to be bootstrap values instead of branch length values.\n\n" + // + + // " Remarks regarding SDI (Speciation Duplication Inference):\n" + // + + // "o Each external node of the gene tree (in display) needs to be associated with\n" + // + + // " a species: either directly through the \"Species\" field, or the species\n" + // + + // " is part of the sequence name in the form \"XXXX_SPECIES\"\n" + // + + // " (e.g. \"ACON_DROME\" or \"ACON_DROME/123-4489\" which is also acceptable).\n" + // + + // "o A species tree for each species of the gene tree needs to be loaded with\n" + // + + // " \"SDI\"|\"Load species tree\" prior the SDI execution.\n" + // + + // "o !External nodes of the gene tree associated with species not present in\n" + // + + // " the species tree are REMOVED prior to SDI execution!\n" + // + + // "o Both the gene tree and the species tree must be completely binary.\n" + // + + // "o Duplications and speciations are a function of the position of the root.\n" + // + + // " Hence, after each manual \"Root/Reroot\"ing some duplications will be\n" + // + " incorrect and need to be inferred again\n" + // + + // " with: \"SDI\"|\"SDI (Speciation Duplication Inference)\n\n" + sb.append( "phyloXML\n" ); + sb.append( "-------------------\n" ); + sb.append( "Reference: " + Constants.PHYLOXML_REFERENCE + "\n" ); + sb.append( "Website: " + Constants.PHYLOXML_WEB_SITE + "\n" ); + sb.append( "Version: " + ForesterConstants.PHYLO_XML_VERSION + "\n" ); + sb.append( "\n" ); + sb.append( "For more information: https://sites.google.com/site/cmzmasek/home/software/archaeopteryx\n" ); + sb.append( "Email: " + Constants.AUTHOR_EMAIL + "\n\n" ); + TextFrame.instantiate( sb.toString(), "Help", _textframes ); + } + + void initializeTypeMenu( final Options options ) { + setTypeMenuToAllUnselected(); + switch ( options.getPhylogenyGraphicsType() ) { + case CONVEX: + _convex_type_cbmi.setSelected( true ); + break; + case CURVED: + _curved_type_cbmi.setSelected( true ); + break; + case EURO_STYLE: + _euro_type_cbmi.setSelected( true ); + break; + case ROUNDED: + _rounded_type_cbmi.setSelected( true ); + break; + case TRIANGULAR: + _triangular_type_cbmi.setSelected( true ); + break; + case UNROOTED: + _unrooted_type_cbmi.setSelected( true ); + break; + case CIRCULAR: + _circular_type_cbmi.setSelected( true ); + break; + default: + _rectangular_type_cbmi.setSelected( true ); + break; + } + } + + boolean isOKforSDI( final boolean species_tree_has_to_binary, final boolean gene_tree_has_to_binary ) { + if ( ( _mainpanel.getCurrentPhylogeny() == null ) || _mainpanel.getCurrentPhylogeny().isEmpty() ) { + return false; + } + else if ( ( getSpeciesTree() == null ) || getSpeciesTree().isEmpty() ) { + JOptionPane.showMessageDialog( this, + "No species tree loaded", + "Cannot execute GSDI", + JOptionPane.ERROR_MESSAGE ); + return false; + } + else if ( species_tree_has_to_binary && !getSpeciesTree().isCompletelyBinary() ) { + JOptionPane.showMessageDialog( this, + "Species tree is not completely binary", + "Cannot execute GSDI", + JOptionPane.ERROR_MESSAGE ); + return false; + } + else if ( gene_tree_has_to_binary && !_mainpanel.getCurrentPhylogeny().isCompletelyBinary() ) { + JOptionPane.showMessageDialog( this, + "Gene tree is not completely binary", + "Cannot execute GSDI", + JOptionPane.ERROR_MESSAGE ); + return false; + } + else { + return true; + } + } + + boolean isSubtreeDisplayed() { + if ( getCurrentTreePanel() != null ) { + if ( getCurrentTreePanel().isCurrentTreeIsSubtree() ) { + JOptionPane + .showMessageDialog( this, + "This operation can only be performed on a complete tree, not on the currently displayed sub-tree only.", + "Operation can not be exectuted on a sub-tree", + JOptionPane.WARNING_MESSAGE ); + return true; + } + } + return false; + } + + void midpointRoot() { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().midpointRoot(); + } + } + + void readPhylogeniesFromWebservice( final int i ) { + final UrlTreeReader reader = new UrlTreeReader( this, i ); + new Thread( reader ).start(); + } + + void removeAllTextFrames() { + for( final TextFrame tf : _textframes ) { + if ( tf != null ) { + tf.close(); + } + } + _textframes.clear(); + } + + void setConfiguration( final Configuration configuration ) { + _configuration = configuration; + } + + void setInferenceManager( final InferenceManager i ) { + _inference_manager = i; + } + + void setOptions( final Options options ) { + _options = options; + } + + void setSelectedTypeInTypeMenu( final PHYLOGENY_GRAPHICS_TYPE type ) { + setTypeMenuToAllUnselected(); + switch ( type ) { + case CIRCULAR: + _circular_type_cbmi.setSelected( true ); + break; + case CONVEX: + _convex_type_cbmi.setSelected( true ); + break; + case CURVED: + _curved_type_cbmi.setSelected( true ); + break; + case EURO_STYLE: + _euro_type_cbmi.setSelected( true ); + break; + case ROUNDED: + _rounded_type_cbmi.setSelected( true ); + break; + case RECTANGULAR: + _rectangular_type_cbmi.setSelected( true ); + break; + case TRIANGULAR: + _triangular_type_cbmi.setSelected( true ); + break; + case UNROOTED: + _unrooted_type_cbmi.setSelected( true ); + break; + default: + throw new IllegalArgumentException( "unknown type: " + type ); + } + } + + final void setSpeciesTree( final Phylogeny species_tree ) { + _species_tree = species_tree; + } + + void setTypeMenuToAllUnselected() { + _convex_type_cbmi.setSelected( false ); + _curved_type_cbmi.setSelected( false ); + _euro_type_cbmi.setSelected( false ); + _rounded_type_cbmi.setSelected( false ); + _triangular_type_cbmi.setSelected( false ); + _rectangular_type_cbmi.setSelected( false ); + _unrooted_type_cbmi.setSelected( false ); + _circular_type_cbmi.setSelected( false ); + } + + void switchColors() { + final TreeColorSet colorset = _mainpanel.getTreeColorSet(); + final ColorSchemeChooser csc = new ColorSchemeChooser( getMainPanel(), colorset ); + csc.setVisible( true ); + } + + void taxColor() { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().taxColor(); + } + } + + void typeChanged( final Object o ) { + updateTypeCheckboxes( getOptions(), o ); + updateOptions( getOptions() ); + if ( getCurrentTreePanel() != null ) { + final PHYLOGENY_GRAPHICS_TYPE previous_type = getCurrentTreePanel().getPhylogenyGraphicsType(); + final PHYLOGENY_GRAPHICS_TYPE new_type = getOptions().getPhylogenyGraphicsType(); + if ( ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) + || ( ( previous_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) + || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) + || ( ( previous_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) && ( new_type == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) ) { + getCurrentTreePanel().getControlPanel().showWhole(); + } + if ( getCurrentTreePanel().isPhyHasBranchLengths() && ( new_type != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) { + getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( true ); + } + else { + getCurrentTreePanel().getControlPanel().setDrawPhylogramEnabled( false ); + } + getCurrentTreePanel().setPhylogenyGraphicsType( getOptions().getPhylogenyGraphicsType() ); + updateScreenTextAntialias( getMainPanel().getTreePanels() ); + if ( getCurrentTreePanel().getControlPanel().getDynamicallyHideData() != null ) { + if ( new_type == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) { + getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( false ); + } + else { + getCurrentTreePanel().getControlPanel().getDynamicallyHideData().setEnabled( true ); + } + } + } + } + + void updateOptions( final Options options ) { + options.setAntialiasScreen( ( _screen_antialias_cbmi != null ) && _screen_antialias_cbmi.isSelected() ); + options.setBackgroundColorGradient( ( _background_gradient_cbmi != null ) + && _background_gradient_cbmi.isSelected() ); + options.setShowDomainLabels( ( _show_domain_labels != null ) && _show_domain_labels.isSelected() ); + options.setShowAnnotationRefSource( ( _show_annotation_ref_source != null ) + && _show_annotation_ref_source.isSelected() ); + options.setAbbreviateScientificTaxonNames( ( _abbreviate_scientific_names != null ) + && _abbreviate_scientific_names.isSelected() ); + options.setColorLabelsSameAsParentBranch( ( _color_labels_same_as_parent_branch != null ) + && _color_labels_same_as_parent_branch.isSelected() ); + options.setShowDefaultNodeShapesInternal( ( _show_default_node_shapes_internal_cbmi != null ) + && _show_default_node_shapes_internal_cbmi.isSelected() ); + options.setShowDefaultNodeShapesExternal( ( _show_default_node_shapes_external_cbmi != null ) + && _show_default_node_shapes_external_cbmi.isSelected() ); + if ( ( _non_lined_up_cladograms_rbmi != null ) && ( _non_lined_up_cladograms_rbmi.isSelected() ) ) { + options.setCladogramType( CLADOGRAM_TYPE.NON_LINED_UP ); + } + else if ( ( _uniform_cladograms_rbmi != null ) && ( _uniform_cladograms_rbmi.isSelected() ) ) { + options.setCladogramType( CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP ); + } + else if ( ( _ext_node_dependent_cladogram_rbmi != null ) && ( _ext_node_dependent_cladogram_rbmi.isSelected() ) ) { + options.setCladogramType( CLADOGRAM_TYPE.EXT_NODE_SUM_DEP ); + } + options.setSearchCaseSensitive( ( _search_case_senstive_cbmi != null ) + && _search_case_senstive_cbmi.isSelected() ); + if ( ( _show_scale_cbmi != null ) && _show_scale_cbmi.isEnabled() ) { + options.setShowScale( _show_scale_cbmi.isSelected() ); + } + if ( _label_direction_cbmi != null ) { + if ( _label_direction_cbmi.isSelected() ) { + options.setNodeLabelDirection( NODE_LABEL_DIRECTION.RADIAL ); + } + else { + options.setNodeLabelDirection( NODE_LABEL_DIRECTION.HORIZONTAL ); + } + } + options.setShowOverview( ( _show_overview_cbmi != null ) && _show_overview_cbmi.isSelected() ); + options.setShowConfidenceStddev( ( _show_confidence_stddev_cbmi != null ) + && _show_confidence_stddev_cbmi.isSelected() ); + if ( ( _show_branch_length_values_cbmi != null ) && _show_branch_length_values_cbmi.isEnabled() ) { + options.setShowBranchLengthValues( _show_branch_length_values_cbmi.isSelected() ); + } + if ( ( _color_by_taxonomic_group_cbmi != null ) && _color_by_taxonomic_group_cbmi.isEnabled() ) { + options.setColorByTaxonomicGroup( _color_by_taxonomic_group_cbmi.isSelected() ); + } + options.setPrintUsingActualSize( ( _print_using_actual_size_cbmi != null ) + && ( _print_using_actual_size_cbmi.isSelected() ) ); + options.setGraphicsExportUsingActualSize( ( _graphics_export_using_actual_size_cbmi != null ) + && ( _graphics_export_using_actual_size_cbmi.isSelected() ) ); + options.setAntialiasPrint( ( _antialias_print_cbmi != null ) && _antialias_print_cbmi.isSelected() ); + if ( ( _use_brackets_for_conf_in_nh_export_cbmi != null ) + && _use_brackets_for_conf_in_nh_export_cbmi.isSelected() ) { + options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ); + } + else if ( ( _use_internal_names_for_conf_in_nh_export_cbmi != null ) + && _use_internal_names_for_conf_in_nh_export_cbmi.isSelected() ) { + options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ); + } + else { + options.setNhConversionSupportValueStyle( NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE ); + } + options.setPrintBlackAndWhite( ( _print_black_and_white_cbmi != null ) + && _print_black_and_white_cbmi.isSelected() ); + options.setInternalNumberAreConfidenceForNhParsing( ( _internal_number_are_confidence_for_nh_parsing_cbmi != null ) + && _internal_number_are_confidence_for_nh_parsing_cbmi.isSelected() ); + if ( ( _extract_taxonomy_pfam_strict_rbmi != null ) && _extract_taxonomy_pfam_strict_rbmi.isSelected() ) { + options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ); + } + else if ( ( _extract_taxonomy_pfam_relaxed_rbmi != null ) && _extract_taxonomy_pfam_relaxed_rbmi.isSelected() ) { + options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED ); + } + else if ( ( _extract_taxonomy_agressive_rbmi != null ) && _extract_taxonomy_agressive_rbmi.isSelected() ) { + options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE ); + } + else if ( ( _extract_taxonomy_no_rbmi != null ) && _extract_taxonomy_no_rbmi.isSelected() ) { + options.setTaxonomyExtraction( TAXONOMY_EXTRACTION.NO ); + } + options.setReplaceUnderscoresInNhParsing( ( _replace_underscores_cbmi != null ) + && _replace_underscores_cbmi.isSelected() ); + options.setAllowErrorsInDistanceToParent( ( _allow_errors_in_distance_to_parent_cbmi != null ) + && _allow_errors_in_distance_to_parent_cbmi.isSelected() ); + options.setMatchWholeTermsOnly( ( _search_whole_words_only_cbmi != null ) + && _search_whole_words_only_cbmi.isSelected() ); + options.setInverseSearchResult( ( _inverse_search_result_cbmi != null ) + && _inverse_search_result_cbmi.isSelected() ); + if ( _graphics_export_visible_only_cbmi != null ) { + options.setGraphicsExportVisibleOnly( _graphics_export_visible_only_cbmi.isSelected() ); + if ( _graphics_export_visible_only_cbmi.isSelected() && ( _graphics_export_using_actual_size_cbmi != null ) ) { + _graphics_export_using_actual_size_cbmi.setSelected( true ); + _graphics_export_using_actual_size_cbmi.setEnabled( false ); + } + else { + _graphics_export_using_actual_size_cbmi.setEnabled( true ); + } + } + if ( ( _rectangular_type_cbmi != null ) && _rectangular_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); + } + else if ( ( _triangular_type_cbmi != null ) && _triangular_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR ); + } + else if ( ( _curved_type_cbmi != null ) && _curved_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CURVED ); + } + else if ( ( _convex_type_cbmi != null ) && _convex_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CONVEX ); + } + else if ( ( _euro_type_cbmi != null ) && _euro_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ); + } + else if ( ( _rounded_type_cbmi != null ) && _rounded_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.ROUNDED ); + } + else if ( ( _unrooted_type_cbmi != null ) && _unrooted_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.UNROOTED ); + } + else if ( ( _circular_type_cbmi != null ) && _circular_type_cbmi.isSelected() ) { + options.setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ); + } + } + + void updateTypeCheckboxes( final Options options, final Object o ) { + setTypeMenuToAllUnselected(); + ( ( JCheckBoxMenuItem ) o ).setSelected( true ); + } + + void viewAsNexus() { + if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { + String title = "Nexus"; + if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { + title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; + } + showTextFrame( _mainpanel.getCurrentPhylogeny().toNexus( getOptions().getNhConversionSupportValueStyle() ), + title ); + } + } + + void viewAsNH() { + if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { + String title = "New Hampshire"; + if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { + title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; + } + showTextFrame( _mainpanel.getCurrentPhylogeny().toNewHampshire( getOptions() + .getNhConversionSupportValueStyle() ), + title ); + } + } + + void viewAsXML() { + if ( ( _mainpanel.getCurrentPhylogeny() != null ) && !_mainpanel.getCurrentPhylogeny().isEmpty() ) { + String title = "phyloXML"; + if ( !ForesterUtil.isEmpty( _mainpanel.getCurrentPhylogeny().getName() ) ) { + title = "\"" + getMainPanel().getCurrentPhylogeny().getName() + "\" in " + title; + } + showTextFrame( _mainpanel.getCurrentPhylogeny().toPhyloXML( 0 ), title ); + } + } + + private void annotateSequences() { + if ( getCurrentTreePanel() != null ) { + final Set nodes = getCurrentTreePanel().getFoundNodes0(); + if ( ( nodes == null ) || nodes.isEmpty() ) { + JOptionPane + .showMessageDialog( this, + "Need to select nodes, either via direct selection or via the \"Search\" function", + "No nodes selected for annotation", + JOptionPane.ERROR_MESSAGE ); + return; + } + final Phylogeny phy = getMainPanel().getCurrentPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final JTextField ref_field = new JTextField( 10 ); + final JTextField desc_filed = new JTextField( 20 ); + ref_field.setText( ForesterUtil.isEmpty( getPreviousNodeAnnotationReference() ) ? "" + : getPreviousNodeAnnotationReference() ); + final JPanel my_panel = new JPanel(); + my_panel.add( new JLabel( "Reference " ) ); + my_panel.add( ref_field ); + my_panel.add( Box.createHorizontalStrut( 15 ) ); + my_panel.add( new JLabel( "Description " ) ); + my_panel.add( desc_filed ); + final int result = JOptionPane.showConfirmDialog( null, + my_panel, + "Enter the sequence annotation(s) for the " + + nodes.size() + " selected nodes", + JOptionPane.OK_CANCEL_OPTION ); + if ( result == JOptionPane.OK_OPTION ) { + String ref = ref_field.getText(); + String desc = desc_filed.getText(); + if ( !ForesterUtil.isEmpty( ref ) ) { + ref = ref.trim(); + ref = ref.replaceAll( "\\s+", " " ); + if ( ( ref.indexOf( ':' ) < 1 ) || ( ref.indexOf( ':' ) > ( ref.length() - 2 ) ) + || ( ref.length() < 3 ) ) { + JOptionPane.showMessageDialog( this, + "Reference needs to be in the form of \"GO:1234567\"", + "Illegal Format for Annotation Reference", + JOptionPane.ERROR_MESSAGE ); + return; + } + } + if ( ref != null ) { + setPreviousNodeAnnotationReference( ref ); + } + if ( desc != null ) { + desc = desc.trim(); + desc = desc.replaceAll( "\\s+", " " ); + } + if ( !ForesterUtil.isEmpty( ref ) || !ForesterUtil.isEmpty( desc ) ) { + for( final Long id : nodes ) { + final PhylogenyNode n = phy.getNode( id ); + ForesterUtil.ensurePresenceOfSequence( n ); + final Annotation ann = ForesterUtil.isEmpty( ref ) ? new Annotation() + : new Annotation( ref ); + if ( !ForesterUtil.isEmpty( desc ) ) { + ann.setDesc( desc ); + } + n.getNodeData().getSequence().addAnnotation( ann ); + } + } + getMainPanel().getControlPanel().showAnnotations(); + } + } + } + } + + private void chooseFont() { + final FontChooser fc = new FontChooser(); + fc.setFont( getMainPanel().getTreeFontSet().getLargeFont() ); + fc.showDialog( this, "Select the Base Font" ); + getMainPanel().getTreeFontSet().setBaseFont( fc.getFont() ); + } + + private void chooseMinimalConfidence() { + final String s = ( String ) JOptionPane + .showInputDialog( this, + "Please enter the minimum for confidence values to be displayed.\n" + + "[current value: " + getOptions().getMinConfidenceValue() + "]\n", + "Minimal Confidence Value", + JOptionPane.QUESTION_MESSAGE, + null, + null, + getOptions().getMinConfidenceValue() ); + if ( !ForesterUtil.isEmpty( s ) ) { + boolean success = true; + double m = 0.0; + final String m_str = s.trim(); + if ( !ForesterUtil.isEmpty( m_str ) ) { + try { + m = Double.parseDouble( m_str ); + } + catch ( final Exception ex ) { + success = false; + } + } + else { + success = false; + } + if ( success && ( m >= 0.0 ) ) { + getOptions().setMinConfidenceValue( m ); + } + } + } + + private void doUpdateProcessMenu() { + if ( _process_pool.size() > 0 ) { + if ( _process_menu == null ) { + _process_menu = createMenu( "", getConfiguration() ); + _process_menu.setForeground( Color.RED ); + } + _process_menu.removeAll(); + final String text = "processes running: " + _process_pool.size(); + _process_menu.setText( text ); + _jmenubar.add( _process_menu ); + for( int i = 0; i < _process_pool.size(); ++i ) { + final ProcessRunning p = _process_pool.getProcessByIndex( i ); + _process_menu.add( customizeJMenuItem( new JMenuItem( p.getName() + " [" + p.getStart() + "]" ) ) ); + } + } + else { + if ( _process_menu != null ) { + _process_menu.removeAll(); + _jmenubar.remove( _process_menu ); + } + } + _jmenubar.validate(); + _jmenubar.repaint(); + repaint(); + } + + private String getPreviousNodeAnnotationReference() { + return _previous_node_annotation_ref; + } + + private void removeBranchColors() { + if ( getMainPanel().getCurrentPhylogeny() != null ) { + AptxUtil.removeBranchColors( getMainPanel().getCurrentPhylogeny() ); + } + } + + private void removeVisualStyles() { + if ( getMainPanel().getCurrentPhylogeny() != null ) { + AptxUtil.removeVisualStyles( getMainPanel().getCurrentPhylogeny() ); + } + } + + private void setPreviousNodeAnnotationReference( final String previous_node_annotation_ref ) { + _previous_node_annotation_ref = previous_node_annotation_ref; + } + + /** + * Display the about box. + */ + static void about() { + final StringBuffer about = new StringBuffer( "Archaeopteryx\nVersion " + Constants.VERSION + "\n" ); + about.append( "Copyright (C) 2013 Christian M. Zmasek\n" ); + about.append( "All Rights Reserved\n" ); + about.append( "License: GNU Lesser General Public License (LGPL)\n" ); + about.append( "Last modified: " + Constants.PRG_DATE + "\n" ); + about.append( "Based on: " + ForesterUtil.getForesterLibraryInformation() + "\n" ); + about.append( "phyloXML version : " + ForesterConstants.PHYLO_XML_VERSION + "\n" ); + about.append( "phyloXML location: " + ForesterConstants.PHYLO_XML_LOCATION + "\n" ); + if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) { + about.append( "[your Java version: " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]\n" ); + } + if ( !ForesterUtil.isEmpty( ForesterUtil.OS_NAME ) && !ForesterUtil.isEmpty( ForesterUtil.OS_ARCH ) + && !ForesterUtil.isEmpty( ForesterUtil.OS_VERSION ) ) { + about.append( "[your OS: " + ForesterUtil.OS_NAME + " " + ForesterUtil.OS_ARCH + " " + + ForesterUtil.OS_VERSION + "]\n" ); + } + final Runtime rt = java.lang.Runtime.getRuntime(); + final long free_memory = rt.freeMemory() / 1000000; + final long total_memory = rt.totalMemory() / 1000000; + about.append( "[free memory: " + free_memory + "MB, total memory: " + total_memory + "MB]\n" ); + about.append( "[locale: " + Locale.getDefault() + "]\n" ); + about.append( "References:\n" ); + about.append( Constants.PHYLOXML_REFERENCE_SHORT + "\n" ); + about.append( "For more information & download:\n" ); + about.append( Constants.APTX_WEB_SITE + "\n" ); + about.append( "Comments: " + Constants.AUTHOR_EMAIL ); + JOptionPane.showMessageDialog( null, about, Constants.PRG_NAME, JOptionPane.PLAIN_MESSAGE ); + } + + static void chooseNodeSize( final Options options, final Component parent ) { + final String s = ( String ) JOptionPane.showInputDialog( parent, + "Please enter the default size for node shapes.\n" + + "[current value: " + + options.getDefaultNodeShapeSize() + "]\n", + "Node Shape Size", + JOptionPane.QUESTION_MESSAGE, + null, + null, + options.getDefaultNodeShapeSize() ); + if ( !ForesterUtil.isEmpty( s ) ) { + boolean success = true; + double m = 0.0; + final String m_str = s.trim(); + if ( !ForesterUtil.isEmpty( m_str ) ) { + try { + m = Double.parseDouble( m_str ); + } + catch ( final Exception ex ) { + success = false; + } + } + else { + success = false; + } + if ( success && ( m >= 0.0 ) ) { + final short size = ForesterUtil.roundToShort( m ); + if ( size >= 0.0 ) { + options.setDefaultNodeShapeSize( size ); + } + } + } + } + + static String createCurrentFontDesc( final TreeFontSet tree_font_set ) { + return tree_font_set.getLargeFont().getFamily() + " " + tree_font_set.getLargeFont().getSize(); + } + + static JMenu createMenu( final String title, final Configuration conf ) { + final JMenu jmenu = new JMenu( title ); + if ( !conf.isUseNativeUI() ) { + jmenu.setFont( MainFrame.menu_font ); + jmenu.setBackground( conf.getGuiMenuBackgroundColor() ); + jmenu.setForeground( conf.getGuiMenuTextColor() ); + } + return jmenu; + } + + static JMenuItem customizeMenuItemAsLabel( final JMenuItem label, final Configuration configuration ) { + label.setFont( MainFrame.menu_font.deriveFont( Font.BOLD ) ); + if ( !configuration.isUseNativeUI() ) { + label.setBackground( configuration.getGuiMenuBackgroundColor() ); + label.setForeground( configuration.getGuiMenuTextColor() ); + label.setOpaque( true ); + } + label.setSelected( false ); + label.setEnabled( false ); + return label; + } + + static void cycleNodeFill( final Options op, final TreePanel tree_panel ) { + switch ( op.getDefaultNodeFill() ) { + case GRADIENT: + op.setDefaultNodeFill( NodeFill.SOLID ); + break; + case NONE: + op.setDefaultNodeFill( NodeFill.GRADIENT ); + break; + case SOLID: + op.setDefaultNodeFill( NodeFill.NONE ); + break; + default: + throw new RuntimeException( "unknown fill: " + op.getDefaultNodeFill() ); + } + } + + static void cycleNodeShape( final Options op, final TreePanel tree_panel ) { + switch ( op.getDefaultNodeShape() ) { + case CIRCLE: + op.setDefaultNodeShape( NodeShape.RECTANGLE ); + break; + case RECTANGLE: + op.setDefaultNodeShape( NodeShape.CIRCLE ); + break; + default: + throw new RuntimeException( "unknown shape: " + op.getDefaultNodeShape() ); + } + } + + static void cycleOverview( final Options op, final TreePanel tree_panel ) { + switch ( op.getOvPlacement() ) { + case LOWER_LEFT: + op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_LEFT ); + break; + case LOWER_RIGHT: + op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_LEFT ); + break; + case UPPER_LEFT: + op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.UPPER_RIGHT ); + break; + case UPPER_RIGHT: + op.setOvPlacement( Options.OVERVIEW_PLACEMENT_TYPE.LOWER_RIGHT ); + break; + default: + throw new RuntimeException( "unknown placement: " + op.getOvPlacement() ); + } + if ( tree_panel != null ) { + tree_panel.updateOvSettings(); + } + } + + static void setCycleNodeFillMenuItem( final JMenuItem mi, final Options options ) { + if ( ( options != null ) && ( options.getDefaultNodeFill() != null ) ) { + mi.setText( "Cycle Node Shape Fill Type... (current: " + + options.getDefaultNodeFill().toString().toLowerCase() + ")" ); + } + else { + mi.setText( "Cycle Node Shape Fill Type..." ); + } + } + + static void setCycleNodeShapeMenuItem( final JMenuItem mi, final Options options ) { + if ( ( options != null ) && ( options.getDefaultNodeShape() != null ) ) { + mi.setText( "Cycle Node Shape Fill Type... (current: " + + options.getDefaultNodeShape().toString().toLowerCase() + ")" ); + } + else { + mi.setText( "Cycle Node Shape Fill Type..." ); + } + } + + static void setOvPlacementColorChooseMenuItem( final JMenuItem mi, final Options options ) { + if ( ( options != null ) && ( options.getOvPlacement() != null ) ) { + mi.setText( "Cycle Overview Placement... (current: " + options.getOvPlacement() + ")" ); + } + else { + mi.setText( "Cycle Overview Placement..." ); + } + } + + static void setTextColorChooseMenuItem( final JMenuItem mi, final TreePanel tree_panel ) { + if ( ( tree_panel != null ) && ( tree_panel.getTreeColorSet() != null ) ) { + mi.setText( "Select Color Scheme... (current: " + tree_panel.getTreeColorSet().getCurrentColorSchemeName() + + ")" ); + } + else { + mi.setText( "Select Color Scheme..." ); + } + } + + static void setTextForFontChooserMenuItem( final JMenuItem mi, final String font_desc ) { + mi.setText( "Select Default Font... (current: " + font_desc + ")" ); + } + + static void setTextMinSupportMenuItem( final JMenuItem mi, final Options options, final TreePanel current_tree_panel ) { + if ( ( current_tree_panel == null ) || ( current_tree_panel.getPhylogeny() == null ) ) { + mi.setEnabled( true ); + } + else if ( AptxUtil.isHasAtLeastOneBranchWithSupportValues( current_tree_panel.getPhylogeny() ) ) { + mi.setEnabled( true ); + } + else { + mi.setEnabled( false ); + } + mi.setText( "Enter Min Confidence Value... (current: " + options.getMinConfidenceValue() + ")" ); + } + + static void setTextNodeSizeMenuItem( final JMenuItem mi, final Options options ) { + mi.setText( "Enter Default Node Shape Size... (current: " + options.getDefaultNodeShapeSize() + ")" ); + } + + static void updateOptionsMenuDependingOnPhylogenyType( final MainPanel main_panel, + final JCheckBoxMenuItem scale, + final JCheckBoxMenuItem branch_lengths, + final JRadioButtonMenuItem non_lined_up, + final JRadioButtonMenuItem uniform_clado, + final JRadioButtonMenuItem nonuniform_clado, + final JCheckBoxMenuItem label_direction_cbmi ) { + final TreePanel tree_panel = main_panel.getCurrentTreePanel(); + final ControlPanel control = main_panel.getControlPanel(); + final Options options = main_panel.getOptions(); + scale.setSelected( options.isShowScale() ); + branch_lengths.setSelected( options.isShowBranchLengthValues() ); + // non_lined_up.setSelected( options.isNonLinedUpCladogram() ); + if ( ( tree_panel != null ) && ( !tree_panel.isPhyHasBranchLengths() ) ) { + scale.setSelected( false ); + scale.setEnabled( false ); + branch_lengths.setSelected( false ); + branch_lengths.setEnabled( false ); + } + else if ( ( tree_panel != null ) && !control.isDrawPhylogram() ) { + scale.setSelected( false ); + scale.setEnabled( false ); + branch_lengths.setEnabled( true ); + } + else { + scale.setEnabled( true ); + branch_lengths.setEnabled( true ); + } + if ( ( tree_panel != null ) + && ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.ROUNDED ) + && ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) && ( tree_panel + .getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) ) ) { + branch_lengths.setSelected( false ); + branch_lengths.setEnabled( false ); + } + if ( tree_panel != null ) { + if ( ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) + || ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) { + non_lined_up.setEnabled( false ); + uniform_clado.setEnabled( false ); + nonuniform_clado.setEnabled( false ); + } + else { + non_lined_up.setEnabled( true ); + uniform_clado.setEnabled( true ); + nonuniform_clado.setEnabled( true ); + } + } + else { + if ( ( tree_panel != null ) + && ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE ) && ( tree_panel + .getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ) ) ) { + branch_lengths.setSelected( false ); + branch_lengths.setEnabled( false ); + } + if ( ( tree_panel != null ) + && ( ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) || ( tree_panel + .getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) ) ) { + non_lined_up.setEnabled( false ); + } + else { + // non_lined_up.setSelected( options.isNonLinedUpCladogram() ); + non_lined_up.setEnabled( true ); + } + } + label_direction_cbmi.setEnabled( true ); + if ( tree_panel != null ) { + if ( ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED ) + && ( tree_panel.getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) ) { + label_direction_cbmi.setEnabled( false ); + } + if ( tree_panel.getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR ) { + scale.setSelected( false ); + scale.setEnabled( false ); + } + } + } + + static void updateScreenTextAntialias( final List treepanels ) { + for( final TreePanel tree_panel : treepanels ) { + tree_panel.setTextAntialias(); + } + } +} diff --git a/forester/java/src/org/forester/archaeopteryx/MainFrameApplication.java b/forester/java/src/org/forester/archaeopteryx/MainFrameApplication.java index 6e13820..f37cb7c 100644 --- a/forester/java/src/org/forester/archaeopteryx/MainFrameApplication.java +++ b/forester/java/src/org/forester/archaeopteryx/MainFrameApplication.java @@ -1,2734 +1,2824 @@ -// $Id: -// FORESTER -- software libraries and applications -// for evolutionary biology research and applications. -// -// Copyright (C) 2008-2009 Christian M. Zmasek -// Copyright (C) 2008-2009 Burnham Institute for Medical Research -// Copyright (C) 2003-2007 Ethalinda K.S. Cannon -// All rights reserved -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -// -// Contact: phylosoft @ gmail . com -// WWW: https://sites.google.com/site/cmzmasek/home/software/forester - -package org.forester.archaeopteryx; - -import java.awt.BorderLayout; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.swing.ButtonGroup; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JFileChooser; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.WindowConstants; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.filechooser.FileFilter; -import javax.swing.plaf.synth.SynthLookAndFeel; - -import org.forester.analysis.TaxonomyDataManager; -import org.forester.archaeopteryx.AptxUtil.GraphicsExportType; -import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE; -import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION; -import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE; -import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer; -import org.forester.archaeopteryx.tools.InferenceManager; -import org.forester.archaeopteryx.tools.PhyloInferenceDialog; -import org.forester.archaeopteryx.tools.PhylogeneticInferenceOptions; -import org.forester.archaeopteryx.tools.PhylogeneticInferrer; -import org.forester.archaeopteryx.tools.SequenceDataRetriver; -import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient; -import org.forester.archaeopteryx.webservices.WebservicesManager; -import org.forester.io.parsers.FastaParser; -import org.forester.io.parsers.GeneralMsaParser; -import org.forester.io.parsers.PhylogenyParser; -import org.forester.io.parsers.nexus.NexusPhylogeniesParser; -import org.forester.io.parsers.nhx.NHXParser; -import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION; -import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException; -import org.forester.io.parsers.phyloxml.PhyloXmlParser; -import org.forester.io.parsers.phyloxml.PhyloXmlUtil; -import org.forester.io.parsers.tol.TolParser; -import org.forester.io.parsers.util.ParserUtils; -import org.forester.io.writers.PhylogenyWriter; -import org.forester.io.writers.SequenceWriter; -import org.forester.msa.Msa; -import org.forester.msa.MsaFormatException; -import org.forester.phylogeny.Phylogeny; -import org.forester.phylogeny.PhylogenyMethods; -import org.forester.phylogeny.PhylogenyNode; -import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE; -import org.forester.phylogeny.data.Confidence; -import org.forester.phylogeny.data.Taxonomy; -import org.forester.phylogeny.iterators.PhylogenyNodeIterator; -import org.forester.sequence.Sequence; -import org.forester.util.BasicDescriptiveStatistics; -import org.forester.util.BasicTable; -import org.forester.util.BasicTableParser; -import org.forester.util.DescriptiveStatistics; -import org.forester.util.ForesterUtil; -import org.forester.util.WindowsUtils; - -public final class MainFrameApplication extends MainFrame { - - static final String INFER_ANCESTOR_TAXONOMIES = "Infer Ancestor Taxonomies"; - static final String OBTAIN_DETAILED_TAXONOMIC_INFORMATION = "Obtain Detailed Taxonomic Information"; - private final static int FRAME_X_SIZE = 800; - private final static int FRAME_Y_SIZE = 800; - // Filters for the file-open dialog (classes defined in this file) - private final static NHFilter nhfilter = new NHFilter(); - private final static NHXFilter nhxfilter = new NHXFilter(); - private final static XMLFilter xmlfilter = new XMLFilter(); - private final static TolFilter tolfilter = new TolFilter(); - private final static NexusFilter nexusfilter = new NexusFilter(); - private final static PdfFilter pdffilter = new PdfFilter(); - private final static GraphicsFileFilter graphicsfilefilter = new GraphicsFileFilter(); - private final static MsaFileFilter msafilter = new MsaFileFilter(); - private final static SequencesFileFilter seqsfilter = new SequencesFileFilter(); - private final static DefaultFilter defaultfilter = new DefaultFilter(); - private static final long serialVersionUID = -799735726778865234L; - private final JFileChooser _values_filechooser; - private final JFileChooser _sequences_filechooser; - private final JFileChooser _open_filechooser; - private final JFileChooser _msa_filechooser; - private final JFileChooser _seqs_pi_filechooser; - private final JFileChooser _open_filechooser_for_species_tree; - private final JFileChooser _save_filechooser; - private final JFileChooser _writetopdf_filechooser; - private final JFileChooser _writetographics_filechooser; - // Application-only print menu items - private JMenuItem _print_item; - private JMenuItem _write_to_pdf_item; - private JMenuItem _write_to_jpg_item; - private JMenuItem _write_to_gif_item; - private JMenuItem _write_to_tif_item; - private JMenuItem _write_to_png_item; - private JMenuItem _write_to_bmp_item; - private File _current_dir; - private ButtonGroup _radio_group_1; - private ButtonGroup _radio_group_2; - // Others: - double _min_not_collapse = Constants.MIN_NOT_COLLAPSE_DEFAULT; - // Phylogeny Inference menu - private JMenu _inference_menu; - private JMenuItem _inference_from_msa_item; - private JMenuItem _inference_from_seqs_item; - // Phylogeny Inference - private PhylogeneticInferenceOptions _phylogenetic_inference_options = null; - private Msa _msa = null; - private File _msa_file = null; - private List _seqs = null; - private File _seqs_file = null; - JMenuItem _read_values_jmi; - JMenuItem _read_seqs_jmi; - - private MainFrameApplication( final Phylogeny[] phys, final Configuration config ) { - _configuration = config; - if ( _configuration == null ) { - throw new IllegalArgumentException( "configuration is null" ); - } - setVisible( false ); - setOptions( Options.createInstance( _configuration ) ); - _mainpanel = new MainPanel( _configuration, this ); - _open_filechooser = null; - _open_filechooser_for_species_tree = null; - _save_filechooser = null; - _writetopdf_filechooser = null; - _writetographics_filechooser = null; - _msa_filechooser = null; - _seqs_pi_filechooser = null; - _values_filechooser = null; - _sequences_filechooser = null; - _jmenubar = new JMenuBar(); - buildFileMenu(); - buildTypeMenu(); - _contentpane = getContentPane(); - _contentpane.setLayout( new BorderLayout() ); - _contentpane.add( _mainpanel, BorderLayout.CENTER ); - // App is this big - setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE ); - // The window listener - setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); - addWindowListener( new WindowAdapter() { - - @Override - public void windowClosing( final WindowEvent e ) { - exit(); - } - } ); - // setVisible( true ); - if ( ( phys != null ) && ( phys.length > 0 ) ) { - AptxUtil.addPhylogeniesToTabs( phys, "", null, _configuration, _mainpanel ); - validate(); - getMainPanel().getControlPanel().showWholeAll(); - getMainPanel().getControlPanel().showWhole(); - } - //activateSaveAllIfNeeded(); - // ...and its children - _contentpane.repaint(); - } - - private MainFrameApplication( final Phylogeny[] phys, final Configuration config, final String title ) { - this( phys, config, title, null ); - } - - private MainFrameApplication( final Phylogeny[] phys, - final Configuration config, - final String title, - final File current_dir ) { - super(); - _configuration = config; - if ( _configuration == null ) { - throw new IllegalArgumentException( "configuration is null" ); - } - try { - boolean synth_exception = false; - if ( Constants.__SYNTH_LF ) { - try { - final SynthLookAndFeel synth = new SynthLookAndFeel(); - synth.load( MainFrameApplication.class.getResourceAsStream( "/resources/synth_look_and_feel_1.xml" ), - MainFrameApplication.class ); - UIManager.setLookAndFeel( synth ); - } - catch ( final Exception ex ) { - synth_exception = true; - ForesterUtil.printWarningMessage( Constants.PRG_NAME, - "could not create synth look and feel: " - + ex.getLocalizedMessage() ); - } - } - if ( !Constants.__SYNTH_LF || synth_exception ) { - if ( _configuration.isUseNativeUI() ) { - UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); - } - else { - UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() ); - } - } - //UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" ); - } - catch ( final UnsupportedLookAndFeelException e ) { - AptxUtil.dieWithSystemError( "unsupported look and feel: " + e.toString() ); - } - catch ( final ClassNotFoundException e ) { - AptxUtil.dieWithSystemError( "class not found exception: " + e.toString() ); - } - catch ( final InstantiationException e ) { - AptxUtil.dieWithSystemError( "instantiation exception: " + e.toString() ); - } - catch ( final IllegalAccessException e ) { - AptxUtil.dieWithSystemError( "illegal access exception: " + e.toString() ); - } - if ( ( current_dir != null ) && current_dir.canRead() && current_dir.isDirectory() ) { - setCurrentDir( current_dir ); - } - // hide until everything is ready - setVisible( false ); - setOptions( Options.createInstance( _configuration ) ); - setInferenceManager( InferenceManager.createInstance( _configuration ) ); - setPhylogeneticInferenceOptions( PhylogeneticInferenceOptions.createInstance( _configuration ) ); - // _textframe = null; #~~~~ - // set title - setTitle( Constants.PRG_NAME + " " + Constants.VERSION + " (" + Constants.PRG_DATE + ")" ); - _mainpanel = new MainPanel( _configuration, this ); - // The file dialogs - _open_filechooser = new JFileChooser(); - _open_filechooser.setCurrentDirectory( new File( "." ) ); - _open_filechooser.setMultiSelectionEnabled( false ); - _open_filechooser.addChoosableFileFilter( MainFrameApplication.xmlfilter ); - _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhxfilter ); - _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter ); - _open_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter ); - _open_filechooser.addChoosableFileFilter( MainFrameApplication.tolfilter ); - _open_filechooser.addChoosableFileFilter( _open_filechooser.getAcceptAllFileFilter() ); - _open_filechooser.setFileFilter( MainFrameApplication.defaultfilter ); - _open_filechooser_for_species_tree = new JFileChooser(); - _open_filechooser_for_species_tree.setCurrentDirectory( new File( "." ) ); - _open_filechooser_for_species_tree.setMultiSelectionEnabled( false ); - _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.xmlfilter ); - _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.tolfilter ); - _open_filechooser_for_species_tree.setFileFilter( MainFrameApplication.xmlfilter ); - _save_filechooser = new JFileChooser(); - _save_filechooser.setCurrentDirectory( new File( "." ) ); - _save_filechooser.setMultiSelectionEnabled( false ); - _save_filechooser.setFileFilter( MainFrameApplication.xmlfilter ); - _save_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter ); - _save_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter ); - _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() ); - _writetopdf_filechooser = new JFileChooser(); - _writetopdf_filechooser.addChoosableFileFilter( MainFrameApplication.pdffilter ); - _writetographics_filechooser = new JFileChooser(); - _writetographics_filechooser.addChoosableFileFilter( MainFrameApplication.graphicsfilefilter ); - // Msa: - _msa_filechooser = new JFileChooser(); - _msa_filechooser.setName( "Read Multiple Sequence Alignment File" ); - _msa_filechooser.setCurrentDirectory( new File( "." ) ); - _msa_filechooser.setMultiSelectionEnabled( false ); - _msa_filechooser.addChoosableFileFilter( _msa_filechooser.getAcceptAllFileFilter() ); - _msa_filechooser.addChoosableFileFilter( MainFrameApplication.msafilter ); - // Seqs: - _seqs_pi_filechooser = new JFileChooser(); - _seqs_pi_filechooser.setName( "Read Sequences File" ); - _seqs_pi_filechooser.setCurrentDirectory( new File( "." ) ); - _seqs_pi_filechooser.setMultiSelectionEnabled( false ); - _seqs_pi_filechooser.addChoosableFileFilter( _seqs_pi_filechooser.getAcceptAllFileFilter() ); - _seqs_pi_filechooser.addChoosableFileFilter( MainFrameApplication.seqsfilter ); - // Expression - _values_filechooser = new JFileChooser(); - _values_filechooser.setCurrentDirectory( new File( "." ) ); - _values_filechooser.setMultiSelectionEnabled( false ); - // Sequences - _sequences_filechooser = new JFileChooser(); - _sequences_filechooser.setCurrentDirectory( new File( "." ) ); - _sequences_filechooser.setMultiSelectionEnabled( false ); - // build the menu bar - _jmenubar = new JMenuBar(); - if ( !_configuration.isUseNativeUI() ) { - _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); - } - buildFileMenu(); - if ( Constants.__ALLOW_PHYLOGENETIC_INFERENCE ) { - buildPhylogeneticInferenceMenu(); - } - buildAnalysisMenu(); - buildToolsMenu(); - buildViewMenu(); - buildFontSizeMenu(); - buildOptionsMenu(); - buildTypeMenu(); - buildHelpMenu(); - setJMenuBar( _jmenubar ); - _jmenubar.add( _help_jmenu ); - _contentpane = getContentPane(); - _contentpane.setLayout( new BorderLayout() ); - _contentpane.add( _mainpanel, BorderLayout.CENTER ); - // App is this big - setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE ); - // addWindowFocusListener( new WindowAdapter() { - // - // @Override - // public void windowGainedFocus( WindowEvent e ) { - // requestFocusInWindow(); - // } - // } ); - // The window listener - setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); - addWindowListener( new WindowAdapter() { - - @Override - public void windowClosing( final WindowEvent e ) { - if ( isUnsavedDataPresent() ) { - final int r = JOptionPane.showConfirmDialog( null, - "Exit despite potentially unsaved changes?", - "Exit?", - JOptionPane.YES_NO_OPTION ); - if ( r != JOptionPane.YES_OPTION ) { - return; - } - } - else { - final int r = JOptionPane.showConfirmDialog( null, - "Exit Archaeopteryx?", - "Exit?", - JOptionPane.YES_NO_OPTION ); - if ( r != JOptionPane.YES_OPTION ) { - return; - } - } - exit(); - } - } ); - // The component listener - addComponentListener( new ComponentAdapter() { - - @Override - public void componentResized( final ComponentEvent e ) { - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel() - .getWidth(), - _mainpanel.getCurrentTreePanel() - .getHeight(), - getOptions().isAllowFontSizeChange() ); - } - } - } ); - requestFocusInWindow(); - // addKeyListener( this ); - setVisible( true ); - if ( ( phys != null ) && ( phys.length > 0 ) ) { - AptxUtil.addPhylogeniesToTabs( phys, title, null, _configuration, _mainpanel ); - validate(); - getMainPanel().getControlPanel().showWholeAll(); - getMainPanel().getControlPanel().showWhole(); - } - activateSaveAllIfNeeded(); - // ...and its children - _contentpane.repaint(); - System.gc(); - } - - private MainFrameApplication( final Phylogeny[] phys, final String config_file, final String title ) { - // Reads the config file (false, false => not url, not applet): - this( phys, new Configuration( config_file, false, false, true ), title ); - } - - @Override - public void actionPerformed( final ActionEvent e ) { - try { - super.actionPerformed( e ); - final Object o = e.getSource(); - // Handle app-specific actions here: - if ( o == _open_item ) { - readPhylogeniesFromFile(); - } - else if ( o == _save_item ) { - writeToFile( _mainpanel.getCurrentPhylogeny() ); - // If subtree currently displayed, save it, instead of complete - // tree. - } - else if ( o == _new_item ) { - newTree(); - } - else if ( o == _save_all_item ) { - writeAllToFile(); - } - else if ( o == _close_item ) { - closeCurrentPane(); - } - else if ( o == _write_to_pdf_item ) { - writeToPdf( _mainpanel.getCurrentPhylogeny() ); - } - else if ( o == _write_to_jpg_item ) { - writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.JPG ); - } - else if ( o == _write_to_png_item ) { - writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.PNG ); - } - else if ( o == _write_to_gif_item ) { - writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.GIF ); - } - else if ( o == _write_to_tif_item ) { - writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.TIFF ); - } - else if ( o == _write_to_bmp_item ) { - writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.BMP ); - } - else if ( o == _print_item ) { - print(); - } - else if ( o == _load_species_tree_item ) { - readSpeciesTreeFromFile(); - } - else if ( o == _lineage_inference ) { - if ( isSubtreeDisplayed() ) { - JOptionPane.showMessageDialog( this, - "Subtree is shown.", - "Cannot infer ancestral taxonomies", - JOptionPane.ERROR_MESSAGE ); - return; - } - executeLineageInference(); - } - else if ( o == _obtain_detailed_taxonomic_information_jmi ) { - if ( isSubtreeDisplayed() ) { - return; - } - obtainDetailedTaxonomicInformation(); - } - else if ( o == _obtain_detailed_taxonomic_information_deleting_jmi ) { - if ( isSubtreeDisplayed() ) { - return; - } - obtainDetailedTaxonomicInformationDelete(); - } - else if ( o == _obtain_seq_information_jmi ) { - obtainSequenceInformation(); - } - else if ( o == _read_values_jmi ) { - if ( isSubtreeDisplayed() ) { - return; - } - addExpressionValuesFromFile(); - } - else if ( o == _read_seqs_jmi ) { - if ( isSubtreeDisplayed() ) { - return; - } - addSequencesFromFile(); - } - else if ( o == _move_node_names_to_tax_sn_jmi ) { - moveNodeNamesToTaxSn(); - } - else if ( o == _move_node_names_to_seq_names_jmi ) { - moveNodeNamesToSeqNames(); - } - else if ( o == _extract_tax_code_from_node_names_jmi ) { - extractTaxDataFromNodeNames(); - } - else if ( o == _graphics_export_visible_only_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _antialias_print_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _print_black_and_white_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _print_using_actual_size_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _graphics_export_using_actual_size_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _print_size_mi ) { - choosePrintSize(); - } - else if ( o == _choose_pdf_width_mi ) { - choosePdfWidth(); - } - else if ( o == _internal_number_are_confidence_for_nh_parsing_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _replace_underscores_cbmi ) { - if ( ( _extract_taxonomy_no_rbmi != null ) && !_extract_taxonomy_no_rbmi.isSelected() ) { - _extract_taxonomy_no_rbmi.setSelected( true ); - } - updateOptions( getOptions() ); - } - else if ( o == _allow_errors_in_distance_to_parent_cbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _collapse_below_threshold ) { - if ( isSubtreeDisplayed() ) { - return; - } - collapseBelowThreshold(); - } - else if ( ( o == _extract_taxonomy_pfam_strict_rbmi ) || ( o == _extract_taxonomy_pfam_relaxed_rbmi ) - || ( o == _extract_taxonomy_agressive_rbmi ) ) { - if ( _replace_underscores_cbmi != null ) { - _replace_underscores_cbmi.setSelected( false ); - } - updateOptions( getOptions() ); - } - else if ( o == _extract_taxonomy_no_rbmi ) { - updateOptions( getOptions() ); - } - else if ( o == _inference_from_msa_item ) { - executePhyleneticInference( false ); - } - else if ( o == _inference_from_seqs_item ) { - executePhyleneticInference( true ); - } - _contentpane.repaint(); - } - catch ( final Exception ex ) { - AptxUtil.unexpectedException( ex ); - } - catch ( final Error err ) { - AptxUtil.unexpectedError( err ); - } - } - - public void end() { - _mainpanel.terminate(); - _contentpane.removeAll(); - setVisible( false ); - dispose(); - } - - @Override - public MainPanel getMainPanel() { - return _mainpanel; - } - - public Msa getMsa() { - return _msa; - } - - public File getMsaFile() { - return _msa_file; - } - - public List getSeqs() { - return _seqs; - } - - public File getSeqsFile() { - return _seqs_file; - } - - public void readMsaFromFile() { - // Set an initial directory if none set yet - final File my_dir = getCurrentDir(); - _msa_filechooser.setMultiSelectionEnabled( false ); - // Open file-open dialog and set current directory - if ( my_dir != null ) { - _msa_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _msa_filechooser.showOpenDialog( _contentpane ); - // All done: get the msa - final File file = _msa_filechooser.getSelectedFile(); - setCurrentDir( _msa_filechooser.getCurrentDirectory() ); - if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { - setMsaFile( null ); - setMsa( null ); - Msa msa = null; - try { - final InputStream is = new FileInputStream( file ); - if ( FastaParser.isLikelyFasta( file ) ) { - msa = FastaParser.parseMsa( is ); - } - else { - msa = GeneralMsaParser.parse( is ); - } - } - catch ( final MsaFormatException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Multiple sequence alignment format error", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final IOException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Failed to read multiple sequence alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final IllegalArgumentException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Unexpected error during reading of multiple sequence alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final Exception e ) { - setArrowCursor(); - e.printStackTrace(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Unexpected error during reading of multiple sequence alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence alignment is empty", - "Illegal Multiple Sequence Alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( msa.getNumberOfSequences() < 4 ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence alignment needs to contain at least 3 sequences", - "Illegal multiple sequence alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( msa.getLength() < 2 ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence alignment needs to contain at least 2 residues", - "Illegal multiple sequence alignment", - JOptionPane.ERROR_MESSAGE ); - return; - } - System.gc(); - setMsaFile( _msa_filechooser.getSelectedFile() ); - setMsa( msa ); - } - } - - public void readSeqsFromFileforPI() { - // Set an initial directory if none set yet - final File my_dir = getCurrentDir(); - _seqs_pi_filechooser.setMultiSelectionEnabled( false ); - // Open file-open dialog and set current directory - if ( my_dir != null ) { - _seqs_pi_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _seqs_pi_filechooser.showOpenDialog( _contentpane ); - // All done: get the seqs - final File file = _seqs_pi_filechooser.getSelectedFile(); - setCurrentDir( _seqs_pi_filechooser.getCurrentDirectory() ); - if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { - setSeqsFile( null ); - setSeqs( null ); - List seqs = null; - try { - if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) { - seqs = FastaParser.parse( new FileInputStream( file ) ); - for( final Sequence seq : seqs ) { - System.out.println( SequenceWriter.toFasta( seq, 60 ) ); - } - } - else { - //TODO error - } - } - catch ( final MsaFormatException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Multiple sequence file format error", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final IOException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Failed to read multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final IllegalArgumentException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Unexpected error during reading of multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final Exception e ) { - setArrowCursor(); - e.printStackTrace(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Unexpected error during reading of multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( ( seqs == null ) || ( seqs.size() < 1 ) ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence file is empty", - "Illegal multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( seqs.size() < 4 ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence file needs to contain at least 3 sequences", - "Illegal multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - // if ( msa.getLength() < 2 ) { - // JOptionPane.showMessageDialog( this, - // "Multiple sequence alignment needs to contain at least 2 residues", - // "Illegal multiple sequence file", - // JOptionPane.ERROR_MESSAGE ); - // return; - // } - System.gc(); - setSeqsFile( _seqs_pi_filechooser.getSelectedFile() ); - setSeqs( seqs ); - } - } - - void buildAnalysisMenu() { - _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() ); - _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) ); - _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (GSDI with re-rooting)" ) ); - _analysis_menu.add( _load_species_tree_item = new JMenuItem( "Load Species Tree..." ) ); - customizeJMenuItem( _gsdi_item ); - customizeJMenuItem( _gsdir_item ); - customizeJMenuItem( _load_species_tree_item ); - _analysis_menu.addSeparator(); - _analysis_menu.add( _lineage_inference = new JMenuItem( INFER_ANCESTOR_TAXONOMIES ) ); - customizeJMenuItem( _lineage_inference ); - _lineage_inference.setToolTipText( "Inference of ancestor taxonomies/lineages" ); - _jmenubar.add( _analysis_menu ); - } - - @Override - void buildFileMenu() { - _file_jmenu = MainFrame.createMenu( "File", getConfiguration() ); - _file_jmenu.add( _open_item = new JMenuItem( "Read Tree from File..." ) ); - _file_jmenu.addSeparator(); - final WebservicesManager webservices_manager = WebservicesManager.getInstance(); - _load_phylogeny_from_webservice_menu_items = new JMenuItem[ webservices_manager - .getAvailablePhylogeniesWebserviceClients().size() ]; - for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) { - final PhylogeniesWebserviceClient client = webservices_manager.getAvailablePhylogeniesWebserviceClient( i ); - _load_phylogeny_from_webservice_menu_items[ i ] = new JMenuItem( client.getMenuName() ); - _file_jmenu.add( _load_phylogeny_from_webservice_menu_items[ i ] ); - } - if ( getConfiguration().isEditable() ) { - _file_jmenu.addSeparator(); - _file_jmenu.add( _new_item = new JMenuItem( "New" ) ); - _new_item.setToolTipText( "to create a new tree with one node, as source for manual tree construction" ); - } - _file_jmenu.addSeparator(); - _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) ); - _file_jmenu.add( _save_all_item = new JMenuItem( "Save All Trees As..." ) ); - _save_all_item.setToolTipText( "Write all phylogenies to one file." ); - _save_all_item.setEnabled( false ); - _file_jmenu.addSeparator(); - _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) ); - if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) { - _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) ); - } - _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) ); - _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) ); - if ( AptxUtil.canWriteFormat( "gif" ) ) { - _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) ); - } - if ( AptxUtil.canWriteFormat( "bmp" ) ) { - _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) ); - } - _file_jmenu.addSeparator(); - _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) ); - _file_jmenu.addSeparator(); - _file_jmenu.add( _close_item = new JMenuItem( "Close Tab" ) ); - _close_item.setToolTipText( "To close the current pane." ); - _close_item.setEnabled( true ); - _file_jmenu.addSeparator(); - _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) ); - // For print in color option item - customizeJMenuItem( _open_item ); - _open_item - .setFont( new Font( _open_item.getFont().getFontName(), Font.BOLD, _open_item.getFont().getSize() + 4 ) ); - for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) { - customizeJMenuItem( _load_phylogeny_from_webservice_menu_items[ i ] ); - } - customizeJMenuItem( _save_item ); - if ( getConfiguration().isEditable() ) { - customizeJMenuItem( _new_item ); - } - customizeJMenuItem( _close_item ); - customizeJMenuItem( _save_all_item ); - customizeJMenuItem( _write_to_pdf_item ); - customizeJMenuItem( _write_to_png_item ); - customizeJMenuItem( _write_to_jpg_item ); - customizeJMenuItem( _write_to_gif_item ); - customizeJMenuItem( _write_to_tif_item ); - customizeJMenuItem( _write_to_bmp_item ); - customizeJMenuItem( _print_item ); - customizeJMenuItem( _exit_item ); - _jmenubar.add( _file_jmenu ); - } - - void buildOptionsMenu() { - _options_jmenu = MainFrame.createMenu( OPTIONS_HEADER, getConfiguration() ); - _options_jmenu.addChangeListener( new ChangeListener() { - - @Override - public void stateChanged( final ChangeEvent e ) { - MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() ); - MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() ); - MainFrame - .setTextMinSupportMenuItem( _choose_minimal_confidence_mi, getOptions(), getCurrentTreePanel() ); - MainFrame.setTextForFontChooserMenuItem( _choose_font_mi, MainFrame - .createCurrentFontDesc( getMainPanel().getTreeFontSet() ) ); - setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() ); - setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() ); - MainFrame.updateOptionsMenuDependingOnPhylogenyType( getMainPanel(), - _show_scale_cbmi, - _show_branch_length_values_cbmi, - _non_lined_up_cladograms_rbmi, - _uniform_cladograms_rbmi, - _ext_node_dependent_cladogram_rbmi, - _label_direction_cbmi ); - MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() ); - MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() ); - MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() ); - } - } ); - _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( DISPLAY_SUBHEADER ), getConfiguration() ) ); - _options_jmenu - .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) ); - _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) ); - _options_jmenu.add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( NON_LINED_UP_CLADOGRAMS_LABEL ) ); - _radio_group_1 = new ButtonGroup(); - _radio_group_1.add( _ext_node_dependent_cladogram_rbmi ); - _radio_group_1.add( _uniform_cladograms_rbmi ); - _radio_group_1.add( _non_lined_up_cladograms_rbmi ); - /////// - _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( SHOW_OVERVIEW_LABEL ) ); - _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( DISPLAY_SCALE_LABEL ) ); - _options_jmenu - .add( _show_branch_length_values_cbmi = new JCheckBoxMenuItem( DISPLAY_BRANCH_LENGTH_VALUES_LABEL ) ); - _options_jmenu - .add( _show_default_node_shapes_internal_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_INT ) ); - _options_jmenu - .add( _show_default_node_shapes_external_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_EXT ) ); - if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) { - _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( SHOW_DOMAIN_LABELS_LABEL ) ); - } - _options_jmenu.add( _show_annotation_ref_source = new JCheckBoxMenuItem( SHOW_ANN_REF_SOURCE_LABEL ) ); - _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( SHOW_CONF_STDDEV_LABEL ) ); - _options_jmenu.add( _color_by_taxonomic_group_cbmi = new JCheckBoxMenuItem( COLOR_BY_TAXONOMIC_GROUP ) ); - _options_jmenu.add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( COLOR_LABELS_LABEL ) ); - _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP ); - _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( ABBREV_SN_LABEL ) ); - _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( LABEL_DIRECTION_LABEL ) ); - _label_direction_cbmi.setToolTipText( LABEL_DIRECTION_TIP ); - _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( SCREEN_ANTIALIAS_LABEL ) ); - _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( BG_GRAD_LABEL ) ); - _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) ); - _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) ); - _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) ); - _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) ); - _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) ); - _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) ); - _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) ); - /////// - _options_jmenu.addSeparator(); - _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( SEARCH_SUBHEADER ), getConfiguration() ) ); - _options_jmenu.add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( SEARCH_CASE_SENSITIVE_LABEL ) ); - _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( SEARCH_TERMS_ONLY_LABEL ) ); - _options_jmenu.add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( INVERSE_SEARCH_RESULT_LABEL ) ); - _options_jmenu.addSeparator(); - _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ), - getConfiguration() ) ); - _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) ); - _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) ); - _options_jmenu - .add( _print_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PDF export and Printing" ) ); - _options_jmenu - .add( _graphics_export_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PNG, JPG, and GIF export" ) ); - _options_jmenu - .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) ); - _options_jmenu.add( _print_size_mi = new JMenuItem( "" ) ); - _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) ); - _options_jmenu.addSeparator(); - _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/NHX/Nexus Input:" ), getConfiguration() ) ); - _options_jmenu - .add( _internal_number_are_confidence_for_nh_parsing_cbmi = new JCheckBoxMenuItem( "Internal Node Names are Confidence Values" ) ); - _options_jmenu.add( _replace_underscores_cbmi = new JCheckBoxMenuItem( "Replace Underscores with Spaces" ) ); - _options_jmenu - .add( _allow_errors_in_distance_to_parent_cbmi = new JCheckBoxMenuItem( "Ignore Distance Values Format Errors" ) ); - // - _options_jmenu.add( _extract_taxonomy_no_rbmi = new JRadioButtonMenuItem( "No Taxonomy Extraction" ) ); - _options_jmenu - .add( _extract_taxonomy_pfam_strict_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style Node Names" ) ); - _options_jmenu - .add( _extract_taxonomy_pfam_relaxed_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style like Node Names" ) ); - _options_jmenu - .add( _extract_taxonomy_agressive_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids/Scientific Names from Node Names" ) ); - _extract_taxonomy_pfam_strict_rbmi - .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"BCL2_MOUSE/123-304\" or \"BCL2_10090/123-304\"" ); - _extract_taxonomy_pfam_relaxed_rbmi - .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"bax_MOUSE\" or \"bax_10090\"" ); - _extract_taxonomy_agressive_rbmi - .setToolTipText( "To extract taxonomy codes/ids or scientific names from node names in the form of e.g. \"MOUSE\" or \"10090\" or \"xyz_Nematostella_vectensis\"" ); - _radio_group_2 = new ButtonGroup(); - _radio_group_2.add( _extract_taxonomy_no_rbmi ); - _radio_group_2.add( _extract_taxonomy_pfam_strict_rbmi ); - _radio_group_2.add( _extract_taxonomy_pfam_relaxed_rbmi ); - _radio_group_2.add( _extract_taxonomy_agressive_rbmi ); - // - _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/Nexus Output:" ), getConfiguration() ) ); - _options_jmenu - .add( _use_brackets_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_BRACKETS_FOR_CONF_IN_NH_LABEL ) ); - _use_brackets_for_conf_in_nh_export_cbmi - .setToolTipText( "e.g. \"0.1[90]\" for a branch with support 90 and a length of 0.1" ); - _options_jmenu - .add( _use_internal_names_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL ) ); - customizeJMenuItem( _choose_font_mi ); - customizeJMenuItem( _choose_minimal_confidence_mi ); - customizeJMenuItem( _switch_colors_mi ); - customizeJMenuItem( _print_size_mi ); - customizeJMenuItem( _choose_pdf_width_mi ); - customizeJMenuItem( _overview_placment_mi ); - customizeCheckBoxMenuItem( _show_default_node_shapes_external_cbmi, getOptions() - .isShowDefaultNodeShapesExternal() ); - customizeCheckBoxMenuItem( _show_default_node_shapes_internal_cbmi, getOptions() - .isShowDefaultNodeShapesInternal() ); - customizeJMenuItem( _cycle_node_shape_mi ); - customizeJMenuItem( _cycle_node_fill_mi ); - customizeJMenuItem( _choose_node_size_mi ); - customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch, getOptions().isColorLabelsSameAsParentBranch() ); - customizeCheckBoxMenuItem( _color_by_taxonomic_group_cbmi, getOptions().isColorByTaxonomicGroup() ); - customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() ); - customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() ); - customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() ); - customizeCheckBoxMenuItem( _show_annotation_ref_source, getOptions().isShowAnnotationRefSource() ); - customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() ); - customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() ); - customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() ); - customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi, - getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP ); - customizeRadioButtonMenuItem( _uniform_cladograms_rbmi, - getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP ); - customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi, - getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP ); - customizeCheckBoxMenuItem( _show_branch_length_values_cbmi, getOptions().isShowBranchLengthValues() ); - customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() ); - customizeCheckBoxMenuItem( _label_direction_cbmi, - getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL ); - customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() ); - customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() ); - customizeCheckBoxMenuItem( _internal_number_are_confidence_for_nh_parsing_cbmi, getOptions() - .isInternalNumberAreConfidenceForNhParsing() ); - customizeRadioButtonMenuItem( _extract_taxonomy_no_rbmi, - getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.NO ); - customizeRadioButtonMenuItem( _extract_taxonomy_pfam_strict_rbmi, - getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ); - customizeRadioButtonMenuItem( _extract_taxonomy_pfam_relaxed_rbmi, - getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED ); - customizeRadioButtonMenuItem( _extract_taxonomy_agressive_rbmi, - getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.AGGRESSIVE ); - customizeCheckBoxMenuItem( _replace_underscores_cbmi, getOptions().isReplaceUnderscoresInNhParsing() ); - customizeCheckBoxMenuItem( _allow_errors_in_distance_to_parent_cbmi, getOptions() - .isReplaceUnderscoresInNhParsing() ); - customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() ); - customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() ); - customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() ); - customizeCheckBoxMenuItem( _print_using_actual_size_cbmi, getOptions().isPrintUsingActualSize() ); - customizeCheckBoxMenuItem( _graphics_export_using_actual_size_cbmi, getOptions() - .isGraphicsExportUsingActualSize() ); - customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() ); - customizeCheckBoxMenuItem( _use_brackets_for_conf_in_nh_export_cbmi, getOptions() - .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ); - customizeCheckBoxMenuItem( _use_internal_names_for_conf_in_nh_export_cbmi, getOptions() - .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ); - _jmenubar.add( _options_jmenu ); - } - - void buildPhylogeneticInferenceMenu() { - final InferenceManager im = getInferenceManager(); - _inference_menu = MainFrame.createMenu( "Inference", getConfiguration() ); - _inference_menu.add( _inference_from_msa_item = new JMenuItem( "From Multiple Sequence Alignment..." ) ); - customizeJMenuItem( _inference_from_msa_item ); - _inference_from_msa_item.setToolTipText( "Basic phylogenetic inference from MSA" ); - if ( im.canDoMsa() ) { - _inference_menu.add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences..." ) ); - customizeJMenuItem( _inference_from_seqs_item ); - _inference_from_seqs_item - .setToolTipText( "Basic phylogenetic inference including multiple sequence alignment" ); - } - else { - _inference_menu - .add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences (no program found)" ) ); - customizeJMenuItem( _inference_from_seqs_item ); - _inference_from_seqs_item.setEnabled( false ); - } - _jmenubar.add( _inference_menu ); - } - - void buildToolsMenu() { - _tools_menu = createMenu( "Tools", getConfiguration() ); - _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) ); - customizeJMenuItem( _confcolor_item ); - _tools_menu.add( _color_rank_jmi = new JMenuItem( "Colorize Subtrees via Taxonomic Rank" ) ); - customizeJMenuItem( _color_rank_jmi ); - _color_rank_jmi.setToolTipText( "for example, at \"Class\" level, colorize mammal specific subtree red" ); - _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) ); - customizeJMenuItem( _taxcolor_item ); - _tools_menu.addSeparator(); - _tools_menu.add( _remove_visual_styles_item = new JMenuItem( "Delete All Visual Styles From Nodes" ) ); - _remove_visual_styles_item - .setToolTipText( "To remove all node visual styles (fonts, colors) from the current phylogeny." ); - customizeJMenuItem( _remove_visual_styles_item ); - _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete All Colors From Branches" ) ); - _remove_branch_color_item.setToolTipText( "To remove all branch color values from the current phylogeny." ); - customizeJMenuItem( _remove_branch_color_item ); - _tools_menu.addSeparator(); - _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) ); - customizeJMenuItem( _annotate_item ); - _tools_menu.addSeparator(); - _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) ); - customizeJMenuItem( _midpoint_root_item ); - _tools_menu.addSeparator(); - _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) ); - customizeJMenuItem( _collapse_species_specific_subtrees ); - _tools_menu - .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) ); - customizeJMenuItem( _collapse_below_threshold ); - _collapse_below_threshold - .setToolTipText( "To collapse branches with confidence values below a threshold into multifurcations (in the case of multiple confidences per branch: without at least one confidence value above a threshold)" ); - _tools_menu.addSeparator(); - _tools_menu - .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Data from Node Names" ) ); - customizeJMenuItem( _extract_tax_code_from_node_names_jmi ); - _extract_tax_code_from_node_names_jmi - .setToolTipText( "To extract SwissProt/Uniprot taxonomic codes (mnemonics) from nodes names in the form of 'xyz_CAEEL', Uniprot/NCBI identifiers form of 'xyz_6239', or scientific names form of 'xyz_Caenorhabditis_elegans'" ); - _tools_menu - .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) ); - customizeJMenuItem( _move_node_names_to_tax_sn_jmi ); - _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" ); - _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) ); - customizeJMenuItem( _move_node_names_to_seq_names_jmi ); - _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" ); - _tools_menu.addSeparator(); - _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) ); - customizeJMenuItem( _obtain_seq_information_jmi ); - _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" ); - _tools_menu - .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) ); - customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi ); - _obtain_detailed_taxonomic_information_jmi - .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" ); - _tools_menu - .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) ); - customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi ); - _obtain_detailed_taxonomic_information_deleting_jmi - .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" ); - _tools_menu.addSeparator(); - _tools_menu.add( _read_values_jmi = new JMenuItem( "Attach Vector/Expression Values" ) ); - customizeJMenuItem( _read_values_jmi ); - _read_values_jmi.setToolTipText( "To attach vector (e.g. gene expression) values to tree nodes (beta)" ); - _jmenubar.add( _tools_menu ); - _tools_menu.add( _read_seqs_jmi = new JMenuItem( "Attach Molecular Sequences" ) ); - customizeJMenuItem( _read_seqs_jmi ); - _read_seqs_jmi - .setToolTipText( "To attach molecular sequences to tree nodes (from Fasta-formatted file) (beta)" ); - _jmenubar.add( _tools_menu ); - } - - @Override - void close() { - if ( isUnsavedDataPresent() ) { - final int r = JOptionPane.showConfirmDialog( this, - "Exit despite potentially unsaved changes?", - "Exit?", - JOptionPane.YES_NO_OPTION ); - if ( r != JOptionPane.YES_OPTION ) { - return; - } - } - exit(); - } - - void executeLineageInference() { - if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) { - return; - } - if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) { - JOptionPane.showMessageDialog( this, - "Phylogeny is not rooted.", - "Cannot infer ancestral taxonomies", - JOptionPane.ERROR_MESSAGE ); - return; - } - final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this, - _mainpanel.getCurrentTreePanel(), - _mainpanel.getCurrentPhylogeny() - .copy() ); - new Thread( inferrer ).start(); - } - - void exit() { - removeAllTextFrames(); - _mainpanel.terminate(); - _contentpane.removeAll(); - setVisible( false ); - dispose(); - System.exit( 0 ); - } - - void setMsa( final Msa msa ) { - _msa = msa; - } - - void setMsaFile( final File msa_file ) { - _msa_file = msa_file; - } - - void setSeqs( final List seqs ) { - _seqs = seqs; - } - - void setSeqsFile( final File seqs_file ) { - _seqs_file = seqs_file; - } - - void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) { - _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(), - _mainpanel.getCurrentTreePanel().getHeight(), - true ); - String file_written_to = ""; - boolean error = false; - try { - file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name, - _mainpanel.getCurrentTreePanel().getWidth(), - _mainpanel.getCurrentTreePanel().getHeight(), - _mainpanel.getCurrentTreePanel(), - _mainpanel.getControlPanel(), - type, - getOptions() ); - } - catch ( final IOException e ) { - error = true; - JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE ); - } - if ( !error ) { - if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) { - JOptionPane.showMessageDialog( this, - "Wrote image to: " + file_written_to, - "Graphics Export", - JOptionPane.INFORMATION_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, - "There was an unknown problem when attempting to write to an image file: \"" - + file_name + "\"", - "Error", - JOptionPane.ERROR_MESSAGE ); - } - } - _contentpane.repaint(); - } - - private void addExpressionValuesFromFile() { - if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) { - JOptionPane.showMessageDialog( this, - "Need to load evolutionary tree first", - "Can Not Read Expression Values", - JOptionPane.WARNING_MESSAGE ); - return; - } - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _values_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _values_filechooser.showOpenDialog( _contentpane ); - final File file = _values_filechooser.getSelectedFile(); - if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - BasicTable t = null; - try { - t = BasicTableParser.parse( file, '\t' ); - if ( t.getNumberOfColumns() < 2 ) { - t = BasicTableParser.parse( file, ',' ); - } - if ( t.getNumberOfColumns() < 2 ) { - t = BasicTableParser.parse( file, ' ' ); - } - } - catch ( final IOException e ) { - JOptionPane.showMessageDialog( this, - e.getMessage(), - "Could Not Read Expression Value Table", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( t.getNumberOfColumns() < 2 ) { - JOptionPane.showMessageDialog( this, - "Table contains " + t.getNumberOfColumns() + " column(s)", - "Problem with Expression Value Table", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( t.getNumberOfRows() < 1 ) { - JOptionPane.showMessageDialog( this, - "Table contains zero rows", - "Problem with Expression Value Table", - JOptionPane.ERROR_MESSAGE ); - return; - } - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) { - JOptionPane.showMessageDialog( this, - "Table contains " + t.getNumberOfRows() + " rows, but tree contains " - + phy.getNumberOfExternalNodes() + " external nodes", - "Warning", - JOptionPane.WARNING_MESSAGE ); - } - final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); - int not_found = 0; - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - final String node_name = node.getName(); - if ( !ForesterUtil.isEmpty( node_name ) ) { - int row = -1; - try { - row = t.findRow( node_name ); - } - catch ( final IllegalArgumentException e ) { - JOptionPane - .showMessageDialog( this, - e.getMessage(), - "Error Mapping Node Identifiers to Expression Value Identifiers", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( row < 0 ) { - if ( node.isExternal() ) { - not_found++; - } - continue; - } - final List l = new ArrayList(); - for( int col = 1; col < t.getNumberOfColumns(); ++col ) { - double d = -100; - try { - d = Double.parseDouble( t.getValueAsString( col, row ) ); - } - catch ( final NumberFormatException e ) { - JOptionPane.showMessageDialog( this, - "Could not parse \"" + t.getValueAsString( col, row ) - + "\" into a decimal value", - "Issue with Expression Value Table", - JOptionPane.ERROR_MESSAGE ); - return; - } - stats.addValue( d ); - l.add( d ); - } - if ( !l.isEmpty() ) { - if ( node.getNodeData().getProperties() != null ) { - node.getNodeData().getProperties() - .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF ); - } - node.getNodeData().setVector( l ); - } - } - } - if ( not_found > 0 ) { - JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found - + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE ); - } - getCurrentTreePanel().setStatisticsForExpressionValues( stats ); - } - } - - private void addSequencesFromFile() { - if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) { - JOptionPane.showMessageDialog( this, - "Need to load evolutionary tree first", - "Can Not Read Sequences", - JOptionPane.WARNING_MESSAGE ); - return; - } - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _sequences_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _sequences_filechooser.showOpenDialog( _contentpane ); - final File file = _sequences_filechooser.getSelectedFile(); - List seqs = null; - if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { - try { - if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) { - seqs = FastaParser.parse( new FileInputStream( file ) ); - } - else { - JOptionPane.showMessageDialog( this, - "Format does not appear to be Fasta", - "Multiple sequence file format error", - JOptionPane.ERROR_MESSAGE ); - return; - } - } - catch ( final MsaFormatException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Multiple sequence file format error", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final IOException e ) { - setArrowCursor(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Failed to read multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - catch ( final Exception e ) { - setArrowCursor(); - e.printStackTrace(); - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "Unexpected error during reading of multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - return; - } - if ( ( seqs == null ) || ( seqs.size() < 1 ) ) { - JOptionPane.showMessageDialog( this, - "Multiple sequence file is empty", - "Empty multiple sequence file", - JOptionPane.ERROR_MESSAGE ); - setArrowCursor(); - return; - } - } - if ( seqs != null ) { - for( final Sequence seq : seqs ) { - System.out.println( seq.getIdentifier() ); - } - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - int total_counter = 0; - int attached_counter = 0; - for( final Sequence seq : seqs ) { - ++total_counter; - final String seq_name = seq.getIdentifier(); - if ( !ForesterUtil.isEmpty( seq_name ) ) { - List nodes = phy.getNodesViaSequenceName( seq_name ); - if ( nodes.isEmpty() ) { - nodes = phy.getNodesViaSequenceSymbol( seq_name ); - } - if ( nodes.isEmpty() ) { - nodes = phy.getNodesViaGeneName( seq_name ); - } - if ( nodes.isEmpty() ) { - nodes = phy.getNodes( seq_name ); - } - if ( nodes.size() > 1 ) { - JOptionPane.showMessageDialog( this, - "Sequence name \"" + seq_name + "\" is not unique", - "Sequence name not unique", - JOptionPane.ERROR_MESSAGE ); - setArrowCursor(); - return; - } - final String[] a = seq_name.split( "\\s" ); - if ( nodes.isEmpty() && ( a.length > 1 ) ) { - final String seq_name_split = a[ 0 ]; - nodes = phy.getNodesViaSequenceName( seq_name_split ); - if ( nodes.isEmpty() ) { - nodes = phy.getNodesViaSequenceSymbol( seq_name_split ); - } - if ( nodes.isEmpty() ) { - nodes = phy.getNodes( seq_name_split ); - } - if ( nodes.size() > 1 ) { - JOptionPane.showMessageDialog( this, "Split sequence name \"" + seq_name_split - + "\" is not unique", "Sequence name not unique", JOptionPane.ERROR_MESSAGE ); - setArrowCursor(); - return; - } - } - if ( nodes.size() == 1 ) { - ++attached_counter; - final PhylogenyNode n = nodes.get( 0 ); - if ( !n.getNodeData().isHasSequence() ) { - n.getNodeData().addSequence( new org.forester.phylogeny.data.Sequence() ); - } - n.getNodeData().getSequence().setMolecularSequence( seq.getMolecularSequenceAsString() ); - if ( ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) { - n.getNodeData().getSequence().setName( seq_name ); - } - } - } - } - if ( attached_counter > 0 ) { - int ext_nodes = 0; - int ext_nodes_with_seq = 0; - for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { - ++ext_nodes; - final PhylogenyNode n = iter.next(); - if ( n.getNodeData().isHasSequence() - && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getMolecularSequence() ) ) { - ++ext_nodes_with_seq; - } - } - final String s; - if ( ext_nodes == ext_nodes_with_seq ) { - s = "All " + ext_nodes_with_seq + " external nodes now have a molecular sequence attached to them."; - } - else { - s = ext_nodes_with_seq + " out of " + ext_nodes - + " external nodes now have a molecular sequence attached to them."; - } - if ( ( attached_counter == total_counter ) && ( ext_nodes == ext_nodes_with_seq ) ) { - JOptionPane.showMessageDialog( this, - "Attached all " + total_counter + " sequences to tree nodes.\n" + s, - "All sequences attached", - JOptionPane.INFORMATION_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, "Attached " + attached_counter - + " sequences out of a total of " + total_counter + " sequences.\n" + s, attached_counter - + " sequences attached", JOptionPane.WARNING_MESSAGE ); - } - } - else { - JOptionPane.showMessageDialog( this, "No maching tree node for any of the " + total_counter - + " sequences", "Could not attach any sequences", JOptionPane.ERROR_MESSAGE ); - } - } - } - - private void choosePdfWidth() { - final String s = ( String ) JOptionPane.showInputDialog( this, - "Please enter the default line width for PDF export.\n" - + "[current value: " - + getOptions().getPrintLineWidth() + "]\n", - "Line Width for PDF Export", - JOptionPane.QUESTION_MESSAGE, - null, - null, - getOptions().getPrintLineWidth() ); - if ( !ForesterUtil.isEmpty( s ) ) { - boolean success = true; - float f = 0.0f; - final String m_str = s.trim(); - if ( !ForesterUtil.isEmpty( m_str ) ) { - try { - f = Float.parseFloat( m_str ); - } - catch ( final Exception ex ) { - success = false; - } - } - else { - success = false; - } - if ( success && ( f > 0.0 ) ) { - getOptions().setPrintLineWidth( f ); - } - } - } - - private void choosePrintSize() { - final String s = ( String ) JOptionPane.showInputDialog( this, - "Please enter values for width and height,\nseparated by a comma.\n" - + "[current values: " - + getOptions().getPrintSizeX() + ", " - + getOptions().getPrintSizeY() + "]\n" - + "[A4: " + Constants.A4_SIZE_X + ", " - + Constants.A4_SIZE_Y + "]\n" + "[US Letter: " - + Constants.US_LETTER_SIZE_X + ", " - + Constants.US_LETTER_SIZE_Y + "]", - "Default Size for Graphics Export", - JOptionPane.QUESTION_MESSAGE, - null, - null, - getOptions().getPrintSizeX() + ", " - + getOptions().getPrintSizeY() ); - if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) { - boolean success = true; - int x = 0; - int y = 0; - final String[] str_ary = s.split( "," ); - if ( str_ary.length == 2 ) { - final String x_str = str_ary[ 0 ].trim(); - final String y_str = str_ary[ 1 ].trim(); - if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) { - try { - x = Integer.parseInt( x_str ); - y = Integer.parseInt( y_str ); - } - catch ( final Exception ex ) { - success = false; - } - } - else { - success = false; - } - } - else { - success = false; - } - if ( success && ( x > 1 ) && ( y > 1 ) ) { - getOptions().setPrintSizeX( x ); - getOptions().setPrintSizeY( y ); - } - } - } - - private void closeCurrentPane() { - if ( getMainPanel().getCurrentTreePanel() != null ) { - if ( getMainPanel().getCurrentTreePanel().isEdited() ) { - final int r = JOptionPane.showConfirmDialog( this, - "Close tab despite potentially unsaved changes?", - "Close Tab?", - JOptionPane.YES_NO_OPTION ); - if ( r != JOptionPane.YES_OPTION ) { - return; - } - } - getMainPanel().closeCurrentPane(); - activateSaveAllIfNeeded(); - } - } - - private void collapse( final Phylogeny phy, final double m ) { - final PhylogenyNodeIterator it = phy.iteratorPostorder(); - final List to_be_removed = new ArrayList(); - double min_support = Double.MAX_VALUE; - boolean conf_present = false; - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - if ( !n.isExternal() && !n.isRoot() ) { - final List c = n.getBranchData().getConfidences(); - if ( ( c != null ) && ( c.size() > 0 ) ) { - conf_present = true; - double max = 0; - for( final Confidence confidence : c ) { - if ( confidence.getValue() > max ) { - max = confidence.getValue(); - } - } - if ( max < getMinNotCollapseConfidenceValue() ) { - to_be_removed.add( n ); - } - if ( max < min_support ) { - min_support = max; - } - } - } - } - if ( conf_present ) { - for( final PhylogenyNode node : to_be_removed ) { - PhylogenyMethods.removeNode( node, phy ); - } - if ( to_be_removed.size() > 0 ) { - phy.externalNodesHaveChanged(); - phy.clearHashIdToNodeMap(); - phy.recalculateNumberOfExternalDescendants( true ); - getCurrentTreePanel().resetNodeIdToDistToLeafMap(); - getCurrentTreePanel().updateSetOfCollapsedExternalNodes(); - getCurrentTreePanel().calculateLongestExtNodeInfo(); - getCurrentTreePanel().setNodeInPreorderToNull(); - getCurrentTreePanel().recalculateMaxDistanceToRoot(); - getCurrentTreePanel().resetPreferredSize(); - getCurrentTreePanel().setEdited( true ); - getCurrentTreePanel().repaint(); - repaint(); - } - if ( to_be_removed.size() > 0 ) { - JOptionPane.showMessageDialog( this, "Collapsed " + to_be_removed.size() - + " branches with\nconfidence values below " + getMinNotCollapseConfidenceValue(), "Collapsed " - + to_be_removed.size() + " branches", JOptionPane.INFORMATION_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, "No branch collapsed,\nminimum confidence value per branch is " - + min_support, "No branch collapsed", JOptionPane.INFORMATION_MESSAGE ); - } - } - else { - JOptionPane.showMessageDialog( this, - "No branch collapsed because no confidence values present", - "No confidence values present", - JOptionPane.INFORMATION_MESSAGE ); - } - } - - private void collapseBelowThreshold() { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final String s = ( String ) JOptionPane.showInputDialog( this, - "Please enter the minimum confidence value\n", - "Minimal Confidence Value", - JOptionPane.QUESTION_MESSAGE, - null, - null, - getMinNotCollapseConfidenceValue() ); - if ( !ForesterUtil.isEmpty( s ) ) { - boolean success = true; - double m = 0.0; - final String m_str = s.trim(); - if ( !ForesterUtil.isEmpty( m_str ) ) { - try { - m = Double.parseDouble( m_str ); - } - catch ( final Exception ex ) { - success = false; - } - } - else { - success = false; - } - if ( success && ( m >= 0.0 ) ) { - setMinNotCollapseConfidenceValue( m ); - collapse( phy, m ); - } - } - } - } - } - - private PhyloXmlParser createPhyloXmlParser() { - PhyloXmlParser xml_parser = null; - if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) { - try { - xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating(); - } - catch ( final Exception e ) { - JOptionPane.showMessageDialog( this, - e.getLocalizedMessage(), - "failed to create validating XML parser", - JOptionPane.WARNING_MESSAGE ); - } - } - if ( xml_parser == null ) { - xml_parser = PhyloXmlParser.createPhyloXmlParser(); - } - return xml_parser; - } - - private void executePhyleneticInference( final boolean from_unaligned_seqs ) { - final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this, - getPhylogeneticInferenceOptions(), - from_unaligned_seqs ); - dialog.activate(); - if ( dialog.getValue() == JOptionPane.OK_OPTION ) { - if ( !from_unaligned_seqs ) { - if ( getMsa() != null ) { - final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(), - getPhylogeneticInferenceOptions() - .copy(), this ); - new Thread( inferrer ).start(); - } - else { - JOptionPane.showMessageDialog( this, - "No multiple sequence alignment selected", - "Phylogenetic Inference Not Launched", - JOptionPane.WARNING_MESSAGE ); - } - } - else { - if ( getSeqs() != null ) { - final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(), - getPhylogeneticInferenceOptions() - .copy(), this ); - new Thread( inferrer ).start(); - } - else { - JOptionPane.showMessageDialog( this, - "No input sequences selected", - "Phylogenetic Inference Not Launched", - JOptionPane.WARNING_MESSAGE ); - } - } - } - } - - private void extractTaxDataFromNodeNames() throws PhyloXmlDataFormatException { - final StringBuilder sb = new StringBuilder(); - final StringBuilder sb_failed = new StringBuilder(); - int counter = 0; - int counter_failed = 0; - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final PhylogenyNodeIterator it = phy.iteratorExternalForward(); - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - final String name = n.getName().trim(); - if ( !ForesterUtil.isEmpty( name ) ) { - final String nt = ParserUtils.extractTaxonomyDataFromNodeName( n, - TAXONOMY_EXTRACTION.AGGRESSIVE ); - if ( !ForesterUtil.isEmpty( nt ) ) { - if ( counter < 15 ) { - sb.append( name + ": " + nt + "\n" ); - } - else if ( counter == 15 ) { - sb.append( "...\n" ); - } - counter++; - } - else { - if ( counter_failed < 15 ) { - sb_failed.append( name + "\n" ); - } - else if ( counter_failed == 15 ) { - sb_failed.append( "...\n" ); - } - counter_failed++; - } - } - } - if ( counter > 0 ) { - String failed = ""; - String all = "all "; - if ( counter_failed > 0 ) { - all = ""; - failed = "\nCould not extract taxonomic data for " + counter_failed - + " named external nodes:\n" + sb_failed; - } - JOptionPane.showMessageDialog( this, - "Extracted taxonomic data from " + all + counter - + " named external nodes:\n" + sb.toString() + failed, - "Taxonomic Data Extraction Completed", - counter_failed > 0 ? JOptionPane.WARNING_MESSAGE - : JOptionPane.INFORMATION_MESSAGE ); - } - else { - JOptionPane - .showMessageDialog( this, - "Could not extract any taxonomic data.\nMaybe node names are empty\n" - + "or not in the forms \"XYZ_CAEEL\", \"XYZ_6239\", or \"XYZ_Caenorhabditis_elegans\"\n" - + "or nodes already have taxonomic data?\n", - "No Taxonomic Data Extracted", - JOptionPane.ERROR_MESSAGE ); - } - } - } - } - - private ControlPanel getControlPanel() { - return getMainPanel().getControlPanel(); - } - - private File getCurrentDir() { - if ( ( _current_dir == null ) || !_current_dir.canRead() ) { - if ( ForesterUtil.isWindows() ) { - try { - _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() ); - } - catch ( final Exception e ) { - _current_dir = null; - } - } - } - if ( ( _current_dir == null ) || !_current_dir.canRead() ) { - if ( System.getProperty( "user.home" ) != null ) { - _current_dir = new File( System.getProperty( "user.home" ) ); - } - else if ( System.getProperty( "user.dir" ) != null ) { - _current_dir = new File( System.getProperty( "user.dir" ) ); - } - } - return _current_dir; - } - - private double getMinNotCollapseConfidenceValue() { - return _min_not_collapse; - } - - private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() { - if ( _phylogenetic_inference_options == null ) { - _phylogenetic_inference_options = new PhylogeneticInferenceOptions(); - } - return _phylogenetic_inference_options; - } - - private boolean isUnsavedDataPresent() { - final List tps = getMainPanel().getTreePanels(); - for( final TreePanel tp : tps ) { - if ( tp.isEdited() ) { - return true; - } - } - return false; - } - - private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - PhylogenyMethods - .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false ); - } - } - } - - private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - PhylogenyMethods.transferNodeNameToField( phy, - PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME, - false ); - } - } - } - - private void newTree() { - final Phylogeny[] phys = new Phylogeny[ 1 ]; - final Phylogeny phy = new Phylogeny(); - final PhylogenyNode node = new PhylogenyNode(); - phy.setRoot( node ); - phy.setRooted( true ); - phys[ 0 ] = phy; - AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() ); - _mainpanel.getControlPanel().showWhole(); - _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); - _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); - if ( getMainPanel().getMainFrame() == null ) { - // Must be "E" applet version. - ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() ) - .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); - } - else { - getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); - } - activateSaveAllIfNeeded(); - System.gc(); - } - - private void obtainDetailedTaxonomicInformation() { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final TaxonomyDataManager t = new TaxonomyDataManager( this, - _mainpanel.getCurrentTreePanel(), - phy.copy(), - false, - true ); - new Thread( t ).start(); - } - } - } - - private void obtainDetailedTaxonomicInformationDelete() { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final TaxonomyDataManager t = new TaxonomyDataManager( this, - _mainpanel.getCurrentTreePanel(), - phy.copy(), - true, - true ); - new Thread( t ).start(); - } - } - } - - private void obtainSequenceInformation() { - if ( getCurrentTreePanel() != null ) { - final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); - if ( ( phy != null ) && !phy.isEmpty() ) { - final SequenceDataRetriver u = new SequenceDataRetriver( this, - _mainpanel.getCurrentTreePanel(), - phy.copy() ); - new Thread( u ).start(); - } - } - } - - private void print() { - if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) - || getCurrentTreePanel().getPhylogeny().isEmpty() ) { - return; - } - if ( !getOptions().isPrintUsingActualSize() ) { - getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX() - 80, - getOptions().getPrintSizeY() - 140, - true ); - getCurrentTreePanel().resetPreferredSize(); - getCurrentTreePanel().repaint(); - } - final String job_name = Constants.PRG_NAME; - boolean error = false; - String printer_name = null; - try { - printer_name = Printer.print( getCurrentTreePanel(), job_name ); - } - catch ( final Exception e ) { - error = true; - JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE ); - } - if ( !error && ( printer_name != null ) ) { - String msg = "Printing data sent to printer"; - if ( printer_name.length() > 1 ) { - msg += " [" + printer_name + "]"; - } - JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE ); - } - if ( !getOptions().isPrintUsingActualSize() ) { - getControlPanel().showWhole(); - } - } - - private void printPhylogenyToPdf( final String file_name ) { - if ( !getOptions().isPrintUsingActualSize() ) { - getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX(), - getOptions().getPrintSizeY(), - true ); - getCurrentTreePanel().resetPreferredSize(); - getCurrentTreePanel().repaint(); - } - String pdf_written_to = ""; - boolean error = false; - try { - if ( getOptions().isPrintUsingActualSize() ) { - pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, - getCurrentTreePanel(), - getCurrentTreePanel().getWidth(), - getCurrentTreePanel().getHeight() ); - } - else { - pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions() - .getPrintSizeX(), getOptions().getPrintSizeY() ); - } - } - catch ( final IOException e ) { - error = true; - JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE ); - } - if ( !error ) { - if ( !ForesterUtil.isEmpty( pdf_written_to ) ) { - JOptionPane.showMessageDialog( this, - "Wrote PDF to: " + pdf_written_to, - "Information", - JOptionPane.INFORMATION_MESSAGE ); - } - else { - JOptionPane.showMessageDialog( this, - "There was an unknown problem when attempting to write to PDF file: \"" - + file_name + "\"", - "Error", - JOptionPane.ERROR_MESSAGE ); - } - } - if ( !getOptions().isPrintUsingActualSize() ) { - getControlPanel().showWhole(); - } - } - - private void readPhylogeniesFromFile() { - boolean exception = false; - Phylogeny[] phys = null; - // Set an initial directory if none set yet - final File my_dir = getCurrentDir(); - _open_filechooser.setMultiSelectionEnabled( true ); - // Open file-open dialog and set current directory - if ( my_dir != null ) { - _open_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _open_filechooser.showOpenDialog( _contentpane ); - // All done: get the file - final File[] files = _open_filechooser.getSelectedFiles(); - setCurrentDir( _open_filechooser.getCurrentDirectory() ); - boolean nhx_or_nexus = false; - if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - for( final File file : files ) { - if ( ( file != null ) && !file.isDirectory() ) { - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().setWaitCursor(); - } - else { - _mainpanel.setWaitCursor(); - } - if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) - || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) { - try { - final NHXParser nhx = new NHXParser(); - setSpecialOptionsForNhxParser( nhx ); - phys = PhylogenyMethods.readPhylogenies( nhx, file ); - nhx_or_nexus = true; - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) { - warnIfNotPhyloXmlValidation( getConfiguration() ); - try { - final PhyloXmlParser xml_parser = createPhyloXmlParser(); - phys = PhylogenyMethods.readPhylogenies( xml_parser, file ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) { - try { - phys = PhylogenyMethods.readPhylogenies( new TolParser(), file ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) { - try { - final NexusPhylogeniesParser nex = new NexusPhylogeniesParser(); - setSpecialOptionsForNexParser( nex ); - phys = PhylogenyMethods.readPhylogenies( nex, file ); - nhx_or_nexus = true; - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - // "*.*": - else { - try { - final PhylogenyParser parser = ParserUtils - .createParserDependingOnFileType( file, getConfiguration() - .isValidatePhyloXmlAgainstSchema() ); - if ( parser instanceof NexusPhylogeniesParser ) { - final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser; - setSpecialOptionsForNexParser( nex ); - nhx_or_nexus = true; - } - else if ( parser instanceof NHXParser ) { - final NHXParser nhx = ( NHXParser ) parser; - setSpecialOptionsForNhxParser( nhx ); - nhx_or_nexus = true; - } - else if ( parser instanceof PhyloXmlParser ) { - warnIfNotPhyloXmlValidation( getConfiguration() ); - } - phys = PhylogenyMethods.readPhylogenies( parser, file ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - if ( _mainpanel.getCurrentTreePanel() != null ) { - _mainpanel.getCurrentTreePanel().setArrowCursor(); - } - else { - _mainpanel.setArrowCursor(); - } - if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) { - boolean one_desc = false; - if ( nhx_or_nexus ) { - for( final Phylogeny phy : phys ) { - if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) { - PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" ); - } - if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) { - one_desc = true; - break; - } - } - } - AptxUtil.addPhylogeniesToTabs( phys, - file.getName(), - file.getAbsolutePath(), - getConfiguration(), - getMainPanel() ); - _mainpanel.getControlPanel().showWhole(); - if ( nhx_or_nexus && one_desc ) { - JOptionPane - .showMessageDialog( this, - "One or more trees contain (a) node(s) with one descendant, " - + ForesterUtil.LINE_SEPARATOR - + "possibly indicating illegal parentheses within node names.", - "Warning: Possible Error in New Hampshire Formatted Data", - JOptionPane.WARNING_MESSAGE ); - } - } - } - } - } - activateSaveAllIfNeeded(); - System.gc(); - } - - private void readSpeciesTreeFromFile() { - Phylogeny t = null; - boolean exception = false; - final File my_dir = getCurrentDir(); - _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) ); - if ( my_dir != null ) { - _open_filechooser_for_species_tree.setCurrentDirectory( my_dir ); - } - final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane ); - final File file = _open_filechooser_for_species_tree.getSelectedFile(); - if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) { - try { - final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser - .createPhyloXmlParserXsdValidating(), file ); - t = trees[ 0 ]; - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) { - try { - final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file ); - t = trees[ 0 ]; - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - // "*.*": - else { - try { - final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser - .createPhyloXmlParserXsdValidating(), file ); - t = trees[ 0 ]; - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringOpenFile( e ); - } - } - if ( !exception && ( t != null ) && !t.isRooted() ) { - exception = true; - t = null; - JOptionPane.showMessageDialog( this, - "Species tree is not rooted", - "Species tree not loaded", - JOptionPane.ERROR_MESSAGE ); - } - if ( !exception && ( t != null ) ) { - final Set tax_set = new HashSet(); - for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode node = it.next(); - if ( !node.getNodeData().isHasTaxonomy() ) { - exception = true; - t = null; - JOptionPane - .showMessageDialog( this, - "Species tree contains external node(s) without taxonomy information", - "Species tree not loaded", - JOptionPane.ERROR_MESSAGE ); - break; - } - else { - if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) { - exception = true; - t = null; - JOptionPane.showMessageDialog( this, - "Taxonomy [" - + node.getNodeData().getTaxonomy().asSimpleText() - + "] is not unique in species tree", - "Species tree not loaded", - JOptionPane.ERROR_MESSAGE ); - break; - } - else { - tax_set.add( node.getNodeData().getTaxonomy() ); - } - } - } - } - if ( !exception && ( t != null ) ) { - setSpeciesTree( t ); - JOptionPane.showMessageDialog( this, - "Species tree successfully loaded", - "Species tree loaded", - JOptionPane.INFORMATION_MESSAGE ); - } - _contentpane.repaint(); - System.gc(); - } - } - - private void setArrowCursor() { - try { - _mainpanel.getCurrentTreePanel().setArrowCursor(); - } - catch ( final Exception ex ) { - // Do nothing. - } - } - - private void setCurrentDir( final File current_dir ) { - _current_dir = current_dir; - } - - private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) { - _min_not_collapse = min_not_collapse; - } - - private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) { - _phylogenetic_inference_options = phylogenetic_inference_options; - } - - private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) { - nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() ); - nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() ); - } - - private void setSpecialOptionsForNhxParser( final NHXParser nhx ) { - nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() ); - nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() ); - nhx.setAllowErrorsInDistanceToParent( getOptions().isAllowErrorsInDistanceToParent() ); - } - - private void writeAllToFile() { - if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) { - return; - } - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _save_filechooser.setCurrentDirectory( my_dir ); - } - _save_filechooser.setSelectedFile( new File( "" ) ); - final int result = _save_filechooser.showSaveDialog( _contentpane ); - final File file = _save_filechooser.getSelectedFile(); - setCurrentDir( _save_filechooser.getCurrentDirectory() ); - if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - if ( file.exists() ) { - final int i = JOptionPane.showConfirmDialog( this, - file + " already exists. Overwrite?", - "Warning", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE ); - if ( i != JOptionPane.OK_OPTION ) { - return; - } - else { - try { - file.delete(); - } - catch ( final Exception e ) { - JOptionPane.showMessageDialog( this, - "Failed to delete: " + file, - "Error", - JOptionPane.WARNING_MESSAGE ); - } - } - } - final int count = getMainPanel().getTabbedPane().getTabCount(); - final List trees = new ArrayList(); - for( int i = 0; i < count; ++i ) { - final Phylogeny phy = getMainPanel().getPhylogeny( i ); - if ( ForesterUtil.isEmpty( phy.getName() ) - && !ForesterUtil.isEmpty( getMainPanel().getTabbedPane().getTitleAt( i ) ) ) { - phy.setName( getMainPanel().getTabbedPane().getTitleAt( i ) ); - } - trees.add( phy ); - getMainPanel().getTreePanels().get( i ).setEdited( false ); - } - final PhylogenyWriter writer = new PhylogenyWriter(); - try { - writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR ); - } - catch ( final IOException e ) { - JOptionPane.showMessageDialog( this, - "Failed to write to: " + file, - "Error", - JOptionPane.WARNING_MESSAGE ); - } - } - } - - private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) { - try { - final PhylogenyWriter writer = new PhylogenyWriter(); - writer.toNewHampshire( t, true, getOptions().getNhConversionSupportValueStyle(), file ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringSaveAs( e ); - } - return exception; - } - - private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) { - try { - final PhylogenyWriter writer = new PhylogenyWriter(); - writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringSaveAs( e ); - } - return exception; - } - - private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) { - try { - final PhylogenyWriter writer = new PhylogenyWriter(); - writer.toPhyloXML( file, t, 0 ); - } - catch ( final Exception e ) { - exception = true; - exceptionOccuredDuringSaveAs( e ); - } - return exception; - } - - private void writeToFile( final Phylogeny t ) { - if ( t == null ) { - return; - } - String initial_filename = null; - if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { - try { - initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath(); - } - catch ( final IOException e ) { - initial_filename = null; - } - } - if ( !ForesterUtil.isEmpty( initial_filename ) ) { - _save_filechooser.setSelectedFile( new File( initial_filename ) ); - } - else { - _save_filechooser.setSelectedFile( new File( "" ) ); - } - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _save_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _save_filechooser.showSaveDialog( _contentpane ); - final File file = _save_filechooser.getSelectedFile(); - setCurrentDir( _save_filechooser.getCurrentDirectory() ); - boolean exception = false; - if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - if ( file.exists() ) { - final int i = JOptionPane.showConfirmDialog( this, - file + " already exists.\nOverwrite?", - "Overwrite?", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE ); - if ( i != JOptionPane.OK_OPTION ) { - return; - } - else { - final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX ); - try { - ForesterUtil.copyFile( file, to ); - } - catch ( final Exception e ) { - JOptionPane.showMessageDialog( this, - "Failed to create backup copy " + to, - "Failed to Create Backup Copy", - JOptionPane.WARNING_MESSAGE ); - } - try { - file.delete(); - } - catch ( final Exception e ) { - JOptionPane.showMessageDialog( this, - "Failed to delete: " + file, - "Failed to Delete", - JOptionPane.WARNING_MESSAGE ); - } - } - } - if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) { - exception = writeAsNewHampshire( t, exception, file ); - } - else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) { - exception = writeAsPhyloXml( t, exception, file ); - } - else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) { - exception = writeAsNexus( t, exception, file ); - } - // "*.*": - else { - final String file_name = file.getName().trim().toLowerCase(); - if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) - || file_name.endsWith( ".tree" ) ) { - exception = writeAsNewHampshire( t, exception, file ); - } - else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) { - exception = writeAsNexus( t, exception, file ); - } - // XML is default: - else { - exception = writeAsPhyloXml( t, exception, file ); - } - } - if ( !exception ) { - getMainPanel().setTitleOfSelectedTab( file.getName() ); - getMainPanel().getCurrentTreePanel().setTreeFile( file ); - getMainPanel().getCurrentTreePanel().setEdited( false ); - } - } - } - - private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) { - if ( ( t == null ) || t.isEmpty() ) { - return; - } - String initial_filename = ""; - if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { - initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString(); - } - if ( initial_filename.indexOf( '.' ) > 0 ) { - initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) ); - } - initial_filename = initial_filename + "." + type; - _writetographics_filechooser.setSelectedFile( new File( initial_filename ) ); - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _writetographics_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _writetographics_filechooser.showSaveDialog( _contentpane ); - File file = _writetographics_filechooser.getSelectedFile(); - setCurrentDir( _writetographics_filechooser.getCurrentDirectory() ); - if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) { - file = new File( file.toString() + "." + type ); - } - if ( file.exists() ) { - final int i = JOptionPane.showConfirmDialog( this, - file + " already exists. Overwrite?", - "Warning", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE ); - if ( i != JOptionPane.OK_OPTION ) { - return; - } - else { - try { - file.delete(); - } - catch ( final Exception e ) { - JOptionPane.showMessageDialog( this, - "Failed to delete: " + file, - "Error", - JOptionPane.WARNING_MESSAGE ); - } - } - } - writePhylogenyToGraphicsFile( file.toString(), type ); - } - } - - private void writeToPdf( final Phylogeny t ) { - if ( ( t == null ) || t.isEmpty() ) { - return; - } - String initial_filename = ""; - if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { - initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString(); - } - if ( initial_filename.indexOf( '.' ) > 0 ) { - initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) ); - } - initial_filename = initial_filename + ".pdf"; - _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) ); - final File my_dir = getCurrentDir(); - if ( my_dir != null ) { - _writetopdf_filechooser.setCurrentDirectory( my_dir ); - } - final int result = _writetopdf_filechooser.showSaveDialog( _contentpane ); - File file = _writetopdf_filechooser.getSelectedFile(); - setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() ); - if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { - if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) { - file = new File( file.toString() + ".pdf" ); - } - if ( file.exists() ) { - final int i = JOptionPane.showConfirmDialog( this, - file + " already exists. Overwrite?", - "WARNING", - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.WARNING_MESSAGE ); - if ( i != JOptionPane.OK_OPTION ) { - return; - } - } - printPhylogenyToPdf( file.toString() ); - } - } - - public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) { - return new MainFrameApplication( phys, config ); - } - - public static MainFrame createInstance( final Phylogeny[] phys, - final Configuration config, - final String title, - final File current_dir ) { - return new MainFrameApplication( phys, config, title, current_dir ); - } - - static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) { - return new MainFrameApplication( phys, config, title ); - } - - static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) { - return new MainFrameApplication( phys, config_file_name, title ); - } - - static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) { - mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", " - + o.getPrintSizeY() + ")" ); - } - - static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) { - mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" ); - } - - static void warnIfNotPhyloXmlValidation( final Configuration c ) { - if ( !c.isValidatePhyloXmlAgainstSchema() ) { - JOptionPane - .showMessageDialog( null, - ForesterUtil - .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]", - 80 ), - "Warning", - JOptionPane.WARNING_MESSAGE ); - } - } -} // MainFrameApplication. - -class DefaultFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) - || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" ) - || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" ) - || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) - || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" ) - || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" ) - || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) - || file_name.endsWith( ".con" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)"; - } -} - -class GraphicsFileFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" ) - || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)"; - } -} - -class MsaFileFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" ) - || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)"; - } -} - -class NexusFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" ) - || file_name.endsWith( ".tre" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "Nexus files (*.nex, *.nexus, *.nx, *.tre)"; - } -} // NexusFilter - -class NHFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) - || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" ) - || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" ) - || f.isDirectory(); - } - - @Override - public String getDescription() { - return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)"; - } -} // NHFilter - -class NHXFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".nhx" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "NHX files (*.nhx) [deprecated]"; - } -} - -class PdfFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "PDF files (*.pdf)"; - } -} // PdfFilter - -class SequencesFileFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" ) - || file_name.endsWith( ".seqs" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )"; - } -} - -class TolFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f - .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) ); - } - - @Override - public String getDescription() { - return "Tree of Life files (*.tol, *.tolxml)"; - } -} // TolFilter - -class XMLFilter extends FileFilter { - - @Override - public boolean accept( final File f ) { - final String file_name = f.getName().trim().toLowerCase(); - return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" ) - || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory(); - } - - @Override - public String getDescription() { - return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)"; - } -} // XMLFilter +// $Id: +// FORESTER -- software libraries and applications +// for evolutionary biology research and applications. +// +// Copyright (C) 2008-2009 Christian M. Zmasek +// Copyright (C) 2008-2009 Burnham Institute for Medical Research +// Copyright (C) 2003-2007 Ethalinda K.S. Cannon +// All rights reserved +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +// +// Contact: phylosoft @ gmail . com +// WWW: https://sites.google.com/site/cmzmasek/home/software/forester + +package org.forester.archaeopteryx; + +import java.awt.BorderLayout; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.swing.ButtonGroup; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFileChooser; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.WindowConstants; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.filechooser.FileFilter; +import javax.swing.plaf.synth.SynthLookAndFeel; + +import org.forester.analysis.TaxonomyDataManager; +import org.forester.archaeopteryx.AptxUtil.GraphicsExportType; +import org.forester.archaeopteryx.Options.CLADOGRAM_TYPE; +import org.forester.archaeopteryx.Options.NODE_LABEL_DIRECTION; +import org.forester.archaeopteryx.Options.PHYLOGENY_GRAPHICS_TYPE; +import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer; +import org.forester.archaeopteryx.tools.InferenceManager; +import org.forester.archaeopteryx.tools.PhyloInferenceDialog; +import org.forester.archaeopteryx.tools.PhylogeneticInferenceOptions; +import org.forester.archaeopteryx.tools.PhylogeneticInferrer; +import org.forester.archaeopteryx.tools.SequenceDataRetriver; +import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient; +import org.forester.archaeopteryx.webservices.WebservicesManager; +import org.forester.io.parsers.FastaParser; +import org.forester.io.parsers.GeneralMsaParser; +import org.forester.io.parsers.PhylogenyParser; +import org.forester.io.parsers.nexus.NexusPhylogeniesParser; +import org.forester.io.parsers.nhx.NHXParser; +import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION; +import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException; +import org.forester.io.parsers.phyloxml.PhyloXmlParser; +import org.forester.io.parsers.phyloxml.PhyloXmlUtil; +import org.forester.io.parsers.tol.TolParser; +import org.forester.io.parsers.util.ParserUtils; +import org.forester.io.writers.PhylogenyWriter; +import org.forester.io.writers.SequenceWriter; +import org.forester.msa.Msa; +import org.forester.msa.MsaFormatException; +import org.forester.phylogeny.Phylogeny; +import org.forester.phylogeny.PhylogenyMethods; +import org.forester.phylogeny.PhylogenyNode; +import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE; +import org.forester.phylogeny.data.Confidence; +import org.forester.phylogeny.data.Taxonomy; +import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory; +import org.forester.phylogeny.factories.PhylogenyFactory; +import org.forester.phylogeny.iterators.PhylogenyNodeIterator; +import org.forester.sequence.Sequence; +import org.forester.util.BasicDescriptiveStatistics; +import org.forester.util.BasicTable; +import org.forester.util.BasicTableParser; +import org.forester.util.DescriptiveStatistics; +import org.forester.util.ForesterUtil; +import org.forester.util.WindowsUtils; + +public final class MainFrameApplication extends MainFrame { + + static final String INFER_ANCESTOR_TAXONOMIES = "Infer Ancestor Taxonomies"; + static final String OBTAIN_DETAILED_TAXONOMIC_INFORMATION = "Obtain Detailed Taxonomic Information"; + private final static int FRAME_X_SIZE = 800; + private final static int FRAME_Y_SIZE = 800; + // Filters for the file-open dialog (classes defined in this file) + private final static NHFilter nhfilter = new NHFilter(); + private final static NHXFilter nhxfilter = new NHXFilter(); + private final static XMLFilter xmlfilter = new XMLFilter(); + private final static TolFilter tolfilter = new TolFilter(); + private final static NexusFilter nexusfilter = new NexusFilter(); + private final static PdfFilter pdffilter = new PdfFilter(); + private final static GraphicsFileFilter graphicsfilefilter = new GraphicsFileFilter(); + private final static MsaFileFilter msafilter = new MsaFileFilter(); + private final static SequencesFileFilter seqsfilter = new SequencesFileFilter(); + private final static DefaultFilter defaultfilter = new DefaultFilter(); + private static final long serialVersionUID = -799735726778865234L; + private final JFileChooser _values_filechooser; + private final JFileChooser _sequences_filechooser; + private final JFileChooser _open_filechooser; + private final JFileChooser _msa_filechooser; + private final JFileChooser _seqs_pi_filechooser; + private final JFileChooser _open_filechooser_for_species_tree; + private final JFileChooser _save_filechooser; + private final JFileChooser _writetopdf_filechooser; + private final JFileChooser _writetographics_filechooser; + // Application-only print menu items + private JMenuItem _print_item; + private JMenuItem _write_to_pdf_item; + private JMenuItem _write_to_jpg_item; + private JMenuItem _write_to_gif_item; + private JMenuItem _write_to_tif_item; + private JMenuItem _write_to_png_item; + private JMenuItem _write_to_bmp_item; + private File _current_dir; + private ButtonGroup _radio_group_1; + private ButtonGroup _radio_group_2; + // Others: + double _min_not_collapse = Constants.MIN_NOT_COLLAPSE_DEFAULT; + // Phylogeny Inference menu + private JMenu _inference_menu; + private JMenuItem _inference_from_msa_item; + private JMenuItem _inference_from_seqs_item; + // Phylogeny Inference + private PhylogeneticInferenceOptions _phylogenetic_inference_options = null; + private Msa _msa = null; + private File _msa_file = null; + private List _seqs = null; + private File _seqs_file = null; + JMenuItem _read_values_jmi; + JMenuItem _read_seqs_jmi; + + private MainFrameApplication( final Phylogeny[] phys, final Configuration config ) { + _configuration = config; + if ( _configuration == null ) { + throw new IllegalArgumentException( "configuration is null" ); + } + setVisible( false ); + setOptions( Options.createInstance( _configuration ) ); + _mainpanel = new MainPanel( _configuration, this ); + _open_filechooser = null; + _open_filechooser_for_species_tree = null; + _save_filechooser = null; + _writetopdf_filechooser = null; + _writetographics_filechooser = null; + _msa_filechooser = null; + _seqs_pi_filechooser = null; + _values_filechooser = null; + _sequences_filechooser = null; + _jmenubar = new JMenuBar(); + buildFileMenu(); + buildTypeMenu(); + _contentpane = getContentPane(); + _contentpane.setLayout( new BorderLayout() ); + _contentpane.add( _mainpanel, BorderLayout.CENTER ); + // App is this big + setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE ); + // The window listener + setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); + addWindowListener( new WindowAdapter() { + + @Override + public void windowClosing( final WindowEvent e ) { + exit(); + } + } ); + // setVisible( true ); + if ( ( phys != null ) && ( phys.length > 0 ) ) { + AptxUtil.addPhylogeniesToTabs( phys, "", null, _configuration, _mainpanel ); + validate(); + getMainPanel().getControlPanel().showWholeAll(); + getMainPanel().getControlPanel().showWhole(); + } + //activateSaveAllIfNeeded(); + // ...and its children + _contentpane.repaint(); + } + + private MainFrameApplication( final Phylogeny[] phys, final Configuration config, final String title ) { + this( phys, config, title, null ); + } + + private MainFrameApplication( final Phylogeny[] phys, + final Configuration config, + final String title, + final File current_dir ) { + super(); + _configuration = config; + if ( _configuration == null ) { + throw new IllegalArgumentException( "configuration is null" ); + } + try { + boolean synth_exception = false; + if ( Constants.__SYNTH_LF ) { + try { + final SynthLookAndFeel synth = new SynthLookAndFeel(); + synth.load( MainFrameApplication.class.getResourceAsStream( "/resources/synth_look_and_feel_1.xml" ), + MainFrameApplication.class ); + UIManager.setLookAndFeel( synth ); + } + catch ( final Exception ex ) { + synth_exception = true; + ForesterUtil.printWarningMessage( Constants.PRG_NAME, + "could not create synth look and feel: " + + ex.getLocalizedMessage() ); + } + } + if ( !Constants.__SYNTH_LF || synth_exception ) { + if ( _configuration.isUseNativeUI() ) { + UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); + } + else { + UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() ); + } + } + //UIManager.setLookAndFeel( "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel" ); + } + catch ( final UnsupportedLookAndFeelException e ) { + AptxUtil.dieWithSystemError( "unsupported look and feel: " + e.toString() ); + } + catch ( final ClassNotFoundException e ) { + AptxUtil.dieWithSystemError( "class not found exception: " + e.toString() ); + } + catch ( final InstantiationException e ) { + AptxUtil.dieWithSystemError( "instantiation exception: " + e.toString() ); + } + catch ( final IllegalAccessException e ) { + AptxUtil.dieWithSystemError( "illegal access exception: " + e.toString() ); + } + if ( ( current_dir != null ) && current_dir.canRead() && current_dir.isDirectory() ) { + setCurrentDir( current_dir ); + } + // hide until everything is ready + setVisible( false ); + setOptions( Options.createInstance( _configuration ) ); + setInferenceManager( InferenceManager.createInstance( _configuration ) ); + setPhylogeneticInferenceOptions( PhylogeneticInferenceOptions.createInstance( _configuration ) ); + // _textframe = null; #~~~~ + // set title + setTitle( Constants.PRG_NAME + " " + Constants.VERSION + " (" + Constants.PRG_DATE + ")" ); + _mainpanel = new MainPanel( _configuration, this ); + // The file dialogs + _open_filechooser = new JFileChooser(); + _open_filechooser.setCurrentDirectory( new File( "." ) ); + _open_filechooser.setMultiSelectionEnabled( false ); + _open_filechooser.addChoosableFileFilter( MainFrameApplication.xmlfilter ); + _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhxfilter ); + _open_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter ); + _open_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter ); + _open_filechooser.addChoosableFileFilter( MainFrameApplication.tolfilter ); + _open_filechooser.addChoosableFileFilter( _open_filechooser.getAcceptAllFileFilter() ); + _open_filechooser.setFileFilter( MainFrameApplication.defaultfilter ); + _open_filechooser_for_species_tree = new JFileChooser(); + _open_filechooser_for_species_tree.setCurrentDirectory( new File( "." ) ); + _open_filechooser_for_species_tree.setMultiSelectionEnabled( false ); + _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.xmlfilter ); + _open_filechooser_for_species_tree.addChoosableFileFilter( MainFrameApplication.tolfilter ); + _open_filechooser_for_species_tree.setFileFilter( MainFrameApplication.xmlfilter ); + _save_filechooser = new JFileChooser(); + _save_filechooser.setCurrentDirectory( new File( "." ) ); + _save_filechooser.setMultiSelectionEnabled( false ); + _save_filechooser.setFileFilter( MainFrameApplication.xmlfilter ); + _save_filechooser.addChoosableFileFilter( MainFrameApplication.nhfilter ); + _save_filechooser.addChoosableFileFilter( MainFrameApplication.nexusfilter ); + _save_filechooser.addChoosableFileFilter( _save_filechooser.getAcceptAllFileFilter() ); + _writetopdf_filechooser = new JFileChooser(); + _writetopdf_filechooser.addChoosableFileFilter( MainFrameApplication.pdffilter ); + _writetographics_filechooser = new JFileChooser(); + _writetographics_filechooser.addChoosableFileFilter( MainFrameApplication.graphicsfilefilter ); + // Msa: + _msa_filechooser = new JFileChooser(); + _msa_filechooser.setName( "Read Multiple Sequence Alignment File" ); + _msa_filechooser.setCurrentDirectory( new File( "." ) ); + _msa_filechooser.setMultiSelectionEnabled( false ); + _msa_filechooser.addChoosableFileFilter( _msa_filechooser.getAcceptAllFileFilter() ); + _msa_filechooser.addChoosableFileFilter( MainFrameApplication.msafilter ); + // Seqs: + _seqs_pi_filechooser = new JFileChooser(); + _seqs_pi_filechooser.setName( "Read Sequences File" ); + _seqs_pi_filechooser.setCurrentDirectory( new File( "." ) ); + _seqs_pi_filechooser.setMultiSelectionEnabled( false ); + _seqs_pi_filechooser.addChoosableFileFilter( _seqs_pi_filechooser.getAcceptAllFileFilter() ); + _seqs_pi_filechooser.addChoosableFileFilter( MainFrameApplication.seqsfilter ); + // Expression + _values_filechooser = new JFileChooser(); + _values_filechooser.setCurrentDirectory( new File( "." ) ); + _values_filechooser.setMultiSelectionEnabled( false ); + // Sequences + _sequences_filechooser = new JFileChooser(); + _sequences_filechooser.setCurrentDirectory( new File( "." ) ); + _sequences_filechooser.setMultiSelectionEnabled( false ); + // build the menu bar + _jmenubar = new JMenuBar(); + if ( !_configuration.isUseNativeUI() ) { + _jmenubar.setBackground( getConfiguration().getGuiMenuBackgroundColor() ); + } + buildFileMenu(); + if ( Constants.__ALLOW_PHYLOGENETIC_INFERENCE ) { + buildPhylogeneticInferenceMenu(); + } + buildAnalysisMenu(); + buildToolsMenu(); + buildViewMenu(); + buildFontSizeMenu(); + buildOptionsMenu(); + buildTypeMenu(); + buildHelpMenu(); + setJMenuBar( _jmenubar ); + _jmenubar.add( _help_jmenu ); + _contentpane = getContentPane(); + _contentpane.setLayout( new BorderLayout() ); + _contentpane.add( _mainpanel, BorderLayout.CENTER ); + // App is this big + setSize( MainFrameApplication.FRAME_X_SIZE, MainFrameApplication.FRAME_Y_SIZE ); + // addWindowFocusListener( new WindowAdapter() { + // + // @Override + // public void windowGainedFocus( WindowEvent e ) { + // requestFocusInWindow(); + // } + // } ); + // The window listener + setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE ); + addWindowListener( new WindowAdapter() { + + @Override + public void windowClosing( final WindowEvent e ) { + if ( isUnsavedDataPresent() ) { + final int r = JOptionPane.showConfirmDialog( null, + "Exit despite potentially unsaved changes?", + "Exit?", + JOptionPane.YES_NO_OPTION ); + if ( r != JOptionPane.YES_OPTION ) { + return; + } + } + else { + final int r = JOptionPane.showConfirmDialog( null, + "Exit Archaeopteryx?", + "Exit?", + JOptionPane.YES_NO_OPTION ); + if ( r != JOptionPane.YES_OPTION ) { + return; + } + } + exit(); + } + } ); + // The component listener + addComponentListener( new ComponentAdapter() { + + @Override + public void componentResized( final ComponentEvent e ) { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel() + .getWidth(), + _mainpanel.getCurrentTreePanel() + .getHeight(), + getOptions().isAllowFontSizeChange() ); + } + } + } ); + requestFocusInWindow(); + // addKeyListener( this ); + setVisible( true ); + if ( ( phys != null ) && ( phys.length > 0 ) ) { + AptxUtil.addPhylogeniesToTabs( phys, title, null, _configuration, _mainpanel ); + validate(); + getMainPanel().getControlPanel().showWholeAll(); + getMainPanel().getControlPanel().showWhole(); + } + activateSaveAllIfNeeded(); + // ...and its children + _contentpane.repaint(); + System.gc(); + } + + private MainFrameApplication( final Phylogeny[] phys, final String config_file, final String title ) { + // Reads the config file (false, false => not url, not applet): + this( phys, new Configuration( config_file, false, false, true ), title ); + } + + @Override + public void actionPerformed( final ActionEvent e ) { + try { + super.actionPerformed( e ); + final Object o = e.getSource(); + // Handle app-specific actions here: + if ( o == _open_item ) { + readPhylogeniesFromFile(); + } + if ( o == _open_url_item ) { + readPhylogeniesFromURL(); + } + else if ( o == _save_item ) { + writeToFile( _mainpanel.getCurrentPhylogeny() ); + // If subtree currently displayed, save it, instead of complete + // tree. + } + else if ( o == _new_item ) { + newTree(); + } + else if ( o == _save_all_item ) { + writeAllToFile(); + } + else if ( o == _close_item ) { + closeCurrentPane(); + } + else if ( o == _write_to_pdf_item ) { + writeToPdf( _mainpanel.getCurrentPhylogeny() ); + } + else if ( o == _write_to_jpg_item ) { + writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.JPG ); + } + else if ( o == _write_to_png_item ) { + writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.PNG ); + } + else if ( o == _write_to_gif_item ) { + writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.GIF ); + } + else if ( o == _write_to_tif_item ) { + writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.TIFF ); + } + else if ( o == _write_to_bmp_item ) { + writeToGraphicsFile( _mainpanel.getCurrentPhylogeny(), GraphicsExportType.BMP ); + } + else if ( o == _print_item ) { + print(); + } + else if ( o == _load_species_tree_item ) { + readSpeciesTreeFromFile(); + } + else if ( o == _lineage_inference ) { + if ( isSubtreeDisplayed() ) { + JOptionPane.showMessageDialog( this, + "Subtree is shown.", + "Cannot infer ancestral taxonomies", + JOptionPane.ERROR_MESSAGE ); + return; + } + executeLineageInference(); + } + else if ( o == _obtain_detailed_taxonomic_information_jmi ) { + if ( isSubtreeDisplayed() ) { + return; + } + obtainDetailedTaxonomicInformation(); + } + else if ( o == _obtain_detailed_taxonomic_information_deleting_jmi ) { + if ( isSubtreeDisplayed() ) { + return; + } + obtainDetailedTaxonomicInformationDelete(); + } + else if ( o == _obtain_seq_information_jmi ) { + obtainSequenceInformation(); + } + else if ( o == _read_values_jmi ) { + if ( isSubtreeDisplayed() ) { + return; + } + addExpressionValuesFromFile(); + } + else if ( o == _read_seqs_jmi ) { + if ( isSubtreeDisplayed() ) { + return; + } + addSequencesFromFile(); + } + else if ( o == _move_node_names_to_tax_sn_jmi ) { + moveNodeNamesToTaxSn(); + } + else if ( o == _move_node_names_to_seq_names_jmi ) { + moveNodeNamesToSeqNames(); + } + else if ( o == _extract_tax_code_from_node_names_jmi ) { + extractTaxDataFromNodeNames(); + } + else if ( o == _graphics_export_visible_only_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _antialias_print_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _print_black_and_white_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _print_using_actual_size_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _graphics_export_using_actual_size_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _print_size_mi ) { + choosePrintSize(); + } + else if ( o == _choose_pdf_width_mi ) { + choosePdfWidth(); + } + else if ( o == _internal_number_are_confidence_for_nh_parsing_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _replace_underscores_cbmi ) { + if ( ( _extract_taxonomy_no_rbmi != null ) && !_extract_taxonomy_no_rbmi.isSelected() ) { + _extract_taxonomy_no_rbmi.setSelected( true ); + } + updateOptions( getOptions() ); + } + else if ( o == _allow_errors_in_distance_to_parent_cbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _collapse_below_threshold ) { + if ( isSubtreeDisplayed() ) { + return; + } + collapseBelowThreshold(); + } + else if ( ( o == _extract_taxonomy_pfam_strict_rbmi ) || ( o == _extract_taxonomy_pfam_relaxed_rbmi ) + || ( o == _extract_taxonomy_agressive_rbmi ) ) { + if ( _replace_underscores_cbmi != null ) { + _replace_underscores_cbmi.setSelected( false ); + } + updateOptions( getOptions() ); + } + else if ( o == _extract_taxonomy_no_rbmi ) { + updateOptions( getOptions() ); + } + else if ( o == _inference_from_msa_item ) { + executePhyleneticInference( false ); + } + else if ( o == _inference_from_seqs_item ) { + executePhyleneticInference( true ); + } + _contentpane.repaint(); + } + catch ( final Exception ex ) { + AptxUtil.unexpectedException( ex ); + } + catch ( final Error err ) { + AptxUtil.unexpectedError( err ); + } + } + + public void end() { + _mainpanel.terminate(); + _contentpane.removeAll(); + setVisible( false ); + dispose(); + } + + @Override + public MainPanel getMainPanel() { + return _mainpanel; + } + + public Msa getMsa() { + return _msa; + } + + public File getMsaFile() { + return _msa_file; + } + + public List getSeqs() { + return _seqs; + } + + public File getSeqsFile() { + return _seqs_file; + } + + public void readMsaFromFile() { + // Set an initial directory if none set yet + final File my_dir = getCurrentDir(); + _msa_filechooser.setMultiSelectionEnabled( false ); + // Open file-open dialog and set current directory + if ( my_dir != null ) { + _msa_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _msa_filechooser.showOpenDialog( _contentpane ); + // All done: get the msa + final File file = _msa_filechooser.getSelectedFile(); + setCurrentDir( _msa_filechooser.getCurrentDirectory() ); + if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { + setMsaFile( null ); + setMsa( null ); + Msa msa = null; + try { + final InputStream is = new FileInputStream( file ); + if ( FastaParser.isLikelyFasta( file ) ) { + msa = FastaParser.parseMsa( is ); + } + else { + msa = GeneralMsaParser.parse( is ); + } + } + catch ( final MsaFormatException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Multiple sequence alignment format error", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final IOException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Failed to read multiple sequence alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final IllegalArgumentException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Unexpected error during reading of multiple sequence alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final Exception e ) { + setArrowCursor(); + e.printStackTrace(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Unexpected error during reading of multiple sequence alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( ( msa == null ) || ( msa.getNumberOfSequences() < 1 ) ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence alignment is empty", + "Illegal Multiple Sequence Alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( msa.getNumberOfSequences() < 4 ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence alignment needs to contain at least 3 sequences", + "Illegal multiple sequence alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( msa.getLength() < 2 ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence alignment needs to contain at least 2 residues", + "Illegal multiple sequence alignment", + JOptionPane.ERROR_MESSAGE ); + return; + } + System.gc(); + setMsaFile( _msa_filechooser.getSelectedFile() ); + setMsa( msa ); + } + } + + public void readSeqsFromFileforPI() { + // Set an initial directory if none set yet + final File my_dir = getCurrentDir(); + _seqs_pi_filechooser.setMultiSelectionEnabled( false ); + // Open file-open dialog and set current directory + if ( my_dir != null ) { + _seqs_pi_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _seqs_pi_filechooser.showOpenDialog( _contentpane ); + // All done: get the seqs + final File file = _seqs_pi_filechooser.getSelectedFile(); + setCurrentDir( _seqs_pi_filechooser.getCurrentDirectory() ); + if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { + setSeqsFile( null ); + setSeqs( null ); + List seqs = null; + try { + if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) { + seqs = FastaParser.parse( new FileInputStream( file ) ); + for( final Sequence seq : seqs ) { + System.out.println( SequenceWriter.toFasta( seq, 60 ) ); + } + } + else { + //TODO error + } + } + catch ( final MsaFormatException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Multiple sequence file format error", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final IOException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Failed to read multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final IllegalArgumentException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Unexpected error during reading of multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final Exception e ) { + setArrowCursor(); + e.printStackTrace(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Unexpected error during reading of multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( ( seqs == null ) || ( seqs.size() < 1 ) ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence file is empty", + "Illegal multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( seqs.size() < 4 ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence file needs to contain at least 3 sequences", + "Illegal multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + // if ( msa.getLength() < 2 ) { + // JOptionPane.showMessageDialog( this, + // "Multiple sequence alignment needs to contain at least 2 residues", + // "Illegal multiple sequence file", + // JOptionPane.ERROR_MESSAGE ); + // return; + // } + System.gc(); + setSeqsFile( _seqs_pi_filechooser.getSelectedFile() ); + setSeqs( seqs ); + } + } + + void buildAnalysisMenu() { + _analysis_menu = MainFrame.createMenu( "Analysis", getConfiguration() ); + _analysis_menu.add( _gsdi_item = new JMenuItem( "GSDI (Generalized Speciation Duplication Inference)" ) ); + _analysis_menu.add( _gsdir_item = new JMenuItem( "GSDIR (GSDI with re-rooting)" ) ); + _analysis_menu.add( _load_species_tree_item = new JMenuItem( "Load Species Tree..." ) ); + customizeJMenuItem( _gsdi_item ); + customizeJMenuItem( _gsdir_item ); + customizeJMenuItem( _load_species_tree_item ); + _analysis_menu.addSeparator(); + _analysis_menu.add( _lineage_inference = new JMenuItem( INFER_ANCESTOR_TAXONOMIES ) ); + customizeJMenuItem( _lineage_inference ); + _lineage_inference.setToolTipText( "Inference of ancestor taxonomies/lineages" ); + _jmenubar.add( _analysis_menu ); + } + + @Override + void buildFileMenu() { + _file_jmenu = MainFrame.createMenu( "File", getConfiguration() ); + _file_jmenu.add( _open_item = new JMenuItem( "Read Tree from File..." ) ); + _file_jmenu.addSeparator(); + _file_jmenu.add( _open_url_item = new JMenuItem( "Read Tree from URL/Webservice..." ) ); + _file_jmenu.addSeparator(); + final WebservicesManager webservices_manager = WebservicesManager.getInstance(); + _load_phylogeny_from_webservice_menu_items = new JMenuItem[ webservices_manager + .getAvailablePhylogeniesWebserviceClients().size() ]; + for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) { + final PhylogeniesWebserviceClient client = webservices_manager.getAvailablePhylogeniesWebserviceClient( i ); + _load_phylogeny_from_webservice_menu_items[ i ] = new JMenuItem( client.getMenuName() ); + _file_jmenu.add( _load_phylogeny_from_webservice_menu_items[ i ] ); + } + if ( getConfiguration().isEditable() ) { + _file_jmenu.addSeparator(); + _file_jmenu.add( _new_item = new JMenuItem( "New" ) ); + _new_item.setToolTipText( "to create a new tree with one node, as source for manual tree construction" ); + } + _file_jmenu.addSeparator(); + _file_jmenu.add( _save_item = new JMenuItem( "Save Tree As..." ) ); + _file_jmenu.add( _save_all_item = new JMenuItem( "Save All Trees As..." ) ); + _save_all_item.setToolTipText( "Write all phylogenies to one file." ); + _save_all_item.setEnabled( false ); + _file_jmenu.addSeparator(); + _file_jmenu.add( _write_to_pdf_item = new JMenuItem( "Export to PDF file ..." ) ); + if ( AptxUtil.canWriteFormat( "tif" ) || AptxUtil.canWriteFormat( "tiff" ) || AptxUtil.canWriteFormat( "TIF" ) ) { + _file_jmenu.add( _write_to_tif_item = new JMenuItem( "Export to TIFF file..." ) ); + } + _file_jmenu.add( _write_to_png_item = new JMenuItem( "Export to PNG file..." ) ); + _file_jmenu.add( _write_to_jpg_item = new JMenuItem( "Export to JPG file..." ) ); + if ( AptxUtil.canWriteFormat( "gif" ) ) { + _file_jmenu.add( _write_to_gif_item = new JMenuItem( "Export to GIF file..." ) ); + } + if ( AptxUtil.canWriteFormat( "bmp" ) ) { + _file_jmenu.add( _write_to_bmp_item = new JMenuItem( "Export to BMP file..." ) ); + } + _file_jmenu.addSeparator(); + _file_jmenu.add( _print_item = new JMenuItem( "Print..." ) ); + _file_jmenu.addSeparator(); + _file_jmenu.add( _close_item = new JMenuItem( "Close Tab" ) ); + _close_item.setToolTipText( "To close the current pane." ); + _close_item.setEnabled( true ); + _file_jmenu.addSeparator(); + _file_jmenu.add( _exit_item = new JMenuItem( "Exit" ) ); + customizeJMenuItem( _open_item ); + _open_item + .setFont( new Font( _open_item.getFont().getFontName(), Font.BOLD, _open_item.getFont().getSize() + 4 ) ); + customizeJMenuItem( _open_url_item ); + for( int i = 0; i < webservices_manager.getAvailablePhylogeniesWebserviceClients().size(); ++i ) { + customizeJMenuItem( _load_phylogeny_from_webservice_menu_items[ i ] ); + } + customizeJMenuItem( _save_item ); + if ( getConfiguration().isEditable() ) { + customizeJMenuItem( _new_item ); + } + customizeJMenuItem( _close_item ); + customizeJMenuItem( _save_all_item ); + customizeJMenuItem( _write_to_pdf_item ); + customizeJMenuItem( _write_to_png_item ); + customizeJMenuItem( _write_to_jpg_item ); + customizeJMenuItem( _write_to_gif_item ); + customizeJMenuItem( _write_to_tif_item ); + customizeJMenuItem( _write_to_bmp_item ); + customizeJMenuItem( _print_item ); + customizeJMenuItem( _exit_item ); + _jmenubar.add( _file_jmenu ); + } + + void buildOptionsMenu() { + _options_jmenu = MainFrame.createMenu( OPTIONS_HEADER, getConfiguration() ); + _options_jmenu.addChangeListener( new ChangeListener() { + + @Override + public void stateChanged( final ChangeEvent e ) { + MainFrame.setOvPlacementColorChooseMenuItem( _overview_placment_mi, getOptions() ); + MainFrame.setTextColorChooseMenuItem( _switch_colors_mi, getCurrentTreePanel() ); + MainFrame + .setTextMinSupportMenuItem( _choose_minimal_confidence_mi, getOptions(), getCurrentTreePanel() ); + MainFrame.setTextForFontChooserMenuItem( _choose_font_mi, MainFrame + .createCurrentFontDesc( getMainPanel().getTreeFontSet() ) ); + setTextForGraphicsSizeChooserMenuItem( _print_size_mi, getOptions() ); + setTextForPdfLineWidthChooserMenuItem( _choose_pdf_width_mi, getOptions() ); + MainFrame.updateOptionsMenuDependingOnPhylogenyType( getMainPanel(), + _show_scale_cbmi, + _show_branch_length_values_cbmi, + _non_lined_up_cladograms_rbmi, + _uniform_cladograms_rbmi, + _ext_node_dependent_cladogram_rbmi, + _label_direction_cbmi ); + MainFrame.setCycleNodeFillMenuItem( _cycle_node_fill_mi, getOptions() ); + MainFrame.setCycleNodeShapeMenuItem( _cycle_node_shape_mi, getOptions() ); + MainFrame.setTextNodeSizeMenuItem( _choose_node_size_mi, getOptions() ); + } + } ); + _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( DISPLAY_SUBHEADER ), getConfiguration() ) ); + _options_jmenu + .add( _ext_node_dependent_cladogram_rbmi = new JRadioButtonMenuItem( MainFrame.NONUNIFORM_CLADOGRAMS_LABEL ) ); + _options_jmenu.add( _uniform_cladograms_rbmi = new JRadioButtonMenuItem( MainFrame.UNIFORM_CLADOGRAMS_LABEL ) ); + _options_jmenu.add( _non_lined_up_cladograms_rbmi = new JRadioButtonMenuItem( NON_LINED_UP_CLADOGRAMS_LABEL ) ); + _radio_group_1 = new ButtonGroup(); + _radio_group_1.add( _ext_node_dependent_cladogram_rbmi ); + _radio_group_1.add( _uniform_cladograms_rbmi ); + _radio_group_1.add( _non_lined_up_cladograms_rbmi ); + /////// + _options_jmenu.add( _show_overview_cbmi = new JCheckBoxMenuItem( SHOW_OVERVIEW_LABEL ) ); + _options_jmenu.add( _show_scale_cbmi = new JCheckBoxMenuItem( DISPLAY_SCALE_LABEL ) ); + _options_jmenu + .add( _show_branch_length_values_cbmi = new JCheckBoxMenuItem( DISPLAY_BRANCH_LENGTH_VALUES_LABEL ) ); + _options_jmenu + .add( _show_default_node_shapes_internal_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_INT ) ); + _options_jmenu + .add( _show_default_node_shapes_external_cbmi = new JCheckBoxMenuItem( DISPLAY_NODE_BOXES_LABEL_EXT ) ); + if ( getConfiguration().doDisplayOption( Configuration.show_domain_architectures ) ) { + _options_jmenu.add( _show_domain_labels = new JCheckBoxMenuItem( SHOW_DOMAIN_LABELS_LABEL ) ); + } + _options_jmenu.add( _show_annotation_ref_source = new JCheckBoxMenuItem( SHOW_ANN_REF_SOURCE_LABEL ) ); + _options_jmenu.add( _show_confidence_stddev_cbmi = new JCheckBoxMenuItem( SHOW_CONF_STDDEV_LABEL ) ); + _options_jmenu.add( _color_by_taxonomic_group_cbmi = new JCheckBoxMenuItem( COLOR_BY_TAXONOMIC_GROUP ) ); + _options_jmenu.add( _color_labels_same_as_parent_branch = new JCheckBoxMenuItem( COLOR_LABELS_LABEL ) ); + _color_labels_same_as_parent_branch.setToolTipText( MainFrame.COLOR_LABELS_TIP ); + _options_jmenu.add( _abbreviate_scientific_names = new JCheckBoxMenuItem( ABBREV_SN_LABEL ) ); + _options_jmenu.add( _label_direction_cbmi = new JCheckBoxMenuItem( LABEL_DIRECTION_LABEL ) ); + _label_direction_cbmi.setToolTipText( LABEL_DIRECTION_TIP ); + _options_jmenu.add( _screen_antialias_cbmi = new JCheckBoxMenuItem( SCREEN_ANTIALIAS_LABEL ) ); + _options_jmenu.add( _background_gradient_cbmi = new JCheckBoxMenuItem( BG_GRAD_LABEL ) ); + _options_jmenu.add( _cycle_node_shape_mi = new JMenuItem( MainFrame.CYCLE_NODE_SHAPE_LABEL ) ); + _options_jmenu.add( _cycle_node_fill_mi = new JMenuItem( MainFrame.CYCLE_NODE_FILL_LABEL ) ); + _options_jmenu.add( _choose_node_size_mi = new JMenuItem( MainFrame.CHOOSE_NODE_SIZE_LABEL ) ); + _options_jmenu.add( _choose_minimal_confidence_mi = new JMenuItem( "" ) ); + _options_jmenu.add( _overview_placment_mi = new JMenuItem( "" ) ); + _options_jmenu.add( _switch_colors_mi = new JMenuItem( "" ) ); + _options_jmenu.add( _choose_font_mi = new JMenuItem( "" ) ); + /////// + _options_jmenu.addSeparator(); + _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( SEARCH_SUBHEADER ), getConfiguration() ) ); + _options_jmenu.add( _search_case_senstive_cbmi = new JCheckBoxMenuItem( SEARCH_CASE_SENSITIVE_LABEL ) ); + _options_jmenu.add( _search_whole_words_only_cbmi = new JCheckBoxMenuItem( SEARCH_TERMS_ONLY_LABEL ) ); + _options_jmenu.add( _inverse_search_result_cbmi = new JCheckBoxMenuItem( INVERSE_SEARCH_RESULT_LABEL ) ); + _options_jmenu.addSeparator(); + _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Graphics Export & Printing:" ), + getConfiguration() ) ); + _options_jmenu.add( _antialias_print_cbmi = new JCheckBoxMenuItem( "Antialias" ) ); + _options_jmenu.add( _print_black_and_white_cbmi = new JCheckBoxMenuItem( "Export in Black and White" ) ); + _options_jmenu + .add( _print_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PDF export and Printing" ) ); + _options_jmenu + .add( _graphics_export_using_actual_size_cbmi = new JCheckBoxMenuItem( "Use Current Image Size for PNG, JPG, and GIF export" ) ); + _options_jmenu + .add( _graphics_export_visible_only_cbmi = new JCheckBoxMenuItem( "Limit to Visible ('Screenshot') for PNG, JPG, and GIF export" ) ); + _options_jmenu.add( _print_size_mi = new JMenuItem( "" ) ); + _options_jmenu.add( _choose_pdf_width_mi = new JMenuItem( "" ) ); + _options_jmenu.addSeparator(); + _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/NHX/Nexus Input:" ), getConfiguration() ) ); + _options_jmenu + .add( _internal_number_are_confidence_for_nh_parsing_cbmi = new JCheckBoxMenuItem( "Internal Node Names are Confidence Values" ) ); + _options_jmenu.add( _replace_underscores_cbmi = new JCheckBoxMenuItem( "Replace Underscores with Spaces" ) ); + _options_jmenu + .add( _allow_errors_in_distance_to_parent_cbmi = new JCheckBoxMenuItem( "Ignore Distance Values Format Errors" ) ); + // + _options_jmenu.add( _extract_taxonomy_no_rbmi = new JRadioButtonMenuItem( "No Taxonomy Extraction" ) ); + _options_jmenu + .add( _extract_taxonomy_pfam_strict_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style Node Names" ) ); + _options_jmenu + .add( _extract_taxonomy_pfam_relaxed_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids from Pfam-style like Node Names" ) ); + _options_jmenu + .add( _extract_taxonomy_agressive_rbmi = new JRadioButtonMenuItem( "Extract Taxonomy Codes/Ids/Scientific Names from Node Names" ) ); + _extract_taxonomy_pfam_strict_rbmi + .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"BCL2_MOUSE/123-304\" or \"BCL2_10090/123-304\"" ); + _extract_taxonomy_pfam_relaxed_rbmi + .setToolTipText( "To extract taxonomy codes/ids from node names in the form of e.g. \"bax_MOUSE\" or \"bax_10090\"" ); + _extract_taxonomy_agressive_rbmi + .setToolTipText( "To extract taxonomy codes/ids or scientific names from node names in the form of e.g. \"MOUSE\" or \"10090\" or \"xyz_Nematostella_vectensis\"" ); + _radio_group_2 = new ButtonGroup(); + _radio_group_2.add( _extract_taxonomy_no_rbmi ); + _radio_group_2.add( _extract_taxonomy_pfam_strict_rbmi ); + _radio_group_2.add( _extract_taxonomy_pfam_relaxed_rbmi ); + _radio_group_2.add( _extract_taxonomy_agressive_rbmi ); + // + _options_jmenu.add( customizeMenuItemAsLabel( new JMenuItem( "Newick/Nexus Output:" ), getConfiguration() ) ); + _options_jmenu + .add( _use_brackets_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_BRACKETS_FOR_CONF_IN_NH_LABEL ) ); + _use_brackets_for_conf_in_nh_export_cbmi + .setToolTipText( "e.g. \"0.1[90]\" for a branch with support 90 and a length of 0.1" ); + _options_jmenu + .add( _use_internal_names_for_conf_in_nh_export_cbmi = new JCheckBoxMenuItem( USE_INTERNAL_NAMES_FOR_CONF_IN_NH_LABEL ) ); + customizeJMenuItem( _choose_font_mi ); + customizeJMenuItem( _choose_minimal_confidence_mi ); + customizeJMenuItem( _switch_colors_mi ); + customizeJMenuItem( _print_size_mi ); + customizeJMenuItem( _choose_pdf_width_mi ); + customizeJMenuItem( _overview_placment_mi ); + customizeCheckBoxMenuItem( _show_default_node_shapes_external_cbmi, getOptions() + .isShowDefaultNodeShapesExternal() ); + customizeCheckBoxMenuItem( _show_default_node_shapes_internal_cbmi, getOptions() + .isShowDefaultNodeShapesInternal() ); + customizeJMenuItem( _cycle_node_shape_mi ); + customizeJMenuItem( _cycle_node_fill_mi ); + customizeJMenuItem( _choose_node_size_mi ); + customizeCheckBoxMenuItem( _color_labels_same_as_parent_branch, getOptions().isColorLabelsSameAsParentBranch() ); + customizeCheckBoxMenuItem( _color_by_taxonomic_group_cbmi, getOptions().isColorByTaxonomicGroup() ); + customizeCheckBoxMenuItem( _screen_antialias_cbmi, getOptions().isAntialiasScreen() ); + customizeCheckBoxMenuItem( _background_gradient_cbmi, getOptions().isBackgroundColorGradient() ); + customizeCheckBoxMenuItem( _show_domain_labels, getOptions().isShowDomainLabels() ); + customizeCheckBoxMenuItem( _show_annotation_ref_source, getOptions().isShowAnnotationRefSource() ); + customizeCheckBoxMenuItem( _abbreviate_scientific_names, getOptions().isAbbreviateScientificTaxonNames() ); + customizeCheckBoxMenuItem( _search_case_senstive_cbmi, getOptions().isSearchCaseSensitive() ); + customizeCheckBoxMenuItem( _show_scale_cbmi, getOptions().isShowScale() ); + customizeRadioButtonMenuItem( _non_lined_up_cladograms_rbmi, + getOptions().getCladogramType() == CLADOGRAM_TYPE.NON_LINED_UP ); + customizeRadioButtonMenuItem( _uniform_cladograms_rbmi, + getOptions().getCladogramType() == CLADOGRAM_TYPE.TOTAL_NODE_SUM_DEP ); + customizeRadioButtonMenuItem( _ext_node_dependent_cladogram_rbmi, + getOptions().getCladogramType() == CLADOGRAM_TYPE.EXT_NODE_SUM_DEP ); + customizeCheckBoxMenuItem( _show_branch_length_values_cbmi, getOptions().isShowBranchLengthValues() ); + customizeCheckBoxMenuItem( _show_overview_cbmi, getOptions().isShowOverview() ); + customizeCheckBoxMenuItem( _label_direction_cbmi, + getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL ); + customizeCheckBoxMenuItem( _antialias_print_cbmi, getOptions().isAntialiasPrint() ); + customizeCheckBoxMenuItem( _print_black_and_white_cbmi, getOptions().isPrintBlackAndWhite() ); + customizeCheckBoxMenuItem( _internal_number_are_confidence_for_nh_parsing_cbmi, getOptions() + .isInternalNumberAreConfidenceForNhParsing() ); + customizeRadioButtonMenuItem( _extract_taxonomy_no_rbmi, + getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.NO ); + customizeRadioButtonMenuItem( _extract_taxonomy_pfam_strict_rbmi, + getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ); + customizeRadioButtonMenuItem( _extract_taxonomy_pfam_relaxed_rbmi, + getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED ); + customizeRadioButtonMenuItem( _extract_taxonomy_agressive_rbmi, + getOptions().getTaxonomyExtraction() == TAXONOMY_EXTRACTION.AGGRESSIVE ); + customizeCheckBoxMenuItem( _replace_underscores_cbmi, getOptions().isReplaceUnderscoresInNhParsing() ); + customizeCheckBoxMenuItem( _allow_errors_in_distance_to_parent_cbmi, getOptions() + .isReplaceUnderscoresInNhParsing() ); + customizeCheckBoxMenuItem( _search_whole_words_only_cbmi, getOptions().isMatchWholeTermsOnly() ); + customizeCheckBoxMenuItem( _inverse_search_result_cbmi, getOptions().isInverseSearchResult() ); + customizeCheckBoxMenuItem( _graphics_export_visible_only_cbmi, getOptions().isGraphicsExportVisibleOnly() ); + customizeCheckBoxMenuItem( _print_using_actual_size_cbmi, getOptions().isPrintUsingActualSize() ); + customizeCheckBoxMenuItem( _graphics_export_using_actual_size_cbmi, getOptions() + .isGraphicsExportUsingActualSize() ); + customizeCheckBoxMenuItem( _show_confidence_stddev_cbmi, getOptions().isShowConfidenceStddev() ); + customizeCheckBoxMenuItem( _use_brackets_for_conf_in_nh_export_cbmi, getOptions() + .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ); + customizeCheckBoxMenuItem( _use_internal_names_for_conf_in_nh_export_cbmi, getOptions() + .getNhConversionSupportValueStyle() == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ); + _jmenubar.add( _options_jmenu ); + } + + void buildPhylogeneticInferenceMenu() { + final InferenceManager im = getInferenceManager(); + _inference_menu = MainFrame.createMenu( "Inference", getConfiguration() ); + _inference_menu.add( _inference_from_msa_item = new JMenuItem( "From Multiple Sequence Alignment..." ) ); + customizeJMenuItem( _inference_from_msa_item ); + _inference_from_msa_item.setToolTipText( "Basic phylogenetic inference from MSA" ); + if ( im.canDoMsa() ) { + _inference_menu.add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences..." ) ); + customizeJMenuItem( _inference_from_seqs_item ); + _inference_from_seqs_item + .setToolTipText( "Basic phylogenetic inference including multiple sequence alignment" ); + } + else { + _inference_menu + .add( _inference_from_seqs_item = new JMenuItem( "From Unaligned Sequences (no program found)" ) ); + customizeJMenuItem( _inference_from_seqs_item ); + _inference_from_seqs_item.setEnabled( false ); + } + _jmenubar.add( _inference_menu ); + } + + void buildToolsMenu() { + _tools_menu = createMenu( "Tools", getConfiguration() ); + _tools_menu.add( _confcolor_item = new JMenuItem( "Colorize Branches Depending on Confidence" ) ); + customizeJMenuItem( _confcolor_item ); + _tools_menu.add( _color_rank_jmi = new JMenuItem( "Colorize Subtrees via Taxonomic Rank" ) ); + customizeJMenuItem( _color_rank_jmi ); + _color_rank_jmi.setToolTipText( "for example, at \"Class\" level, colorize mammal specific subtree red" ); + _tools_menu.add( _taxcolor_item = new JMenuItem( "Taxonomy Colorize Branches" ) ); + customizeJMenuItem( _taxcolor_item ); + _tools_menu.addSeparator(); + _tools_menu.add( _remove_visual_styles_item = new JMenuItem( "Delete All Visual Styles From Nodes" ) ); + _remove_visual_styles_item + .setToolTipText( "To remove all node visual styles (fonts, colors) from the current phylogeny." ); + customizeJMenuItem( _remove_visual_styles_item ); + _tools_menu.add( _remove_branch_color_item = new JMenuItem( "Delete All Colors From Branches" ) ); + _remove_branch_color_item.setToolTipText( "To remove all branch color values from the current phylogeny." ); + customizeJMenuItem( _remove_branch_color_item ); + _tools_menu.addSeparator(); + _tools_menu.add( _annotate_item = new JMenuItem( "Annotate Sequences of Selected Nodes" ) ); + customizeJMenuItem( _annotate_item ); + _tools_menu.addSeparator(); + _tools_menu.add( _midpoint_root_item = new JMenuItem( "Midpoint-Root" ) ); + customizeJMenuItem( _midpoint_root_item ); + _tools_menu.addSeparator(); + _tools_menu.add( _collapse_species_specific_subtrees = new JMenuItem( "Collapse Species-Specific Subtrees" ) ); + customizeJMenuItem( _collapse_species_specific_subtrees ); + _tools_menu + .add( _collapse_below_threshold = new JMenuItem( "Collapse Branches with Confidence Below Threshold into Multifurcations" ) ); + customizeJMenuItem( _collapse_below_threshold ); + _collapse_below_threshold + .setToolTipText( "To collapse branches with confidence values below a threshold into multifurcations (in the case of multiple confidences per branch: without at least one confidence value above a threshold)" ); + _tools_menu.addSeparator(); + _tools_menu + .add( _extract_tax_code_from_node_names_jmi = new JMenuItem( "Extract Taxonomic Data from Node Names" ) ); + customizeJMenuItem( _extract_tax_code_from_node_names_jmi ); + _extract_tax_code_from_node_names_jmi + .setToolTipText( "To extract SwissProt/Uniprot taxonomic codes (mnemonics) from nodes names in the form of 'xyz_CAEEL', Uniprot/NCBI identifiers form of 'xyz_6239', or scientific names form of 'xyz_Caenorhabditis_elegans'" ); + _tools_menu + .add( _move_node_names_to_tax_sn_jmi = new JMenuItem( "Transfer Node Names to Taxonomic Scientific Names" ) ); + customizeJMenuItem( _move_node_names_to_tax_sn_jmi ); + _move_node_names_to_tax_sn_jmi.setToolTipText( "To interpret node names as taxonomic scientific names" ); + _tools_menu.add( _move_node_names_to_seq_names_jmi = new JMenuItem( "Transfer Node Names to Sequence Names" ) ); + customizeJMenuItem( _move_node_names_to_seq_names_jmi ); + _move_node_names_to_seq_names_jmi.setToolTipText( "To interpret node names as sequence (protein, gene) names" ); + _tools_menu.addSeparator(); + _tools_menu.add( _obtain_seq_information_jmi = new JMenuItem( "Obtain Sequence Information" ) ); + customizeJMenuItem( _obtain_seq_information_jmi ); + _obtain_seq_information_jmi.setToolTipText( "To add additional sequence information" ); + _tools_menu + .add( _obtain_detailed_taxonomic_information_jmi = new JMenuItem( OBTAIN_DETAILED_TAXONOMIC_INFORMATION ) ); + customizeJMenuItem( _obtain_detailed_taxonomic_information_jmi ); + _obtain_detailed_taxonomic_information_jmi + .setToolTipText( "To add additional taxonomic information (from UniProt Taxonomy)" ); + _tools_menu + .add( _obtain_detailed_taxonomic_information_deleting_jmi = new JMenuItem( "Obtain Detailed Taxonomic Information (deletes nodes!)" ) ); + customizeJMenuItem( _obtain_detailed_taxonomic_information_deleting_jmi ); + _obtain_detailed_taxonomic_information_deleting_jmi + .setToolTipText( "To add additional taxonomic information, deletes nodes for which taxonomy cannot found (from UniProt Taxonomy)" ); + _tools_menu.addSeparator(); + _tools_menu.add( _read_values_jmi = new JMenuItem( "Attach Vector/Expression Values" ) ); + customizeJMenuItem( _read_values_jmi ); + _read_values_jmi.setToolTipText( "To attach vector (e.g. gene expression) values to tree nodes (beta)" ); + _jmenubar.add( _tools_menu ); + _tools_menu.add( _read_seqs_jmi = new JMenuItem( "Attach Molecular Sequences" ) ); + customizeJMenuItem( _read_seqs_jmi ); + _read_seqs_jmi + .setToolTipText( "To attach molecular sequences to tree nodes (from Fasta-formatted file) (beta)" ); + _jmenubar.add( _tools_menu ); + } + + @Override + void close() { + if ( isUnsavedDataPresent() ) { + final int r = JOptionPane.showConfirmDialog( this, + "Exit despite potentially unsaved changes?", + "Exit?", + JOptionPane.YES_NO_OPTION ); + if ( r != JOptionPane.YES_OPTION ) { + return; + } + } + exit(); + } + + void executeLineageInference() { + if ( ( _mainpanel.getCurrentPhylogeny() == null ) || ( _mainpanel.getCurrentPhylogeny().isEmpty() ) ) { + return; + } + if ( !_mainpanel.getCurrentPhylogeny().isRooted() ) { + JOptionPane.showMessageDialog( this, + "Phylogeny is not rooted.", + "Cannot infer ancestral taxonomies", + JOptionPane.ERROR_MESSAGE ); + return; + } + final AncestralTaxonomyInferrer inferrer = new AncestralTaxonomyInferrer( this, + _mainpanel.getCurrentTreePanel(), + _mainpanel.getCurrentPhylogeny() + .copy() ); + new Thread( inferrer ).start(); + } + + void exit() { + removeAllTextFrames(); + _mainpanel.terminate(); + _contentpane.removeAll(); + setVisible( false ); + dispose(); + System.exit( 0 ); + } + + void readPhylogeniesFromURL() { + URL url = null; + Phylogeny[] phys = null; + final String message = "Please enter a complete URL, for example \"http://purl.org/phylo/treebase/phylows/study/TB2:S15480?format=nexus\""; + final String url_string = JOptionPane.showInputDialog( this, + message, + "Use URL/webservice to obtain a phylogeny", + JOptionPane.QUESTION_MESSAGE ); + boolean nhx_or_nexus = false; + if ( ( url_string != null ) && ( url_string.length() > 0 ) ) { + try { + url = new URL( url_string ); + PhylogenyParser parser = null; + if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) { + parser = new TolParser(); + } + else { + parser = ParserUtils.createParserDependingOnUrlContents( url, getConfiguration() + .isValidatePhyloXmlAgainstSchema() ); + } + if ( parser instanceof NexusPhylogeniesParser ) { + nhx_or_nexus = true; + } + else if ( parser instanceof NHXParser ) { + nhx_or_nexus = true; + } + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().setWaitCursor(); + } + else { + _mainpanel.setWaitCursor(); + } + final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance(); + phys = factory.create( url.openStream(), parser ); + } + catch ( final MalformedURLException e ) { + JOptionPane.showMessageDialog( this, + "Malformed URL: " + url + "\n" + e.getLocalizedMessage(), + "Malformed URL", + JOptionPane.ERROR_MESSAGE ); + } + catch ( final IOException e ) { + JOptionPane.showMessageDialog( this, + "Could not read from " + url + "\n" + + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ), + "Failed to read URL", + JOptionPane.ERROR_MESSAGE ); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ), + "Unexpected Exception", + JOptionPane.ERROR_MESSAGE ); + } + finally { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().setArrowCursor(); + } + else { + _mainpanel.setArrowCursor(); + } + } + if ( ( phys != null ) && ( phys.length > 0 ) ) { + if ( nhx_or_nexus && getOptions().isInternalNumberAreConfidenceForNhParsing() ) { + for( final Phylogeny phy : phys ) { + + PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" ); + } + } + AptxUtil.addPhylogeniesToTabs( phys, + new File( url.getFile() ).getName(), + new File( url.getFile() ).toString(), + getConfiguration(), + getMainPanel() ); + _mainpanel.getControlPanel().showWhole(); + } + } + activateSaveAllIfNeeded(); + System.gc(); + } + + void setMsa( final Msa msa ) { + _msa = msa; + } + + void setMsaFile( final File msa_file ) { + _msa_file = msa_file; + } + + void setSeqs( final List seqs ) { + _seqs = seqs; + } + + void setSeqsFile( final File seqs_file ) { + _seqs_file = seqs_file; + } + + void writePhylogenyToGraphicsFile( final String file_name, final GraphicsExportType type ) { + _mainpanel.getCurrentTreePanel().calcParametersForPainting( _mainpanel.getCurrentTreePanel().getWidth(), + _mainpanel.getCurrentTreePanel().getHeight(), + true ); + String file_written_to = ""; + boolean error = false; + try { + file_written_to = AptxUtil.writePhylogenyToGraphicsFile( file_name, + _mainpanel.getCurrentTreePanel().getWidth(), + _mainpanel.getCurrentTreePanel().getHeight(), + _mainpanel.getCurrentTreePanel(), + _mainpanel.getControlPanel(), + type, + getOptions() ); + } + catch ( final IOException e ) { + error = true; + JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE ); + } + if ( !error ) { + if ( ( file_written_to != null ) && ( file_written_to.length() > 0 ) ) { + JOptionPane.showMessageDialog( this, + "Wrote image to: " + file_written_to, + "Graphics Export", + JOptionPane.INFORMATION_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, + "There was an unknown problem when attempting to write to an image file: \"" + + file_name + "\"", + "Error", + JOptionPane.ERROR_MESSAGE ); + } + } + _contentpane.repaint(); + } + + private void addExpressionValuesFromFile() { + if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) { + JOptionPane.showMessageDialog( this, + "Need to load evolutionary tree first", + "Can Not Read Expression Values", + JOptionPane.WARNING_MESSAGE ); + return; + } + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _values_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _values_filechooser.showOpenDialog( _contentpane ); + final File file = _values_filechooser.getSelectedFile(); + if ( ( file != null ) && ( file.length() > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + BasicTable t = null; + try { + t = BasicTableParser.parse( file, '\t' ); + if ( t.getNumberOfColumns() < 2 ) { + t = BasicTableParser.parse( file, ',' ); + } + if ( t.getNumberOfColumns() < 2 ) { + t = BasicTableParser.parse( file, ' ' ); + } + } + catch ( final IOException e ) { + JOptionPane.showMessageDialog( this, + e.getMessage(), + "Could Not Read Expression Value Table", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( t.getNumberOfColumns() < 2 ) { + JOptionPane.showMessageDialog( this, + "Table contains " + t.getNumberOfColumns() + " column(s)", + "Problem with Expression Value Table", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( t.getNumberOfRows() < 1 ) { + JOptionPane.showMessageDialog( this, + "Table contains zero rows", + "Problem with Expression Value Table", + JOptionPane.ERROR_MESSAGE ); + return; + } + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( t.getNumberOfRows() != phy.getNumberOfExternalNodes() ) { + JOptionPane.showMessageDialog( this, + "Table contains " + t.getNumberOfRows() + " rows, but tree contains " + + phy.getNumberOfExternalNodes() + " external nodes", + "Warning", + JOptionPane.WARNING_MESSAGE ); + } + final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); + int not_found = 0; + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + final String node_name = node.getName(); + if ( !ForesterUtil.isEmpty( node_name ) ) { + int row = -1; + try { + row = t.findRow( node_name ); + } + catch ( final IllegalArgumentException e ) { + JOptionPane + .showMessageDialog( this, + e.getMessage(), + "Error Mapping Node Identifiers to Expression Value Identifiers", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( row < 0 ) { + if ( node.isExternal() ) { + not_found++; + } + continue; + } + final List l = new ArrayList(); + for( int col = 1; col < t.getNumberOfColumns(); ++col ) { + double d = -100; + try { + d = Double.parseDouble( t.getValueAsString( col, row ) ); + } + catch ( final NumberFormatException e ) { + JOptionPane.showMessageDialog( this, + "Could not parse \"" + t.getValueAsString( col, row ) + + "\" into a decimal value", + "Issue with Expression Value Table", + JOptionPane.ERROR_MESSAGE ); + return; + } + stats.addValue( d ); + l.add( d ); + } + if ( !l.isEmpty() ) { + if ( node.getNodeData().getProperties() != null ) { + node.getNodeData().getProperties() + .removePropertiesWithGivenReferencePrefix( PhyloXmlUtil.VECTOR_PROPERTY_REF ); + } + node.getNodeData().setVector( l ); + } + } + } + if ( not_found > 0 ) { + JOptionPane.showMessageDialog( this, "Could not fine expression values for " + not_found + + " external node(s)", "Warning", JOptionPane.WARNING_MESSAGE ); + } + getCurrentTreePanel().setStatisticsForExpressionValues( stats ); + } + } + + private void addSequencesFromFile() { + if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) ) { + JOptionPane.showMessageDialog( this, + "Need to load evolutionary tree first", + "Can Not Read Sequences", + JOptionPane.WARNING_MESSAGE ); + return; + } + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _sequences_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _sequences_filechooser.showOpenDialog( _contentpane ); + final File file = _sequences_filechooser.getSelectedFile(); + List seqs = null; + if ( ( file != null ) && !file.isDirectory() && ( result == JFileChooser.APPROVE_OPTION ) ) { + try { + if ( FastaParser.isLikelyFasta( new FileInputStream( file ) ) ) { + seqs = FastaParser.parse( new FileInputStream( file ) ); + } + else { + JOptionPane.showMessageDialog( this, + "Format does not appear to be Fasta", + "Multiple sequence file format error", + JOptionPane.ERROR_MESSAGE ); + return; + } + } + catch ( final MsaFormatException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Multiple sequence file format error", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final IOException e ) { + setArrowCursor(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Failed to read multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + catch ( final Exception e ) { + setArrowCursor(); + e.printStackTrace(); + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "Unexpected error during reading of multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + return; + } + if ( ( seqs == null ) || ( seqs.size() < 1 ) ) { + JOptionPane.showMessageDialog( this, + "Multiple sequence file is empty", + "Empty multiple sequence file", + JOptionPane.ERROR_MESSAGE ); + setArrowCursor(); + return; + } + } + if ( seqs != null ) { + for( final Sequence seq : seqs ) { + System.out.println( seq.getIdentifier() ); + } + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + int total_counter = 0; + int attached_counter = 0; + for( final Sequence seq : seqs ) { + ++total_counter; + final String seq_name = seq.getIdentifier(); + if ( !ForesterUtil.isEmpty( seq_name ) ) { + List nodes = phy.getNodesViaSequenceName( seq_name ); + if ( nodes.isEmpty() ) { + nodes = phy.getNodesViaSequenceSymbol( seq_name ); + } + if ( nodes.isEmpty() ) { + nodes = phy.getNodesViaGeneName( seq_name ); + } + if ( nodes.isEmpty() ) { + nodes = phy.getNodes( seq_name ); + } + if ( nodes.size() > 1 ) { + JOptionPane.showMessageDialog( this, + "Sequence name \"" + seq_name + "\" is not unique", + "Sequence name not unique", + JOptionPane.ERROR_MESSAGE ); + setArrowCursor(); + return; + } + final String[] a = seq_name.split( "\\s" ); + if ( nodes.isEmpty() && ( a.length > 1 ) ) { + final String seq_name_split = a[ 0 ]; + nodes = phy.getNodesViaSequenceName( seq_name_split ); + if ( nodes.isEmpty() ) { + nodes = phy.getNodesViaSequenceSymbol( seq_name_split ); + } + if ( nodes.isEmpty() ) { + nodes = phy.getNodes( seq_name_split ); + } + if ( nodes.size() > 1 ) { + JOptionPane.showMessageDialog( this, "Split sequence name \"" + seq_name_split + + "\" is not unique", "Sequence name not unique", JOptionPane.ERROR_MESSAGE ); + setArrowCursor(); + return; + } + } + if ( nodes.size() == 1 ) { + ++attached_counter; + final PhylogenyNode n = nodes.get( 0 ); + if ( !n.getNodeData().isHasSequence() ) { + n.getNodeData().addSequence( new org.forester.phylogeny.data.Sequence() ); + } + n.getNodeData().getSequence().setMolecularSequence( seq.getMolecularSequenceAsString() ); + if ( ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) { + n.getNodeData().getSequence().setName( seq_name ); + } + } + } + } + if ( attached_counter > 0 ) { + int ext_nodes = 0; + int ext_nodes_with_seq = 0; + for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { + ++ext_nodes; + final PhylogenyNode n = iter.next(); + if ( n.getNodeData().isHasSequence() + && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getMolecularSequence() ) ) { + ++ext_nodes_with_seq; + } + } + final String s; + if ( ext_nodes == ext_nodes_with_seq ) { + s = "All " + ext_nodes_with_seq + " external nodes now have a molecular sequence attached to them."; + } + else { + s = ext_nodes_with_seq + " out of " + ext_nodes + + " external nodes now have a molecular sequence attached to them."; + } + if ( ( attached_counter == total_counter ) && ( ext_nodes == ext_nodes_with_seq ) ) { + JOptionPane.showMessageDialog( this, + "Attached all " + total_counter + " sequences to tree nodes.\n" + s, + "All sequences attached", + JOptionPane.INFORMATION_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, "Attached " + attached_counter + + " sequences out of a total of " + total_counter + " sequences.\n" + s, attached_counter + + " sequences attached", JOptionPane.WARNING_MESSAGE ); + } + } + else { + JOptionPane.showMessageDialog( this, "No maching tree node for any of the " + total_counter + + " sequences", "Could not attach any sequences", JOptionPane.ERROR_MESSAGE ); + } + } + } + + private void choosePdfWidth() { + final String s = ( String ) JOptionPane.showInputDialog( this, + "Please enter the default line width for PDF export.\n" + + "[current value: " + + getOptions().getPrintLineWidth() + "]\n", + "Line Width for PDF Export", + JOptionPane.QUESTION_MESSAGE, + null, + null, + getOptions().getPrintLineWidth() ); + if ( !ForesterUtil.isEmpty( s ) ) { + boolean success = true; + float f = 0.0f; + final String m_str = s.trim(); + if ( !ForesterUtil.isEmpty( m_str ) ) { + try { + f = Float.parseFloat( m_str ); + } + catch ( final Exception ex ) { + success = false; + } + } + else { + success = false; + } + if ( success && ( f > 0.0 ) ) { + getOptions().setPrintLineWidth( f ); + } + } + } + + private void choosePrintSize() { + final String s = ( String ) JOptionPane.showInputDialog( this, + "Please enter values for width and height,\nseparated by a comma.\n" + + "[current values: " + + getOptions().getPrintSizeX() + ", " + + getOptions().getPrintSizeY() + "]\n" + + "[A4: " + Constants.A4_SIZE_X + ", " + + Constants.A4_SIZE_Y + "]\n" + "[US Letter: " + + Constants.US_LETTER_SIZE_X + ", " + + Constants.US_LETTER_SIZE_Y + "]", + "Default Size for Graphics Export", + JOptionPane.QUESTION_MESSAGE, + null, + null, + getOptions().getPrintSizeX() + ", " + + getOptions().getPrintSizeY() ); + if ( !ForesterUtil.isEmpty( s ) && ( s.indexOf( ',' ) > 0 ) ) { + boolean success = true; + int x = 0; + int y = 0; + final String[] str_ary = s.split( "," ); + if ( str_ary.length == 2 ) { + final String x_str = str_ary[ 0 ].trim(); + final String y_str = str_ary[ 1 ].trim(); + if ( !ForesterUtil.isEmpty( x_str ) && !ForesterUtil.isEmpty( y_str ) ) { + try { + x = Integer.parseInt( x_str ); + y = Integer.parseInt( y_str ); + } + catch ( final Exception ex ) { + success = false; + } + } + else { + success = false; + } + } + else { + success = false; + } + if ( success && ( x > 1 ) && ( y > 1 ) ) { + getOptions().setPrintSizeX( x ); + getOptions().setPrintSizeY( y ); + } + } + } + + private void closeCurrentPane() { + if ( getMainPanel().getCurrentTreePanel() != null ) { + if ( getMainPanel().getCurrentTreePanel().isEdited() ) { + final int r = JOptionPane.showConfirmDialog( this, + "Close tab despite potentially unsaved changes?", + "Close Tab?", + JOptionPane.YES_NO_OPTION ); + if ( r != JOptionPane.YES_OPTION ) { + return; + } + } + getMainPanel().closeCurrentPane(); + activateSaveAllIfNeeded(); + } + } + + private void collapse( final Phylogeny phy, final double m ) { + final PhylogenyNodeIterator it = phy.iteratorPostorder(); + final List to_be_removed = new ArrayList(); + double min_support = Double.MAX_VALUE; + boolean conf_present = false; + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + if ( !n.isExternal() && !n.isRoot() ) { + final List c = n.getBranchData().getConfidences(); + if ( ( c != null ) && ( c.size() > 0 ) ) { + conf_present = true; + double max = 0; + for( final Confidence confidence : c ) { + if ( confidence.getValue() > max ) { + max = confidence.getValue(); + } + } + if ( max < getMinNotCollapseConfidenceValue() ) { + to_be_removed.add( n ); + } + if ( max < min_support ) { + min_support = max; + } + } + } + } + if ( conf_present ) { + for( final PhylogenyNode node : to_be_removed ) { + PhylogenyMethods.removeNode( node, phy ); + } + if ( to_be_removed.size() > 0 ) { + phy.externalNodesHaveChanged(); + phy.clearHashIdToNodeMap(); + phy.recalculateNumberOfExternalDescendants( true ); + getCurrentTreePanel().resetNodeIdToDistToLeafMap(); + getCurrentTreePanel().updateSetOfCollapsedExternalNodes(); + getCurrentTreePanel().calculateLongestExtNodeInfo(); + getCurrentTreePanel().setNodeInPreorderToNull(); + getCurrentTreePanel().recalculateMaxDistanceToRoot(); + getCurrentTreePanel().resetPreferredSize(); + getCurrentTreePanel().setEdited( true ); + getCurrentTreePanel().repaint(); + repaint(); + } + if ( to_be_removed.size() > 0 ) { + JOptionPane.showMessageDialog( this, "Collapsed " + to_be_removed.size() + + " branches with\nconfidence values below " + getMinNotCollapseConfidenceValue(), "Collapsed " + + to_be_removed.size() + " branches", JOptionPane.INFORMATION_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, "No branch collapsed,\nminimum confidence value per branch is " + + min_support, "No branch collapsed", JOptionPane.INFORMATION_MESSAGE ); + } + } + else { + JOptionPane.showMessageDialog( this, + "No branch collapsed because no confidence values present", + "No confidence values present", + JOptionPane.INFORMATION_MESSAGE ); + } + } + + private void collapseBelowThreshold() { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final String s = ( String ) JOptionPane.showInputDialog( this, + "Please enter the minimum confidence value\n", + "Minimal Confidence Value", + JOptionPane.QUESTION_MESSAGE, + null, + null, + getMinNotCollapseConfidenceValue() ); + if ( !ForesterUtil.isEmpty( s ) ) { + boolean success = true; + double m = 0.0; + final String m_str = s.trim(); + if ( !ForesterUtil.isEmpty( m_str ) ) { + try { + m = Double.parseDouble( m_str ); + } + catch ( final Exception ex ) { + success = false; + } + } + else { + success = false; + } + if ( success && ( m >= 0.0 ) ) { + setMinNotCollapseConfidenceValue( m ); + collapse( phy, m ); + } + } + } + } + } + + private PhyloXmlParser createPhyloXmlParser() { + PhyloXmlParser xml_parser = null; + if ( getConfiguration().isValidatePhyloXmlAgainstSchema() ) { + try { + xml_parser = PhyloXmlParser.createPhyloXmlParserXsdValidating(); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + e.getLocalizedMessage(), + "failed to create validating XML parser", + JOptionPane.WARNING_MESSAGE ); + } + } + if ( xml_parser == null ) { + xml_parser = PhyloXmlParser.createPhyloXmlParser(); + } + return xml_parser; + } + + private void executePhyleneticInference( final boolean from_unaligned_seqs ) { + final PhyloInferenceDialog dialog = new PhyloInferenceDialog( this, + getPhylogeneticInferenceOptions(), + from_unaligned_seqs ); + dialog.activate(); + if ( dialog.getValue() == JOptionPane.OK_OPTION ) { + if ( !from_unaligned_seqs ) { + if ( getMsa() != null ) { + final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getMsa(), + getPhylogeneticInferenceOptions() + .copy(), this ); + new Thread( inferrer ).start(); + } + else { + JOptionPane.showMessageDialog( this, + "No multiple sequence alignment selected", + "Phylogenetic Inference Not Launched", + JOptionPane.WARNING_MESSAGE ); + } + } + else { + if ( getSeqs() != null ) { + final PhylogeneticInferrer inferrer = new PhylogeneticInferrer( getSeqs(), + getPhylogeneticInferenceOptions() + .copy(), this ); + new Thread( inferrer ).start(); + } + else { + JOptionPane.showMessageDialog( this, + "No input sequences selected", + "Phylogenetic Inference Not Launched", + JOptionPane.WARNING_MESSAGE ); + } + } + } + } + + private void extractTaxDataFromNodeNames() throws PhyloXmlDataFormatException { + final StringBuilder sb = new StringBuilder(); + final StringBuilder sb_failed = new StringBuilder(); + int counter = 0; + int counter_failed = 0; + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final PhylogenyNodeIterator it = phy.iteratorExternalForward(); + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + final String name = n.getName().trim(); + if ( !ForesterUtil.isEmpty( name ) ) { + final String nt = ParserUtils.extractTaxonomyDataFromNodeName( n, + TAXONOMY_EXTRACTION.AGGRESSIVE ); + if ( !ForesterUtil.isEmpty( nt ) ) { + if ( counter < 15 ) { + sb.append( name + ": " + nt + "\n" ); + } + else if ( counter == 15 ) { + sb.append( "...\n" ); + } + counter++; + } + else { + if ( counter_failed < 15 ) { + sb_failed.append( name + "\n" ); + } + else if ( counter_failed == 15 ) { + sb_failed.append( "...\n" ); + } + counter_failed++; + } + } + } + if ( counter > 0 ) { + String failed = ""; + String all = "all "; + if ( counter_failed > 0 ) { + all = ""; + failed = "\nCould not extract taxonomic data for " + counter_failed + + " named external nodes:\n" + sb_failed; + } + JOptionPane.showMessageDialog( this, + "Extracted taxonomic data from " + all + counter + + " named external nodes:\n" + sb.toString() + failed, + "Taxonomic Data Extraction Completed", + counter_failed > 0 ? JOptionPane.WARNING_MESSAGE + : JOptionPane.INFORMATION_MESSAGE ); + } + else { + JOptionPane + .showMessageDialog( this, + "Could not extract any taxonomic data.\nMaybe node names are empty\n" + + "or not in the forms \"XYZ_CAEEL\", \"XYZ_6239\", or \"XYZ_Caenorhabditis_elegans\"\n" + + "or nodes already have taxonomic data?\n", + "No Taxonomic Data Extracted", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + + private ControlPanel getControlPanel() { + return getMainPanel().getControlPanel(); + } + + private File getCurrentDir() { + if ( ( _current_dir == null ) || !_current_dir.canRead() ) { + if ( ForesterUtil.isWindows() ) { + try { + _current_dir = new File( WindowsUtils.getCurrentUserDesktopPath() ); + } + catch ( final Exception e ) { + _current_dir = null; + } + } + } + if ( ( _current_dir == null ) || !_current_dir.canRead() ) { + if ( System.getProperty( "user.home" ) != null ) { + _current_dir = new File( System.getProperty( "user.home" ) ); + } + else if ( System.getProperty( "user.dir" ) != null ) { + _current_dir = new File( System.getProperty( "user.dir" ) ); + } + } + return _current_dir; + } + + private double getMinNotCollapseConfidenceValue() { + return _min_not_collapse; + } + + private PhylogeneticInferenceOptions getPhylogeneticInferenceOptions() { + if ( _phylogenetic_inference_options == null ) { + _phylogenetic_inference_options = new PhylogeneticInferenceOptions(); + } + return _phylogenetic_inference_options; + } + + private boolean isUnsavedDataPresent() { + final List tps = getMainPanel().getTreePanels(); + for( final TreePanel tp : tps ) { + if ( tp.isEdited() ) { + return true; + } + } + return false; + } + + private void moveNodeNamesToSeqNames() throws PhyloXmlDataFormatException { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + PhylogenyMethods + .transferNodeNameToField( phy, PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME, false ); + } + } + } + + private void moveNodeNamesToTaxSn() throws PhyloXmlDataFormatException { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + PhylogenyMethods.transferNodeNameToField( phy, + PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME, + false ); + } + } + } + + private void newTree() { + final Phylogeny[] phys = new Phylogeny[ 1 ]; + final Phylogeny phy = new Phylogeny(); + final PhylogenyNode node = new PhylogenyNode(); + phy.setRoot( node ); + phy.setRooted( true ); + phys[ 0 ] = phy; + AptxUtil.addPhylogeniesToTabs( phys, "", "", getConfiguration(), getMainPanel() ); + _mainpanel.getControlPanel().showWhole(); + _mainpanel.getCurrentTreePanel().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); + _mainpanel.getOptions().setPhylogenyGraphicsType( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); + if ( getMainPanel().getMainFrame() == null ) { + // Must be "E" applet version. + ( ( ArchaeopteryxE ) ( ( MainPanelApplets ) getMainPanel() ).getApplet() ) + .setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); + } + else { + getMainPanel().getMainFrame().setSelectedTypeInTypeMenu( PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR ); + } + activateSaveAllIfNeeded(); + System.gc(); + } + + private void obtainDetailedTaxonomicInformation() { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final TaxonomyDataManager t = new TaxonomyDataManager( this, + _mainpanel.getCurrentTreePanel(), + phy.copy(), + false, + true ); + new Thread( t ).start(); + } + } + } + + private void obtainDetailedTaxonomicInformationDelete() { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final TaxonomyDataManager t = new TaxonomyDataManager( this, + _mainpanel.getCurrentTreePanel(), + phy.copy(), + true, + true ); + new Thread( t ).start(); + } + } + } + + private void obtainSequenceInformation() { + if ( getCurrentTreePanel() != null ) { + final Phylogeny phy = getCurrentTreePanel().getPhylogeny(); + if ( ( phy != null ) && !phy.isEmpty() ) { + final SequenceDataRetriver u = new SequenceDataRetriver( this, + _mainpanel.getCurrentTreePanel(), + phy.copy() ); + new Thread( u ).start(); + } + } + } + + private void print() { + if ( ( getCurrentTreePanel() == null ) || ( getCurrentTreePanel().getPhylogeny() == null ) + || getCurrentTreePanel().getPhylogeny().isEmpty() ) { + return; + } + if ( !getOptions().isPrintUsingActualSize() ) { + getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX() - 80, + getOptions().getPrintSizeY() - 140, + true ); + getCurrentTreePanel().resetPreferredSize(); + getCurrentTreePanel().repaint(); + } + final String job_name = Constants.PRG_NAME; + boolean error = false; + String printer_name = null; + try { + printer_name = Printer.print( getCurrentTreePanel(), job_name ); + } + catch ( final Exception e ) { + error = true; + JOptionPane.showMessageDialog( this, e.getMessage(), "Printing Error", JOptionPane.ERROR_MESSAGE ); + } + if ( !error && ( printer_name != null ) ) { + String msg = "Printing data sent to printer"; + if ( printer_name.length() > 1 ) { + msg += " [" + printer_name + "]"; + } + JOptionPane.showMessageDialog( this, msg, "Printing...", JOptionPane.INFORMATION_MESSAGE ); + } + if ( !getOptions().isPrintUsingActualSize() ) { + getControlPanel().showWhole(); + } + } + + private void printPhylogenyToPdf( final String file_name ) { + if ( !getOptions().isPrintUsingActualSize() ) { + getCurrentTreePanel().calcParametersForPainting( getOptions().getPrintSizeX(), + getOptions().getPrintSizeY(), + true ); + getCurrentTreePanel().resetPreferredSize(); + getCurrentTreePanel().repaint(); + } + String pdf_written_to = ""; + boolean error = false; + try { + if ( getOptions().isPrintUsingActualSize() ) { + pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, + getCurrentTreePanel(), + getCurrentTreePanel().getWidth(), + getCurrentTreePanel().getHeight() ); + } + else { + pdf_written_to = PdfExporter.writePhylogenyToPdf( file_name, getCurrentTreePanel(), getOptions() + .getPrintSizeX(), getOptions().getPrintSizeY() ); + } + } + catch ( final IOException e ) { + error = true; + JOptionPane.showMessageDialog( this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE ); + } + if ( !error ) { + if ( !ForesterUtil.isEmpty( pdf_written_to ) ) { + JOptionPane.showMessageDialog( this, + "Wrote PDF to: " + pdf_written_to, + "Information", + JOptionPane.INFORMATION_MESSAGE ); + } + else { + JOptionPane.showMessageDialog( this, + "There was an unknown problem when attempting to write to PDF file: \"" + + file_name + "\"", + "Error", + JOptionPane.ERROR_MESSAGE ); + } + } + if ( !getOptions().isPrintUsingActualSize() ) { + getControlPanel().showWhole(); + } + } + + private void readPhylogeniesFromFile() { + boolean exception = false; + Phylogeny[] phys = null; + // Set an initial directory if none set yet + final File my_dir = getCurrentDir(); + _open_filechooser.setMultiSelectionEnabled( true ); + // Open file-open dialog and set current directory + if ( my_dir != null ) { + _open_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _open_filechooser.showOpenDialog( _contentpane ); + // All done: get the file + final File[] files = _open_filechooser.getSelectedFiles(); + setCurrentDir( _open_filechooser.getCurrentDirectory() ); + boolean nhx_or_nexus = false; + if ( ( files != null ) && ( files.length > 0 ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + for( final File file : files ) { + if ( ( file != null ) && !file.isDirectory() ) { + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().setWaitCursor(); + } + else { + _mainpanel.setWaitCursor(); + } + if ( ( _open_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) + || ( _open_filechooser.getFileFilter() == MainFrameApplication.nhxfilter ) ) { + try { + final NHXParser nhx = new NHXParser(); + setSpecialOptionsForNhxParser( nhx ); + phys = PhylogenyMethods.readPhylogenies( nhx, file ); + nhx_or_nexus = true; + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + else if ( _open_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) { + warnIfNotPhyloXmlValidation( getConfiguration() ); + try { + final PhyloXmlParser xml_parser = createPhyloXmlParser(); + phys = PhylogenyMethods.readPhylogenies( xml_parser, file ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + else if ( _open_filechooser.getFileFilter() == MainFrameApplication.tolfilter ) { + try { + phys = PhylogenyMethods.readPhylogenies( new TolParser(), file ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + else if ( _open_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) { + try { + final NexusPhylogeniesParser nex = new NexusPhylogeniesParser(); + setSpecialOptionsForNexParser( nex ); + phys = PhylogenyMethods.readPhylogenies( nex, file ); + nhx_or_nexus = true; + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + // "*.*": + else { + try { + final PhylogenyParser parser = ParserUtils + .createParserDependingOnFileType( file, getConfiguration() + .isValidatePhyloXmlAgainstSchema() ); + if ( parser instanceof NexusPhylogeniesParser ) { + final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) parser; + setSpecialOptionsForNexParser( nex ); + nhx_or_nexus = true; + } + else if ( parser instanceof NHXParser ) { + final NHXParser nhx = ( NHXParser ) parser; + setSpecialOptionsForNhxParser( nhx ); + nhx_or_nexus = true; + } + else if ( parser instanceof PhyloXmlParser ) { + warnIfNotPhyloXmlValidation( getConfiguration() ); + } + phys = PhylogenyMethods.readPhylogenies( parser, file ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + if ( _mainpanel.getCurrentTreePanel() != null ) { + _mainpanel.getCurrentTreePanel().setArrowCursor(); + } + else { + _mainpanel.setArrowCursor(); + } + if ( !exception && ( phys != null ) && ( phys.length > 0 ) ) { + boolean one_desc = false; + if ( nhx_or_nexus ) { + for( final Phylogeny phy : phys ) { + if ( getOptions().isInternalNumberAreConfidenceForNhParsing() ) { + PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" ); + } + if ( PhylogenyMethods.getMinimumDescendentsPerInternalNodes( phy ) == 1 ) { + one_desc = true; + break; + } + } + } + AptxUtil.addPhylogeniesToTabs( phys, + file.getName(), + file.getAbsolutePath(), + getConfiguration(), + getMainPanel() ); + _mainpanel.getControlPanel().showWhole(); + if ( nhx_or_nexus && one_desc ) { + JOptionPane + .showMessageDialog( this, + "One or more trees contain (a) node(s) with one descendant, " + + ForesterUtil.LINE_SEPARATOR + + "possibly indicating illegal parentheses within node names.", + "Warning: Possible Error in New Hampshire Formatted Data", + JOptionPane.WARNING_MESSAGE ); + } + } + } + } + } + activateSaveAllIfNeeded(); + System.gc(); + } + + private void readSpeciesTreeFromFile() { + Phylogeny t = null; + boolean exception = false; + final File my_dir = getCurrentDir(); + _open_filechooser_for_species_tree.setSelectedFile( new File( "" ) ); + if ( my_dir != null ) { + _open_filechooser_for_species_tree.setCurrentDirectory( my_dir ); + } + final int result = _open_filechooser_for_species_tree.showOpenDialog( _contentpane ); + final File file = _open_filechooser_for_species_tree.getSelectedFile(); + if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.xmlfilter ) { + try { + final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser + .createPhyloXmlParserXsdValidating(), file ); + t = trees[ 0 ]; + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + else if ( _open_filechooser_for_species_tree.getFileFilter() == MainFrameApplication.tolfilter ) { + try { + final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( new TolParser(), file ); + t = trees[ 0 ]; + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + // "*.*": + else { + try { + final Phylogeny[] trees = PhylogenyMethods.readPhylogenies( PhyloXmlParser + .createPhyloXmlParserXsdValidating(), file ); + t = trees[ 0 ]; + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringOpenFile( e ); + } + } + if ( !exception && ( t != null ) && !t.isRooted() ) { + exception = true; + t = null; + JOptionPane.showMessageDialog( this, + "Species tree is not rooted", + "Species tree not loaded", + JOptionPane.ERROR_MESSAGE ); + } + if ( !exception && ( t != null ) ) { + final Set tax_set = new HashSet(); + for( final PhylogenyNodeIterator it = t.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode node = it.next(); + if ( !node.getNodeData().isHasTaxonomy() ) { + exception = true; + t = null; + JOptionPane + .showMessageDialog( this, + "Species tree contains external node(s) without taxonomy information", + "Species tree not loaded", + JOptionPane.ERROR_MESSAGE ); + break; + } + else { + if ( tax_set.contains( node.getNodeData().getTaxonomy() ) ) { + exception = true; + t = null; + JOptionPane.showMessageDialog( this, + "Taxonomy [" + + node.getNodeData().getTaxonomy().asSimpleText() + + "] is not unique in species tree", + "Species tree not loaded", + JOptionPane.ERROR_MESSAGE ); + break; + } + else { + tax_set.add( node.getNodeData().getTaxonomy() ); + } + } + } + } + if ( !exception && ( t != null ) ) { + setSpeciesTree( t ); + JOptionPane.showMessageDialog( this, + "Species tree successfully loaded", + "Species tree loaded", + JOptionPane.INFORMATION_MESSAGE ); + } + _contentpane.repaint(); + System.gc(); + } + } + + private void setArrowCursor() { + try { + _mainpanel.getCurrentTreePanel().setArrowCursor(); + } + catch ( final Exception ex ) { + // Do nothing. + } + } + + private void setCurrentDir( final File current_dir ) { + _current_dir = current_dir; + } + + private void setMinNotCollapseConfidenceValue( final double min_not_collapse ) { + _min_not_collapse = min_not_collapse; + } + + private void setPhylogeneticInferenceOptions( final PhylogeneticInferenceOptions phylogenetic_inference_options ) { + _phylogenetic_inference_options = phylogenetic_inference_options; + } + + private void setSpecialOptionsForNexParser( final NexusPhylogeniesParser nex ) { + nex.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() ); + nex.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() ); + } + + private void setSpecialOptionsForNhxParser( final NHXParser nhx ) { + nhx.setReplaceUnderscores( getOptions().isReplaceUnderscoresInNhParsing() ); + nhx.setTaxonomyExtraction( getOptions().getTaxonomyExtraction() ); + nhx.setAllowErrorsInDistanceToParent( getOptions().isAllowErrorsInDistanceToParent() ); + } + + private void writeAllToFile() { + if ( ( getMainPanel().getTabbedPane() == null ) || ( getMainPanel().getTabbedPane().getTabCount() < 1 ) ) { + return; + } + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _save_filechooser.setCurrentDirectory( my_dir ); + } + _save_filechooser.setSelectedFile( new File( "" ) ); + final int result = _save_filechooser.showSaveDialog( _contentpane ); + final File file = _save_filechooser.getSelectedFile(); + setCurrentDir( _save_filechooser.getCurrentDirectory() ); + if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + if ( file.exists() ) { + final int i = JOptionPane.showConfirmDialog( this, + file + " already exists. Overwrite?", + "Warning", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE ); + if ( i != JOptionPane.OK_OPTION ) { + return; + } + else { + try { + file.delete(); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + "Failed to delete: " + file, + "Error", + JOptionPane.WARNING_MESSAGE ); + } + } + } + final int count = getMainPanel().getTabbedPane().getTabCount(); + final List trees = new ArrayList(); + for( int i = 0; i < count; ++i ) { + final Phylogeny phy = getMainPanel().getPhylogeny( i ); + if ( ForesterUtil.isEmpty( phy.getName() ) + && !ForesterUtil.isEmpty( getMainPanel().getTabbedPane().getTitleAt( i ) ) ) { + phy.setName( getMainPanel().getTabbedPane().getTitleAt( i ) ); + } + trees.add( phy ); + getMainPanel().getTreePanels().get( i ).setEdited( false ); + } + final PhylogenyWriter writer = new PhylogenyWriter(); + try { + writer.toPhyloXML( file, trees, 0, ForesterUtil.LINE_SEPARATOR ); + } + catch ( final IOException e ) { + JOptionPane.showMessageDialog( this, + "Failed to write to: " + file, + "Error", + JOptionPane.WARNING_MESSAGE ); + } + } + } + + private boolean writeAsNewHampshire( final Phylogeny t, boolean exception, final File file ) { + try { + final PhylogenyWriter writer = new PhylogenyWriter(); + writer.toNewHampshire( t, true, getOptions().getNhConversionSupportValueStyle(), file ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringSaveAs( e ); + } + return exception; + } + + private boolean writeAsNexus( final Phylogeny t, boolean exception, final File file ) { + try { + final PhylogenyWriter writer = new PhylogenyWriter(); + writer.toNexus( file, t, getOptions().getNhConversionSupportValueStyle() ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringSaveAs( e ); + } + return exception; + } + + private boolean writeAsPhyloXml( final Phylogeny t, boolean exception, final File file ) { + try { + final PhylogenyWriter writer = new PhylogenyWriter(); + writer.toPhyloXML( file, t, 0 ); + } + catch ( final Exception e ) { + exception = true; + exceptionOccuredDuringSaveAs( e ); + } + return exception; + } + + private void writeToFile( final Phylogeny t ) { + if ( t == null ) { + return; + } + String initial_filename = null; + if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { + try { + initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().getCanonicalPath(); + } + catch ( final IOException e ) { + initial_filename = null; + } + } + if ( !ForesterUtil.isEmpty( initial_filename ) ) { + _save_filechooser.setSelectedFile( new File( initial_filename ) ); + } + else { + _save_filechooser.setSelectedFile( new File( "" ) ); + } + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _save_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _save_filechooser.showSaveDialog( _contentpane ); + final File file = _save_filechooser.getSelectedFile(); + setCurrentDir( _save_filechooser.getCurrentDirectory() ); + boolean exception = false; + if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + if ( file.exists() ) { + final int i = JOptionPane.showConfirmDialog( this, + file + " already exists.\nOverwrite?", + "Overwrite?", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE ); + if ( i != JOptionPane.OK_OPTION ) { + return; + } + else { + final File to = new File( file.getAbsoluteFile().toString() + Constants.BACKUP_FILE_SUFFIX ); + try { + ForesterUtil.copyFile( file, to ); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + "Failed to create backup copy " + to, + "Failed to Create Backup Copy", + JOptionPane.WARNING_MESSAGE ); + } + try { + file.delete(); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + "Failed to delete: " + file, + "Failed to Delete", + JOptionPane.WARNING_MESSAGE ); + } + } + } + if ( _save_filechooser.getFileFilter() == MainFrameApplication.nhfilter ) { + exception = writeAsNewHampshire( t, exception, file ); + } + else if ( _save_filechooser.getFileFilter() == MainFrameApplication.xmlfilter ) { + exception = writeAsPhyloXml( t, exception, file ); + } + else if ( _save_filechooser.getFileFilter() == MainFrameApplication.nexusfilter ) { + exception = writeAsNexus( t, exception, file ); + } + // "*.*": + else { + final String file_name = file.getName().trim().toLowerCase(); + if ( file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) + || file_name.endsWith( ".tree" ) ) { + exception = writeAsNewHampshire( t, exception, file ); + } + else if ( file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) ) { + exception = writeAsNexus( t, exception, file ); + } + // XML is default: + else { + exception = writeAsPhyloXml( t, exception, file ); + } + } + if ( !exception ) { + getMainPanel().setTitleOfSelectedTab( file.getName() ); + getMainPanel().getCurrentTreePanel().setTreeFile( file ); + getMainPanel().getCurrentTreePanel().setEdited( false ); + } + } + } + + private void writeToGraphicsFile( final Phylogeny t, final GraphicsExportType type ) { + if ( ( t == null ) || t.isEmpty() ) { + return; + } + String initial_filename = ""; + if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { + initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString(); + } + if ( initial_filename.indexOf( '.' ) > 0 ) { + initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) ); + } + initial_filename = initial_filename + "." + type; + _writetographics_filechooser.setSelectedFile( new File( initial_filename ) ); + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _writetographics_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _writetographics_filechooser.showSaveDialog( _contentpane ); + File file = _writetographics_filechooser.getSelectedFile(); + setCurrentDir( _writetographics_filechooser.getCurrentDirectory() ); + if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + if ( !file.toString().toLowerCase().endsWith( type.toString() ) ) { + file = new File( file.toString() + "." + type ); + } + if ( file.exists() ) { + final int i = JOptionPane.showConfirmDialog( this, + file + " already exists. Overwrite?", + "Warning", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE ); + if ( i != JOptionPane.OK_OPTION ) { + return; + } + else { + try { + file.delete(); + } + catch ( final Exception e ) { + JOptionPane.showMessageDialog( this, + "Failed to delete: " + file, + "Error", + JOptionPane.WARNING_MESSAGE ); + } + } + } + writePhylogenyToGraphicsFile( file.toString(), type ); + } + } + + private void writeToPdf( final Phylogeny t ) { + if ( ( t == null ) || t.isEmpty() ) { + return; + } + String initial_filename = ""; + if ( getMainPanel().getCurrentTreePanel().getTreeFile() != null ) { + initial_filename = getMainPanel().getCurrentTreePanel().getTreeFile().toString(); + } + if ( initial_filename.indexOf( '.' ) > 0 ) { + initial_filename = initial_filename.substring( 0, initial_filename.lastIndexOf( '.' ) ); + } + initial_filename = initial_filename + ".pdf"; + _writetopdf_filechooser.setSelectedFile( new File( initial_filename ) ); + final File my_dir = getCurrentDir(); + if ( my_dir != null ) { + _writetopdf_filechooser.setCurrentDirectory( my_dir ); + } + final int result = _writetopdf_filechooser.showSaveDialog( _contentpane ); + File file = _writetopdf_filechooser.getSelectedFile(); + setCurrentDir( _writetopdf_filechooser.getCurrentDirectory() ); + if ( ( file != null ) && ( result == JFileChooser.APPROVE_OPTION ) ) { + if ( !file.toString().toLowerCase().endsWith( ".pdf" ) ) { + file = new File( file.toString() + ".pdf" ); + } + if ( file.exists() ) { + final int i = JOptionPane.showConfirmDialog( this, + file + " already exists. Overwrite?", + "WARNING", + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.WARNING_MESSAGE ); + if ( i != JOptionPane.OK_OPTION ) { + return; + } + } + printPhylogenyToPdf( file.toString() ); + } + } + + public static MainFrameApplication createInstance( final Phylogeny[] phys, final Configuration config ) { + return new MainFrameApplication( phys, config ); + } + + public static MainFrame createInstance( final Phylogeny[] phys, + final Configuration config, + final String title, + final File current_dir ) { + return new MainFrameApplication( phys, config, title, current_dir ); + } + + static MainFrame createInstance( final Phylogeny[] phys, final Configuration config, final String title ) { + return new MainFrameApplication( phys, config, title ); + } + + static MainFrame createInstance( final Phylogeny[] phys, final String config_file_name, final String title ) { + return new MainFrameApplication( phys, config_file_name, title ); + } + + static void setTextForGraphicsSizeChooserMenuItem( final JMenuItem mi, final Options o ) { + mi.setText( "Enter Default Size for Graphics Export... (current: " + o.getPrintSizeX() + ", " + + o.getPrintSizeY() + ")" ); + } + + static void setTextForPdfLineWidthChooserMenuItem( final JMenuItem mi, final Options o ) { + mi.setText( "Enter Default Line Width for PDF Export... (current: " + o.getPrintLineWidth() + ")" ); + } + + static void warnIfNotPhyloXmlValidation( final Configuration c ) { + if ( !c.isValidatePhyloXmlAgainstSchema() ) { + JOptionPane + .showMessageDialog( null, + ForesterUtil + .wordWrap( "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]", + 80 ), + "Warning", + JOptionPane.WARNING_MESSAGE ); + } + } +} // MainFrameApplication. + +class DefaultFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) + || file_name.endsWith( ".nwk" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".ph" ) + || file_name.endsWith( ".tr" ) || file_name.endsWith( ".dnd" ) || file_name.endsWith( ".tree" ) + || file_name.endsWith( ".nhx" ) || file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) + || file_name.endsWith( "phylo.xml" ) || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".nexus" ) + || file_name.endsWith( ".nx" ) || file_name.endsWith( ".nex" ) || file_name.endsWith( ".tre" ) + || file_name.endsWith( ".zip" ) || file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) + || file_name.endsWith( ".con" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "All supported files (*.xml, *.phyloxml, *phylo.xml, *.nhx, *.nh, *.newick, *.nex, *.nexus, *.phy, *.tre, *.tree, *.tol, ...)"; + } +} + +class GraphicsFileFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".jpg" ) || file_name.endsWith( ".jpeg" ) || file_name.endsWith( ".png" ) + || file_name.endsWith( ".gif" ) || file_name.endsWith( ".bmp" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "Image files (*.jpg, *.jpeg, *.png, *.gif, *.bmp)"; + } +} + +class MsaFileFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".msa" ) || file_name.endsWith( ".aln" ) || file_name.endsWith( ".fasta" ) + || file_name.endsWith( ".fas" ) || file_name.endsWith( ".fa" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "Multiple sequence alignment files (*.msa, *.aln, *.fasta, *.fa, *.fas)"; + } +} + +class NexusFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".nex" ) || file_name.endsWith( ".nexus" ) || file_name.endsWith( ".nx" ) + || file_name.endsWith( ".tre" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "Nexus files (*.nex, *.nexus, *.nx, *.tre)"; + } +} // NexusFilter + +class NHFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".nh" ) || file_name.endsWith( ".newick" ) || file_name.endsWith( ".phy" ) + || file_name.endsWith( ".tr" ) || file_name.endsWith( ".tree" ) || file_name.endsWith( ".dnd" ) + || file_name.endsWith( ".ph" ) || file_name.endsWith( ".phb" ) || file_name.endsWith( ".nwk" ) + || f.isDirectory(); + } + + @Override + public String getDescription() { + return "New Hampshire - Newick files (*.nh, *.newick, *.phy, *.tree, *.dnd, *.tr, *.ph, *.phb, *.nwk)"; + } +} // NHFilter + +class NHXFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".nhx" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "NHX files (*.nhx) [deprecated]"; + } +} + +class PdfFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + return f.getName().trim().toLowerCase().endsWith( ".pdf" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "PDF files (*.pdf)"; + } +} // PdfFilter + +class SequencesFileFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".fasta" ) || file_name.endsWith( ".fa" ) || file_name.endsWith( ".fas" ) + || file_name.endsWith( ".seqs" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "Sequences files (*.fasta, *.fa, *.fas, *.seqs )"; + } +} + +class TolFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return ( file_name.endsWith( ".tol" ) || file_name.endsWith( ".tolxml" ) || file_name.endsWith( ".zip" ) || f + .isDirectory() ) && ( !file_name.endsWith( ".xml.zip" ) ); + } + + @Override + public String getDescription() { + return "Tree of Life files (*.tol, *.tolxml)"; + } +} // TolFilter + +class XMLFilter extends FileFilter { + + @Override + public boolean accept( final File f ) { + final String file_name = f.getName().trim().toLowerCase(); + return file_name.endsWith( ".xml" ) || file_name.endsWith( ".phyloxml" ) || file_name.endsWith( "phylo.xml" ) + || file_name.endsWith( ".pxml" ) || file_name.endsWith( ".zip" ) || f.isDirectory(); + } + + @Override + public String getDescription() { + return "phyloXML files (*.xml, *.phyloxml, *phylo.xml, *.pxml, *.zip)"; + } +} // XMLFilter diff --git a/forester/java/src/org/forester/phylogeny/PhylogenyMethods.java b/forester/java/src/org/forester/phylogeny/PhylogenyMethods.java index 01c84c3..5ffa89c 100644 --- a/forester/java/src/org/forester/phylogeny/PhylogenyMethods.java +++ b/forester/java/src/org/forester/phylogeny/PhylogenyMethods.java @@ -1,1799 +1,1799 @@ -// $Id: -// FORESTER -- software libraries and applications -// for evolutionary biology research and applications. -// -// Copyright (C) 2008-2009 Christian M. Zmasek -// Copyright (C) 2008-2009 Burnham Institute for Medical Research -// All rights reserved -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -// -// Contact: phylosoft @ gmail . com -// WWW: https://sites.google.com/site/cmzmasek/home/software/forester - -package org.forester.phylogeny; - -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.forester.io.parsers.FastaParser; -import org.forester.io.parsers.PhylogenyParser; -import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException; -import org.forester.io.parsers.phyloxml.PhyloXmlUtil; -import org.forester.io.parsers.util.PhylogenyParserException; -import org.forester.phylogeny.data.Accession; -import org.forester.phylogeny.data.Annotation; -import org.forester.phylogeny.data.BranchColor; -import org.forester.phylogeny.data.BranchWidth; -import org.forester.phylogeny.data.Confidence; -import org.forester.phylogeny.data.DomainArchitecture; -import org.forester.phylogeny.data.Event; -import org.forester.phylogeny.data.Identifier; -import org.forester.phylogeny.data.PhylogenyDataUtil; -import org.forester.phylogeny.data.Sequence; -import org.forester.phylogeny.data.Taxonomy; -import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory; -import org.forester.phylogeny.factories.PhylogenyFactory; -import org.forester.phylogeny.iterators.PhylogenyNodeIterator; -import org.forester.util.BasicDescriptiveStatistics; -import org.forester.util.DescriptiveStatistics; -import org.forester.util.ForesterUtil; - -public class PhylogenyMethods { - - private PhylogenyMethods() { - // Hidden constructor. - } - - @Override - public Object clone() throws CloneNotSupportedException { - throw new CloneNotSupportedException(); - } - - public static boolean extractFastaInformation( final Phylogeny phy ) { - boolean could_extract = false; - for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - if ( !ForesterUtil.isEmpty( node.getName() ) ) { - final Matcher name_m = FastaParser.FASTA_DESC_LINE.matcher( node.getName() ); - if ( name_m.lookingAt() ) { - could_extract = true; - final String acc_source = name_m.group( 1 ); - final String acc = name_m.group( 2 ); - final String seq_name = name_m.group( 3 ); - final String tax_sn = name_m.group( 4 ); - if ( !ForesterUtil.isEmpty( acc_source ) && !ForesterUtil.isEmpty( acc ) ) { - ForesterUtil.ensurePresenceOfSequence( node ); - node.getNodeData().getSequence( 0 ).setAccession( new Accession( acc, acc_source ) ); - } - if ( !ForesterUtil.isEmpty( seq_name ) ) { - ForesterUtil.ensurePresenceOfSequence( node ); - node.getNodeData().getSequence( 0 ).setName( seq_name ); - } - if ( !ForesterUtil.isEmpty( tax_sn ) ) { - ForesterUtil.ensurePresenceOfTaxonomy( node ); - node.getNodeData().getTaxonomy( 0 ).setScientificName( tax_sn ); - } - } - } - } - return could_extract; - } - - public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) { - final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) { - stats.addValue( n.getDistanceToParent() ); - } - } - return stats; - } - - public static List calculatConfidenceStatistics( final Phylogeny phy ) { - final List stats = new ArrayList(); - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( !n.isExternal() && !n.isRoot() ) { - if ( n.getBranchData().isHasConfidences() ) { - for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) { - final Confidence c = n.getBranchData().getConfidences().get( i ); - if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) { - stats.add( i, new BasicDescriptiveStatistics() ); - } - if ( !ForesterUtil.isEmpty( c.getType() ) ) { - if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) { - if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) { - throw new IllegalArgumentException( "support values in node [" + n.toString() - + "] appear inconsistently ordered" ); - } - } - stats.get( i ).setDescription( c.getType() ); - } - stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 ); - } - } - } - } - return stats; - } - - /** - * Calculates the distance between PhylogenyNodes node1 and node2. - * - * - * @param node1 - * @param node2 - * @return distance between node1 and node2 - */ - public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) { - final PhylogenyNode lca = calculateLCA( node1, node2 ); - final PhylogenyNode n1 = node1; - final PhylogenyNode n2 = node2; - return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) ); - } - - /** - * Returns the LCA of PhylogenyNodes node1 and node2. - * - * - * @param node1 - * @param node2 - * @return LCA of node1 and node2 - */ - public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) { - if ( node1 == null ) { - throw new IllegalArgumentException( "first argument (node) is null" ); - } - if ( node2 == null ) { - throw new IllegalArgumentException( "second argument (node) is null" ); - } - if ( node1 == node2 ) { - return node1; - } - if ( ( node1.getParent() == node2.getParent() ) ) { - return node1.getParent(); - } - int depth1 = node1.calculateDepth(); - int depth2 = node2.calculateDepth(); - while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) { - if ( depth1 > depth2 ) { - node1 = node1.getParent(); - depth1--; - } - else if ( depth2 > depth1 ) { - node2 = node2.getParent(); - depth2--; - } - else { - if ( node1 == node2 ) { - return node1; - } - node1 = node1.getParent(); - node2 = node2.getParent(); - depth1--; - depth2--; - } - } - throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" ); - } - - /** - * Returns the LCA of PhylogenyNodes node1 and node2. - * Precondition: ids are in pre-order (or level-order). - * - * - * @param node1 - * @param node2 - * @return LCA of node1 and node2 - */ - public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) { - if ( node1 == null ) { - throw new IllegalArgumentException( "first argument (node) is null" ); - } - if ( node2 == null ) { - throw new IllegalArgumentException( "second argument (node) is null" ); - } - while ( node1 != node2 ) { - if ( node1.getId() > node2.getId() ) { - node1 = node1.getParent(); - } - else { - node2 = node2.getParent(); - } - } - return node1; - } - - public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) { - if ( node.isExternal() ) { - return 0; - } - short max = 0; - for( PhylogenyNode d : node.getAllExternalDescendants() ) { - short steps = 0; - while ( d != node ) { - if ( d.isCollapse() ) { - steps = 0; - } - else { - steps++; - } - d = d.getParent(); - } - if ( max < steps ) { - max = steps; - } - } - return max; - } - - public static int calculateMaxDepth( final Phylogeny phy ) { - int max = 0; - for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - final int steps = node.calculateDepth(); - if ( steps > max ) { - max = steps; - } - } - return max; - } - - public static double calculateMaxDistanceToRoot( final Phylogeny phy ) { - double max = 0.0; - for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - final double d = node.calculateDistanceToRoot(); - if ( d > max ) { - max = d; - } - } - return max; - } - - public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) { - final List descs = node.getAllExternalDescendants(); - int x = 0; - for( final PhylogenyNode n : descs ) { - if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { - x++; - } - } - return x; - } - - public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) { - final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( !n.isExternal() ) { - stats.addValue( n.getNumberOfDescendants() ); - } - } - return stats; - } - - public final static void collapseSubtreeStructure( final PhylogenyNode n ) { - final List eds = n.getAllExternalDescendants(); - final List d = new ArrayList(); - for( final PhylogenyNode ed : eds ) { - d.add( calculateDistanceToAncestor( n, ed ) ); - } - for( int i = 0; i < eds.size(); ++i ) { - n.setChildNode( i, eds.get( i ) ); - eds.get( i ).setDistanceToParent( d.get( i ) ); - } - } - - public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) { - int count = 0; - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) { - count++; - } - } - return count; - } - - public static int countNumberOfPolytomies( final Phylogeny phy ) { - int count = 0; - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) { - count++; - } - } - return count; - } - - public static final HashMap createNameToExtNodeMap( final Phylogeny phy ) { - final HashMap nodes = new HashMap(); - final List ext = phy.getExternalNodes(); - for( final PhylogenyNode n : ext ) { - nodes.put( n.getName(), n ); - } - return nodes; - } - - public static void deleteExternalNodesNegativeSelection( final Set to_delete, final Phylogeny phy ) { - for( final Long id : to_delete ) { - phy.deleteSubtree( phy.getNode( id ), true ); - } - phy.clearHashIdToNodeMap(); - phy.externalNodesHaveChanged(); - } - - public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p ) - throws IllegalArgumentException { - for( final String element : node_names_to_delete ) { - if ( ForesterUtil.isEmpty( element ) ) { - continue; - } - List nodes = null; - nodes = p.getNodes( element ); - final Iterator it = nodes.iterator(); - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - if ( !n.isExternal() ) { - throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" ); - } - p.deleteSubtree( n, true ); - } - } - p.clearHashIdToNodeMap(); - p.externalNodesHaveChanged(); - } - - public static List deleteExternalNodesPositiveSelection( final String[] node_names_to_keep, - final Phylogeny p ) { - final PhylogenyNodeIterator it = p.iteratorExternalForward(); - final String[] to_delete = new String[ p.getNumberOfExternalNodes() ]; - int i = 0; - Arrays.sort( node_names_to_keep ); - while ( it.hasNext() ) { - final String curent_name = it.next().getName(); - if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) { - to_delete[ i++ ] = curent_name; - } - } - PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p ); - final List deleted = new ArrayList(); - for( final String n : to_delete ) { - if ( !ForesterUtil.isEmpty( n ) ) { - deleted.add( n ); - } - } - return deleted; - } - - public static void deleteExternalNodesPositiveSelectionT( final List species_to_keep, final Phylogeny phy ) { - final Set to_delete = new HashSet(); - for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode n = it.next(); - if ( n.getNodeData().isHasTaxonomy() ) { - if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) { - to_delete.add( n.getId() ); - } - } - else { - throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" ); - } - } - deleteExternalNodesNegativeSelection( to_delete, phy ); - } - - final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) { - final ArrayList to_delete = new ArrayList(); - for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) { - final PhylogenyNode n = iter.next(); - if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) { - to_delete.add( n ); - } - } - for( final PhylogenyNode d : to_delete ) { - PhylogenyMethods.removeNode( d, phy ); - } - phy.clearHashIdToNodeMap(); - phy.externalNodesHaveChanged(); - } - - final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) { - if ( n.isInternal() ) { - throw new IllegalArgumentException( "node is not external" ); - } - final ArrayList to_delete = new ArrayList(); - for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode i = it.next(); - if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) { - to_delete.add( i ); - } - } - for( final PhylogenyNode d : to_delete ) { - phy.deleteSubtree( d, true ); - } - phy.clearHashIdToNodeMap(); - phy.externalNodesHaveChanged(); - } - - public final static List> divideIntoSubTrees( final Phylogeny phy, - final double min_distance_to_root ) { - if ( min_distance_to_root <= 0 ) { - throw new IllegalArgumentException( "attempt to use min distance to root of: " + min_distance_to_root ); - } - final List> l = new ArrayList>(); - setAllIndicatorsToZero( phy ); - for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode n = it.next(); - if ( n.getIndicator() != 0 ) { - continue; - } - l.add( divideIntoSubTreesHelper( n, min_distance_to_root ) ); - if ( l.isEmpty() ) { - throw new RuntimeException( "this should not have happened" ); - } - } - return l; - } - - public static List getAllDescendants( final PhylogenyNode node ) { - final List descs = new ArrayList(); - final Set encountered = new HashSet(); - if ( !node.isExternal() ) { - final List exts = node.getAllExternalDescendants(); - for( PhylogenyNode current : exts ) { - descs.add( current ); - while ( current != node ) { - current = current.getParent(); - if ( encountered.contains( current.getId() ) ) { - continue; - } - descs.add( current ); - encountered.add( current.getId() ); - } - } - } - return descs; - } - - /** - * - * Convenience method - * - * @param node - * @return - */ - public static Color getBranchColorValue( final PhylogenyNode node ) { - if ( node.getBranchData().getBranchColor() == null ) { - return null; - } - return node.getBranchData().getBranchColor().getValue(); - } - - /** - * Convenience method - */ - public static double getBranchWidthValue( final PhylogenyNode node ) { - if ( !node.getBranchData().isHasBranchWidth() ) { - return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE; - } - return node.getBranchData().getBranchWidth().getValue(); - } - - /** - * Convenience method - */ - public static double getConfidenceValue( final PhylogenyNode node ) { - if ( !node.getBranchData().isHasConfidences() ) { - return Confidence.CONFIDENCE_DEFAULT_VALUE; - } - return node.getBranchData().getConfidence( 0 ).getValue(); - } - - /** - * Convenience method - */ - public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) { - if ( !node.getBranchData().isHasConfidences() ) { - return new double[ 0 ]; - } - final double[] values = new double[ node.getBranchData().getConfidences().size() ]; - int i = 0; - for( final Confidence c : node.getBranchData().getConfidences() ) { - values[ i++ ] = c.getValue(); - } - return values; - } - - final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) { - return calculateLCA( n1, n2 ).getNodeData().getEvent(); - } - - /** - * Returns taxonomy t if all external descendants have - * the same taxonomy t, null otherwise. - * - */ - public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) { - final List descs = node.getAllExternalDescendants(); - Taxonomy tax = null; - for( final PhylogenyNode n : descs ) { - if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { - return null; - } - else if ( tax == null ) { - tax = n.getNodeData().getTaxonomy(); - } - else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) { - return null; - } - } - return tax; - } - - public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) { - final List children = node.getAllExternalDescendants(); - PhylogenyNode farthest = null; - double longest = -Double.MAX_VALUE; - for( final PhylogenyNode child : children ) { - if ( PhylogenyMethods.getDistance( child, node ) > longest ) { - farthest = child; - longest = PhylogenyMethods.getDistance( child, node ); - } - } - return farthest; - } - - // public static PhylogenyMethods getInstance() { - // if ( PhylogenyMethods._instance == null ) { - // PhylogenyMethods._instance = new PhylogenyMethods(); - // } - // return PhylogenyMethods._instance; - // } - /** - * Returns the largest confidence value found on phy. - */ - static public double getMaximumConfidenceValue( final Phylogeny phy ) { - double max = -Double.MAX_VALUE; - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final double s = PhylogenyMethods.getConfidenceValue( iter.next() ); - if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) { - max = s; - } - } - return max; - } - - static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) { - int min = Integer.MAX_VALUE; - int d = 0; - PhylogenyNode n; - for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) { - n = it.next(); - if ( n.isInternal() ) { - d = n.getNumberOfDescendants(); - if ( d < min ) { - min = d; - } - } - } - return min; - } - - /** - * Convenience method for display purposes. - * Not intended for algorithms. - */ - public static String getSpecies( final PhylogenyNode node ) { - if ( !node.getNodeData().isHasTaxonomy() ) { - return ""; - } - else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) { - return node.getNodeData().getTaxonomy().getScientificName(); - } - if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) { - return node.getNodeData().getTaxonomy().getTaxonomyCode(); - } - else { - return node.getNodeData().getTaxonomy().getCommonName(); - } - } - - /** - * Convenience method for display purposes. - * Not intended for algorithms. - */ - public static String getTaxonomyIdentifier( final PhylogenyNode node ) { - if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) { - return ""; - } - return node.getNodeData().getTaxonomy().getIdentifier().getValue(); - } - - public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) { - if ( n.isExternal() ) { - return true; - } - else { - if ( n.isDuplication() ) { - for( final PhylogenyNode desc : n.getDescendants() ) { - if ( !isAllDecendentsAreDuplications( desc ) ) { - return false; - } - } - return true; - } - else { - return false; - } - } - } - - public static boolean isHasExternalDescendant( final PhylogenyNode node ) { - for( int i = 0; i < node.getNumberOfDescendants(); ++i ) { - if ( node.getChildNode( i ).isExternal() ) { - return true; - } - } - return false; - } - - /* - * This is case insensitive. - * - */ - public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax, - final String[] providers ) { - if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) { - final String my_tax_prov = tax.getIdentifier().getProvider(); - for( final String provider : providers ) { - if ( provider.equalsIgnoreCase( my_tax_prov ) ) { - return true; - } - } - return false; - } - else { - return false; - } - } - - public static void midpointRoot( final Phylogeny phylogeny ) { - if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) { - return; - } - int counter = 0; - final int total_nodes = phylogeny.getNodeCount(); - while ( true ) { - if ( ++counter > total_nodes ) { - throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" ); - } - PhylogenyNode a = null; - double da = 0; - double db = 0; - for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) { - final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) ); - final double df = getDistance( f, phylogeny.getRoot() ); - if ( df > 0 ) { - if ( df > da ) { - db = da; - da = df; - a = f; - } - else if ( df > db ) { - db = df; - } - } - } - final double diff = da - db; - if ( diff < 0.000001 ) { - break; - } - double x = da - ( diff / 2.0 ); - while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) { - x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 ); - a = a.getParent(); - } - phylogeny.reRoot( a, x ); - } - phylogeny.recalculateNumberOfExternalDescendants( true ); - } - - public static void normalizeBootstrapValues( final Phylogeny phylogeny, - final double max_bootstrap_value, - final double max_normalized_value ) { - for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - if ( node.isInternal() ) { - final double confidence = getConfidenceValue( node ); - if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) { - if ( confidence >= max_bootstrap_value ) { - setBootstrapConfidence( node, max_normalized_value ); - } - else { - setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value ); - } - } - } - } - } - - public static List obtainAllNodesAsList( final Phylogeny phy ) { - final List nodes = new ArrayList(); - if ( phy.isEmpty() ) { - return nodes; - } - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - nodes.add( iter.next() ); - } - return nodes; - } - - /** - * Returns a map of distinct taxonomies of - * all external nodes of node. - * If at least one of the external nodes has no taxonomy, - * null is returned. - * - */ - public static Map obtainDistinctTaxonomyCounts( final PhylogenyNode node ) { - final List descs = node.getAllExternalDescendants(); - final Map tax_map = new HashMap(); - for( final PhylogenyNode n : descs ) { - if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { - return null; - } - final Taxonomy t = n.getNodeData().getTaxonomy(); - if ( tax_map.containsKey( t ) ) { - tax_map.put( t, tax_map.get( t ) + 1 ); - } - else { - tax_map.put( t, 1 ); - } - } - return tax_map; - } - - /** - * Arranges the order of childern for each node of this Phylogeny in such a - * way that either the branch with more children is on top (right) or on - * bottom (left), dependent on the value of boolean order. - * - * @param order - * decides in which direction to order - * @param pri - */ - public static void orderAppearance( final PhylogenyNode n, - final boolean order, - final boolean order_ext_alphabetically, - final DESCENDANT_SORT_PRIORITY pri ) { - if ( n.isExternal() ) { - return; - } - else { - PhylogenyNode temp = null; - if ( ( n.getNumberOfDescendants() == 2 ) - && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() ) - && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) { - temp = n.getChildNode1(); - n.setChild1( n.getChildNode2() ); - n.setChild2( temp ); - } - else if ( order_ext_alphabetically ) { - boolean all_ext = true; - for( final PhylogenyNode i : n.getDescendants() ) { - if ( !i.isExternal() ) { - all_ext = false; - break; - } - } - if ( all_ext ) { - PhylogenyMethods.sortNodeDescendents( n, pri ); - } - } - for( int i = 0; i < n.getNumberOfDescendants(); ++i ) { - orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri ); - } - } - } - - public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) { - for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - double red = 0.0; - double green = 0.0; - double blue = 0.0; - int n = 0; - if ( node.isInternal() ) { - //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) { - for( int i = 0; i < node.getNumberOfDescendants(); ++i ) { - final PhylogenyNode child_node = node.getChildNode( i ); - final Color child_color = getBranchColorValue( child_node ); - if ( child_color != null ) { - ++n; - red += child_color.getRed(); - green += child_color.getGreen(); - blue += child_color.getBlue(); - } - } - setBranchColorValue( node, - new Color( ForesterUtil.roundToInt( red / n ), - ForesterUtil.roundToInt( green / n ), - ForesterUtil.roundToInt( blue / n ) ) ); - } - } - } - - public static final void preOrderReId( final Phylogeny phy ) { - if ( phy.isEmpty() ) { - return; - } - phy.setIdToNodeMap( null ); - long i = PhylogenyNode.getNodeCount(); - for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) { - it.next().setId( i++ ); - } - PhylogenyNode.setNodeCount( i ); - } - - public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException { - final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance(); - final Phylogeny[] trees = factory.create( file, parser ); - if ( ( trees == null ) || ( trees.length == 0 ) ) { - throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file ); - } - return trees; - } - - public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List files ) - throws IOException { - final List tree_list = new ArrayList(); - for( final File file : files ) { - final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance(); - final Phylogeny[] trees = factory.create( file, parser ); - if ( ( trees == null ) || ( trees.length == 0 ) ) { - throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file ); - } - tree_list.addAll( Arrays.asList( trees ) ); - } - return tree_list.toArray( new Phylogeny[ tree_list.size() ] ); - } - - public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) { - if ( remove_me.isRoot() ) { - if ( remove_me.getNumberOfDescendants() == 1 ) { - final PhylogenyNode desc = remove_me.getDescendants().get( 0 ); - desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(), - desc.getDistanceToParent() ) ); - desc.setParent( null ); - phylogeny.setRoot( desc ); - phylogeny.clearHashIdToNodeMap(); - } - else { - throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" ); - } - } - else if ( remove_me.isExternal() ) { - phylogeny.deleteSubtree( remove_me, false ); - phylogeny.clearHashIdToNodeMap(); - phylogeny.externalNodesHaveChanged(); - } - else { - final PhylogenyNode parent = remove_me.getParent(); - final List descs = remove_me.getDescendants(); - parent.removeChildNode( remove_me ); - for( final PhylogenyNode desc : descs ) { - parent.addAsChild( desc ); - desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(), - desc.getDistanceToParent() ) ); - } - remove_me.setParent( null ); - phylogeny.clearHashIdToNodeMap(); - phylogeny.externalNodesHaveChanged(); - } - } - - public static List searchData( final String query, - final Phylogeny phy, - final boolean case_sensitive, - final boolean partial, - final boolean search_domains ) { - final List nodes = new ArrayList(); - if ( phy.isEmpty() || ( query == null ) ) { - return nodes; - } - if ( ForesterUtil.isEmpty( query ) ) { - return nodes; - } - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - boolean match = false; - if ( match( node.getName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && ( node.getNodeData().getTaxonomy().getIdentifier() != null ) - && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(), - query, - case_sensitive, - partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) { - final List syns = node.getNodeData().getTaxonomy().getSynonyms(); - I: for( final String syn : syns ) { - if ( match( syn, query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match - && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getAccession() != null ) - && match( node.getNodeData().getSequence().getAccession().getValue(), - query, - case_sensitive, - partial ) ) { - match = true; - } - if ( search_domains && !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) { - final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture(); - I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) { - if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - // - if ( !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getAnnotations() != null ) ) { - for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) { - if ( match( ann.getDesc(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( ann.getRef(), query, case_sensitive, partial ) ) { - match = true; - break; - } - } - } - if ( !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) { - for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) { - if ( match( x.getComment(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( x.getSource(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( x.getValue(), query, case_sensitive, partial ) ) { - match = true; - break; - } - } - } - // - if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) { - Iterator it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator(); - I: while ( it.hasNext() ) { - if ( match( it.next(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator(); - I: while ( it.hasNext() ) { - if ( match( it.next(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - if ( match ) { - nodes.add( node ); - } - } - return nodes; - } - - public static List searchDataLogicalAnd( final String[] queries, - final Phylogeny phy, - final boolean case_sensitive, - final boolean partial, - final boolean search_domains ) { - final List nodes = new ArrayList(); - if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) { - return nodes; - } - for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { - final PhylogenyNode node = iter.next(); - boolean all_matched = true; - for( final String query : queries ) { - boolean match = false; - if ( ForesterUtil.isEmpty( query ) ) { - continue; - } - if ( match( node.getName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && ( node.getNodeData().getTaxonomy().getIdentifier() != null ) - && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(), - query, - case_sensitive, - partial ) ) { - match = true; - } - else if ( node.getNodeData().isHasTaxonomy() - && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) { - final List syns = node.getNodeData().getTaxonomy().getSynonyms(); - I: for( final String syn : syns ) { - if ( match( syn, query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match && node.getNodeData().isHasSequence() - && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) { - match = true; - } - if ( !match - && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getAccession() != null ) - && match( node.getNodeData().getSequence().getAccession().getValue(), - query, - case_sensitive, - partial ) ) { - match = true; - } - if ( search_domains && !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) { - final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture(); - I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) { - if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - // - if ( !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getAnnotations() != null ) ) { - for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) { - if ( match( ann.getDesc(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( ann.getRef(), query, case_sensitive, partial ) ) { - match = true; - break; - } - } - } - if ( !match && node.getNodeData().isHasSequence() - && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) { - for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) { - if ( match( x.getComment(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( x.getSource(), query, case_sensitive, partial ) ) { - match = true; - break; - } - if ( match( x.getValue(), query, case_sensitive, partial ) ) { - match = true; - break; - } - } - } - // - if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) { - Iterator it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator(); - I: while ( it.hasNext() ) { - if ( match( it.next(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator(); - I: while ( it.hasNext() ) { - if ( match( it.next(), query, case_sensitive, partial ) ) { - match = true; - break I; - } - } - } - if ( !match ) { - all_matched = false; - break; - } - } - if ( all_matched ) { - nodes.add( node ); - } - } - return nodes; - } - - public static void setAllIndicatorsToZero( final Phylogeny phy ) { - for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) { - it.next().setIndicator( ( byte ) 0 ); - } - } - - /** - * Convenience method. - * Sets value for the first confidence value (created if not present, values overwritten otherwise). - */ - public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) { - setConfidence( node, bootstrap_confidence_value, "bootstrap" ); - } - - public static void setBranchColorValue( final PhylogenyNode node, final Color color ) { - if ( node.getBranchData().getBranchColor() == null ) { - node.getBranchData().setBranchColor( new BranchColor() ); - } - node.getBranchData().getBranchColor().setValue( color ); - } - - /** - * Convenience method - */ - public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) { - node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) ); - } - - /** - * Convenience method. - * Sets value for the first confidence value (created if not present, values overwritten otherwise). - */ - public static void setConfidence( final PhylogenyNode node, final double confidence_value ) { - setConfidence( node, confidence_value, "" ); - } - - /** - * Convenience method. - * Sets value for the first confidence value (created if not present, values overwritten otherwise). - */ - public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) { - Confidence c = null; - if ( node.getBranchData().getNumberOfConfidences() > 0 ) { - c = node.getBranchData().getConfidence( 0 ); - } - else { - c = new Confidence(); - node.getBranchData().addConfidence( c ); - } - c.setType( type ); - c.setValue( confidence_value ); - } - - public static void setScientificName( final PhylogenyNode node, final String scientific_name ) { - if ( !node.getNodeData().isHasTaxonomy() ) { - node.getNodeData().setTaxonomy( new Taxonomy() ); - } - node.getNodeData().getTaxonomy().setScientificName( scientific_name ); - } - - /** - * Convenience method to set the taxonomy code of a phylogeny node. - * - * - * @param node - * @param taxonomy_code - * @throws PhyloXmlDataFormatException - */ - public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code ) - throws PhyloXmlDataFormatException { - if ( !node.getNodeData().isHasTaxonomy() ) { - node.getNodeData().setTaxonomy( new Taxonomy() ); - } - node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code ); - } - - final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) { - class PhylogenyNodeSortTaxonomyPriority implements Comparator { - - @Override - public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { - if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { - return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { - return n1.getNodeData().getTaxonomy().getTaxonomyCode() - .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { - return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); - } - } - if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { - return n1.getNodeData().getSequence().getName().toLowerCase() - .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { - return n1.getNodeData().getSequence().getSymbol() - .compareTo( n2.getNodeData().getSequence().getSymbol() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { - return n1.getNodeData().getSequence().getGeneName() - .compareTo( n2.getNodeData().getSequence().getGeneName() ); - } - if ( ( n1.getNodeData().getSequence().getAccession() != null ) - && ( n2.getNodeData().getSequence().getAccession() != null ) - && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) - && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { - return n1.getNodeData().getSequence().getAccession().getValue() - .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); - } - } - if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { - return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); - } - return 0; - } - } - class PhylogenyNodeSortSequencePriority implements Comparator { - - @Override - public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { - if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { - return n1.getNodeData().getSequence().getName().toLowerCase() - .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { - return n1.getNodeData().getSequence().getSymbol() - .compareTo( n2.getNodeData().getSequence().getSymbol() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { - return n1.getNodeData().getSequence().getGeneName() - .compareTo( n2.getNodeData().getSequence().getGeneName() ); - } - if ( ( n1.getNodeData().getSequence().getAccession() != null ) - && ( n2.getNodeData().getSequence().getAccession() != null ) - && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) - && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { - return n1.getNodeData().getSequence().getAccession().getValue() - .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); - } - } - if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { - return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { - return n1.getNodeData().getTaxonomy().getTaxonomyCode() - .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { - return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); - } - } - if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { - return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); - } - return 0; - } - } - class PhylogenyNodeSortNodeNamePriority implements Comparator { - - @Override - public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { - if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { - return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); - } - if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { - return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { - return n1.getNodeData().getTaxonomy().getTaxonomyCode() - .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { - return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() - .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); - } - } - if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { - return n1.getNodeData().getSequence().getName().toLowerCase() - .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { - return n1.getNodeData().getSequence().getSymbol() - .compareTo( n2.getNodeData().getSequence().getSymbol() ); - } - if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) - && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { - return n1.getNodeData().getSequence().getGeneName() - .compareTo( n2.getNodeData().getSequence().getGeneName() ); - } - if ( ( n1.getNodeData().getSequence().getAccession() != null ) - && ( n2.getNodeData().getSequence().getAccession() != null ) - && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) - && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { - return n1.getNodeData().getSequence().getAccession().getValue() - .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); - } - } - return 0; - } - } - Comparator c; - switch ( pri ) { - case SEQUENCE: - c = new PhylogenyNodeSortSequencePriority(); - break; - case NODE_NAME: - c = new PhylogenyNodeSortNodeNamePriority(); - break; - default: - c = new PhylogenyNodeSortTaxonomyPriority(); - } - final List descs = node.getDescendants(); - Collections.sort( descs, c ); - int i = 0; - for( final PhylogenyNode desc : descs ) { - node.setChildNode( i++, desc ); - } - } - - /** - * Removes from Phylogeny to_be_stripped all external Nodes which are - * associated with a species NOT found in Phylogeny reference. - * - * @param reference - * a reference Phylogeny - * @param to_be_stripped - * Phylogeny to be stripped - * @return nodes removed from to_be_stripped - */ - public static List taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, - final Phylogeny to_be_stripped ) { - final Set ref_ext_taxo = new HashSet(); - for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode n = it.next(); - if ( !n.getNodeData().isHasTaxonomy() ) { - throw new IllegalArgumentException( "no taxonomic data in node: " + n ); - } - if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) { - ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() ); - } - if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) { - ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() ); - } - if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) - && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) { - ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ); - } - } - final ArrayList nodes_to_delete = new ArrayList(); - for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) { - final PhylogenyNode n = it.next(); - if ( !n.getNodeData().isHasTaxonomy() ) { - nodes_to_delete.add( n ); - } - else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) ) - && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) - && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n - .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) { - nodes_to_delete.add( n ); - } - } - for( final PhylogenyNode n : nodes_to_delete ) { - to_be_stripped.deleteSubtree( n, true ); - } - to_be_stripped.clearHashIdToNodeMap(); - to_be_stripped.externalNodesHaveChanged(); - return nodes_to_delete; - } - - final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) { - final PhylogenyNodeIterator it = phy.iteratorPostorder(); - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) { - double value = -1; - try { - value = Double.parseDouble( n.getName() ); - } - catch ( final NumberFormatException e ) { - throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: " - + e.getLocalizedMessage() ); - } - if ( value >= 0.0 ) { - n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) ); - n.setName( "" ); - } - } - } - } - - final static public boolean isInternalNamesLookLikeConfidences( final Phylogeny phy ) { - final PhylogenyNodeIterator it = phy.iteratorPostorder(); - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - if ( !n.isExternal() && !n.isRoot() ) { - if ( !ForesterUtil.isEmpty( n.getName() ) ) { - double value = -1; - try { - value = Double.parseDouble( n.getName() ); - } - catch ( final NumberFormatException e ) { - return false; - } - if ( ( value < 0.0 ) || ( value > 100 ) ) { - return false; - } - } - } - } - return true; - } - - final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy, final String confidence_type ) { - final PhylogenyNodeIterator it = phy.iteratorPostorder(); - while ( it.hasNext() ) { - transferInternalNodeNameToConfidence( confidence_type, it.next() ); - } - } - - private static void transferInternalNodeNameToConfidence( final String confidence_type, final PhylogenyNode n ) { - if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) { - if ( !ForesterUtil.isEmpty( n.getName() ) ) { - double d = -1.0; - try { - d = Double.parseDouble( n.getName() ); - } - catch ( final Exception e ) { - d = -1.0; - } - if ( d >= 0.0 ) { - n.getBranchData().addConfidence( new Confidence( d, confidence_type ) ); - n.setName( "" ); - } - } - } - } - - final static public void transferNodeNameToField( final Phylogeny phy, - final PhylogenyNodeField field, - final boolean external_only ) throws PhyloXmlDataFormatException { - final PhylogenyNodeIterator it = phy.iteratorPostorder(); - while ( it.hasNext() ) { - final PhylogenyNode n = it.next(); - if ( external_only && n.isInternal() ) { - continue; - } - final String name = n.getName().trim(); - if ( !ForesterUtil.isEmpty( name ) ) { - switch ( field ) { - case TAXONOMY_CODE: - n.setName( "" ); - setTaxonomyCode( n, name ); - break; - case TAXONOMY_SCIENTIFIC_NAME: - n.setName( "" ); - if ( !n.getNodeData().isHasTaxonomy() ) { - n.getNodeData().setTaxonomy( new Taxonomy() ); - } - n.getNodeData().getTaxonomy().setScientificName( name ); - break; - case TAXONOMY_COMMON_NAME: - n.setName( "" ); - if ( !n.getNodeData().isHasTaxonomy() ) { - n.getNodeData().setTaxonomy( new Taxonomy() ); - } - n.getNodeData().getTaxonomy().setCommonName( name ); - break; - case SEQUENCE_SYMBOL: - n.setName( "" ); - if ( !n.getNodeData().isHasSequence() ) { - n.getNodeData().setSequence( new Sequence() ); - } - n.getNodeData().getSequence().setSymbol( name ); - break; - case SEQUENCE_NAME: - n.setName( "" ); - if ( !n.getNodeData().isHasSequence() ) { - n.getNodeData().setSequence( new Sequence() ); - } - n.getNodeData().getSequence().setName( name ); - break; - case TAXONOMY_ID_UNIPROT_1: { - if ( !n.getNodeData().isHasTaxonomy() ) { - n.getNodeData().setTaxonomy( new Taxonomy() ); - } - String id = name; - final int i = name.indexOf( '_' ); - if ( i > 0 ) { - id = name.substring( 0, i ); - } - else { - n.setName( "" ); - } - n.getNodeData().getTaxonomy() - .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) ); - break; - } - case TAXONOMY_ID_UNIPROT_2: { - if ( !n.getNodeData().isHasTaxonomy() ) { - n.getNodeData().setTaxonomy( new Taxonomy() ); - } - String id = name; - final int i = name.indexOf( '_' ); - if ( i > 0 ) { - id = name.substring( i + 1, name.length() ); - } - else { - n.setName( "" ); - } - n.getNodeData().getTaxonomy() - .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) ); - break; - } - case TAXONOMY_ID: { - if ( !n.getNodeData().isHasTaxonomy() ) { - n.getNodeData().setTaxonomy( new Taxonomy() ); - } - n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) ); - break; - } - } - } - } - } - - static double addPhylogenyDistances( final double a, final double b ) { - if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) { - return a + b; - } - else if ( a >= 0.0 ) { - return a; - } - else if ( b >= 0.0 ) { - return b; - } - return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT; - } - - static double calculateDistanceToAncestor( final PhylogenyNode anc, PhylogenyNode desc ) { - double d = 0; - boolean all_default = true; - while ( anc != desc ) { - if ( desc.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) { - d += desc.getDistanceToParent(); - if ( all_default ) { - all_default = false; - } - } - desc = desc.getParent(); - } - if ( all_default ) { - return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT; - } - return d; - } - - /** - * Deep copies the phylogeny originating from this node. - */ - static PhylogenyNode copySubTree( final PhylogenyNode source ) { - if ( source == null ) { - return null; - } - else { - final PhylogenyNode newnode = source.copyNodeData(); - if ( !source.isExternal() ) { - for( int i = 0; i < source.getNumberOfDescendants(); ++i ) { - newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) ); - } - } - return newnode; - } - } - - /** - * Shallow copies the phylogeny originating from this node. - */ - static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) { - if ( source == null ) { - return null; - } - else { - final PhylogenyNode newnode = source.copyNodeDataShallow(); - if ( !source.isExternal() ) { - for( int i = 0; i < source.getNumberOfDescendants(); ++i ) { - newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) ); - } - } - return newnode; - } - } - - private final static List divideIntoSubTreesHelper( final PhylogenyNode node, - final double min_distance_to_root ) { - final List l = new ArrayList(); - final PhylogenyNode r = moveTowardsRoot( node, min_distance_to_root ); - for( final PhylogenyNode ext : r.getAllExternalDescendants() ) { - if ( ext.getIndicator() != 0 ) { - throw new RuntimeException( "this should not have happened" ); - } - ext.setIndicator( ( byte ) 1 ); - l.add( ext ); - } - return l; - } - - /** - * Calculates the distance between PhylogenyNodes n1 and n2. - * PRECONDITION: n1 is a descendant of n2. - * - * @param n1 - * a descendant of n2 - * @param n2 - * @return distance between n1 and n2 - */ - private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) { - double d = 0.0; - while ( n1 != n2 ) { - if ( n1.getDistanceToParent() > 0.0 ) { - d += n1.getDistanceToParent(); - } - n1 = n1.getParent(); - } - return d; - } - - private static boolean match( final String s, - final String query, - final boolean case_sensitive, - final boolean partial ) { - if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) { - return false; - } - String my_s = s.trim(); - String my_query = query.trim(); - if ( !case_sensitive ) { - my_s = my_s.toLowerCase(); - my_query = my_query.toLowerCase(); - } - if ( partial ) { - return my_s.indexOf( my_query ) >= 0; - } - else { - return Pattern.compile( "(\\b|_)" + Pattern.quote( my_query ) + "(\\b|_)" ).matcher( my_s ).find(); - } - } - - private final static PhylogenyNode moveTowardsRoot( final PhylogenyNode node, final double min_distance_to_root ) { - PhylogenyNode n = node; - PhylogenyNode prev = node; - while ( min_distance_to_root < n.calculateDistanceToRoot() ) { - prev = n; - n = n.getParent(); - } - return prev; - } - - public static enum DESCENDANT_SORT_PRIORITY { - NODE_NAME, SEQUENCE, TAXONOMY; - } - - public static enum PhylogenyNodeField { - CLADE_NAME, - SEQUENCE_NAME, - SEQUENCE_SYMBOL, - TAXONOMY_CODE, - TAXONOMY_COMMON_NAME, - TAXONOMY_ID, - TAXONOMY_ID_UNIPROT_1, - TAXONOMY_ID_UNIPROT_2, - TAXONOMY_SCIENTIFIC_NAME; - } -} +// $Id: +// FORESTER -- software libraries and applications +// for evolutionary biology research and applications. +// +// Copyright (C) 2008-2009 Christian M. Zmasek +// Copyright (C) 2008-2009 Burnham Institute for Medical Research +// All rights reserved +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +// +// Contact: phylosoft @ gmail . com +// WWW: https://sites.google.com/site/cmzmasek/home/software/forester + +package org.forester.phylogeny; + +import java.awt.Color; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.forester.io.parsers.FastaParser; +import org.forester.io.parsers.PhylogenyParser; +import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException; +import org.forester.io.parsers.phyloxml.PhyloXmlUtil; +import org.forester.io.parsers.util.PhylogenyParserException; +import org.forester.phylogeny.data.Accession; +import org.forester.phylogeny.data.Annotation; +import org.forester.phylogeny.data.BranchColor; +import org.forester.phylogeny.data.BranchWidth; +import org.forester.phylogeny.data.Confidence; +import org.forester.phylogeny.data.DomainArchitecture; +import org.forester.phylogeny.data.Event; +import org.forester.phylogeny.data.Identifier; +import org.forester.phylogeny.data.PhylogenyDataUtil; +import org.forester.phylogeny.data.Sequence; +import org.forester.phylogeny.data.Taxonomy; +import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory; +import org.forester.phylogeny.factories.PhylogenyFactory; +import org.forester.phylogeny.iterators.PhylogenyNodeIterator; +import org.forester.util.BasicDescriptiveStatistics; +import org.forester.util.DescriptiveStatistics; +import org.forester.util.ForesterUtil; + +public class PhylogenyMethods { + + private PhylogenyMethods() { + // Hidden constructor. + } + + @Override + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } + + public static boolean extractFastaInformation( final Phylogeny phy ) { + boolean could_extract = false; + for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + if ( !ForesterUtil.isEmpty( node.getName() ) ) { + final Matcher name_m = FastaParser.FASTA_DESC_LINE.matcher( node.getName() ); + if ( name_m.lookingAt() ) { + could_extract = true; + final String acc_source = name_m.group( 1 ); + final String acc = name_m.group( 2 ); + final String seq_name = name_m.group( 3 ); + final String tax_sn = name_m.group( 4 ); + if ( !ForesterUtil.isEmpty( acc_source ) && !ForesterUtil.isEmpty( acc ) ) { + ForesterUtil.ensurePresenceOfSequence( node ); + node.getNodeData().getSequence( 0 ).setAccession( new Accession( acc, acc_source ) ); + } + if ( !ForesterUtil.isEmpty( seq_name ) ) { + ForesterUtil.ensurePresenceOfSequence( node ); + node.getNodeData().getSequence( 0 ).setName( seq_name ); + } + if ( !ForesterUtil.isEmpty( tax_sn ) ) { + ForesterUtil.ensurePresenceOfTaxonomy( node ); + node.getNodeData().getTaxonomy( 0 ).setScientificName( tax_sn ); + } + } + } + } + return could_extract; + } + + public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) { + final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) { + stats.addValue( n.getDistanceToParent() ); + } + } + return stats; + } + + public static List calculatConfidenceStatistics( final Phylogeny phy ) { + final List stats = new ArrayList(); + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( !n.isExternal() && !n.isRoot() ) { + if ( n.getBranchData().isHasConfidences() ) { + for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) { + final Confidence c = n.getBranchData().getConfidences().get( i ); + if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) { + stats.add( i, new BasicDescriptiveStatistics() ); + } + if ( !ForesterUtil.isEmpty( c.getType() ) ) { + if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) { + if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) { + throw new IllegalArgumentException( "support values in node [" + n.toString() + + "] appear inconsistently ordered" ); + } + } + stats.get( i ).setDescription( c.getType() ); + } + stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 ); + } + } + } + } + return stats; + } + + /** + * Calculates the distance between PhylogenyNodes node1 and node2. + * + * + * @param node1 + * @param node2 + * @return distance between node1 and node2 + */ + public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) { + final PhylogenyNode lca = calculateLCA( node1, node2 ); + final PhylogenyNode n1 = node1; + final PhylogenyNode n2 = node2; + return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) ); + } + + /** + * Returns the LCA of PhylogenyNodes node1 and node2. + * + * + * @param node1 + * @param node2 + * @return LCA of node1 and node2 + */ + public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) { + if ( node1 == null ) { + throw new IllegalArgumentException( "first argument (node) is null" ); + } + if ( node2 == null ) { + throw new IllegalArgumentException( "second argument (node) is null" ); + } + if ( node1 == node2 ) { + return node1; + } + if ( ( node1.getParent() == node2.getParent() ) ) { + return node1.getParent(); + } + int depth1 = node1.calculateDepth(); + int depth2 = node2.calculateDepth(); + while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) { + if ( depth1 > depth2 ) { + node1 = node1.getParent(); + depth1--; + } + else if ( depth2 > depth1 ) { + node2 = node2.getParent(); + depth2--; + } + else { + if ( node1 == node2 ) { + return node1; + } + node1 = node1.getParent(); + node2 = node2.getParent(); + depth1--; + depth2--; + } + } + throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" ); + } + + /** + * Returns the LCA of PhylogenyNodes node1 and node2. + * Precondition: ids are in pre-order (or level-order). + * + * + * @param node1 + * @param node2 + * @return LCA of node1 and node2 + */ + public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) { + if ( node1 == null ) { + throw new IllegalArgumentException( "first argument (node) is null" ); + } + if ( node2 == null ) { + throw new IllegalArgumentException( "second argument (node) is null" ); + } + while ( node1 != node2 ) { + if ( node1.getId() > node2.getId() ) { + node1 = node1.getParent(); + } + else { + node2 = node2.getParent(); + } + } + return node1; + } + + public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) { + if ( node.isExternal() ) { + return 0; + } + short max = 0; + for( PhylogenyNode d : node.getAllExternalDescendants() ) { + short steps = 0; + while ( d != node ) { + if ( d.isCollapse() ) { + steps = 0; + } + else { + steps++; + } + d = d.getParent(); + } + if ( max < steps ) { + max = steps; + } + } + return max; + } + + public static int calculateMaxDepth( final Phylogeny phy ) { + int max = 0; + for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + final int steps = node.calculateDepth(); + if ( steps > max ) { + max = steps; + } + } + return max; + } + + public static double calculateMaxDistanceToRoot( final Phylogeny phy ) { + double max = 0.0; + for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + final double d = node.calculateDistanceToRoot(); + if ( d > max ) { + max = d; + } + } + return max; + } + + public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) { + final List descs = node.getAllExternalDescendants(); + int x = 0; + for( final PhylogenyNode n : descs ) { + if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { + x++; + } + } + return x; + } + + public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) { + final DescriptiveStatistics stats = new BasicDescriptiveStatistics(); + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( !n.isExternal() ) { + stats.addValue( n.getNumberOfDescendants() ); + } + } + return stats; + } + + public final static void collapseSubtreeStructure( final PhylogenyNode n ) { + final List eds = n.getAllExternalDescendants(); + final List d = new ArrayList(); + for( final PhylogenyNode ed : eds ) { + d.add( calculateDistanceToAncestor( n, ed ) ); + } + for( int i = 0; i < eds.size(); ++i ) { + n.setChildNode( i, eds.get( i ) ); + eds.get( i ).setDistanceToParent( d.get( i ) ); + } + } + + public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) { + int count = 0; + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) { + count++; + } + } + return count; + } + + public static int countNumberOfPolytomies( final Phylogeny phy ) { + int count = 0; + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) { + count++; + } + } + return count; + } + + public static final HashMap createNameToExtNodeMap( final Phylogeny phy ) { + final HashMap nodes = new HashMap(); + final List ext = phy.getExternalNodes(); + for( final PhylogenyNode n : ext ) { + nodes.put( n.getName(), n ); + } + return nodes; + } + + public static void deleteExternalNodesNegativeSelection( final Set to_delete, final Phylogeny phy ) { + for( final Long id : to_delete ) { + phy.deleteSubtree( phy.getNode( id ), true ); + } + phy.clearHashIdToNodeMap(); + phy.externalNodesHaveChanged(); + } + + public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p ) + throws IllegalArgumentException { + for( final String element : node_names_to_delete ) { + if ( ForesterUtil.isEmpty( element ) ) { + continue; + } + List nodes = null; + nodes = p.getNodes( element ); + final Iterator it = nodes.iterator(); + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + if ( !n.isExternal() ) { + throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" ); + } + p.deleteSubtree( n, true ); + } + } + p.clearHashIdToNodeMap(); + p.externalNodesHaveChanged(); + } + + public static List deleteExternalNodesPositiveSelection( final String[] node_names_to_keep, + final Phylogeny p ) { + final PhylogenyNodeIterator it = p.iteratorExternalForward(); + final String[] to_delete = new String[ p.getNumberOfExternalNodes() ]; + int i = 0; + Arrays.sort( node_names_to_keep ); + while ( it.hasNext() ) { + final String curent_name = it.next().getName(); + if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) { + to_delete[ i++ ] = curent_name; + } + } + PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p ); + final List deleted = new ArrayList(); + for( final String n : to_delete ) { + if ( !ForesterUtil.isEmpty( n ) ) { + deleted.add( n ); + } + } + return deleted; + } + + public static void deleteExternalNodesPositiveSelectionT( final List species_to_keep, final Phylogeny phy ) { + final Set to_delete = new HashSet(); + for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode n = it.next(); + if ( n.getNodeData().isHasTaxonomy() ) { + if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) { + to_delete.add( n.getId() ); + } + } + else { + throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" ); + } + } + deleteExternalNodesNegativeSelection( to_delete, phy ); + } + + final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) { + final ArrayList to_delete = new ArrayList(); + for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) { + final PhylogenyNode n = iter.next(); + if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) { + to_delete.add( n ); + } + } + for( final PhylogenyNode d : to_delete ) { + PhylogenyMethods.removeNode( d, phy ); + } + phy.clearHashIdToNodeMap(); + phy.externalNodesHaveChanged(); + } + + final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) { + if ( n.isInternal() ) { + throw new IllegalArgumentException( "node is not external" ); + } + final ArrayList to_delete = new ArrayList(); + for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode i = it.next(); + if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) { + to_delete.add( i ); + } + } + for( final PhylogenyNode d : to_delete ) { + phy.deleteSubtree( d, true ); + } + phy.clearHashIdToNodeMap(); + phy.externalNodesHaveChanged(); + } + + public final static List> divideIntoSubTrees( final Phylogeny phy, + final double min_distance_to_root ) { + if ( min_distance_to_root <= 0 ) { + throw new IllegalArgumentException( "attempt to use min distance to root of: " + min_distance_to_root ); + } + final List> l = new ArrayList>(); + setAllIndicatorsToZero( phy ); + for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode n = it.next(); + if ( n.getIndicator() != 0 ) { + continue; + } + l.add( divideIntoSubTreesHelper( n, min_distance_to_root ) ); + if ( l.isEmpty() ) { + throw new RuntimeException( "this should not have happened" ); + } + } + return l; + } + + public static List getAllDescendants( final PhylogenyNode node ) { + final List descs = new ArrayList(); + final Set encountered = new HashSet(); + if ( !node.isExternal() ) { + final List exts = node.getAllExternalDescendants(); + for( PhylogenyNode current : exts ) { + descs.add( current ); + while ( current != node ) { + current = current.getParent(); + if ( encountered.contains( current.getId() ) ) { + continue; + } + descs.add( current ); + encountered.add( current.getId() ); + } + } + } + return descs; + } + + /** + * + * Convenience method + * + * @param node + * @return + */ + public static Color getBranchColorValue( final PhylogenyNode node ) { + if ( node.getBranchData().getBranchColor() == null ) { + return null; + } + return node.getBranchData().getBranchColor().getValue(); + } + + /** + * Convenience method + */ + public static double getBranchWidthValue( final PhylogenyNode node ) { + if ( !node.getBranchData().isHasBranchWidth() ) { + return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE; + } + return node.getBranchData().getBranchWidth().getValue(); + } + + /** + * Convenience method + */ + public static double getConfidenceValue( final PhylogenyNode node ) { + if ( !node.getBranchData().isHasConfidences() ) { + return Confidence.CONFIDENCE_DEFAULT_VALUE; + } + return node.getBranchData().getConfidence( 0 ).getValue(); + } + + /** + * Convenience method + */ + public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) { + if ( !node.getBranchData().isHasConfidences() ) { + return new double[ 0 ]; + } + final double[] values = new double[ node.getBranchData().getConfidences().size() ]; + int i = 0; + for( final Confidence c : node.getBranchData().getConfidences() ) { + values[ i++ ] = c.getValue(); + } + return values; + } + + final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) { + return calculateLCA( n1, n2 ).getNodeData().getEvent(); + } + + /** + * Returns taxonomy t if all external descendants have + * the same taxonomy t, null otherwise. + * + */ + public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) { + final List descs = node.getAllExternalDescendants(); + Taxonomy tax = null; + for( final PhylogenyNode n : descs ) { + if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { + return null; + } + else if ( tax == null ) { + tax = n.getNodeData().getTaxonomy(); + } + else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) { + return null; + } + } + return tax; + } + + public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) { + final List children = node.getAllExternalDescendants(); + PhylogenyNode farthest = null; + double longest = -Double.MAX_VALUE; + for( final PhylogenyNode child : children ) { + if ( PhylogenyMethods.getDistance( child, node ) > longest ) { + farthest = child; + longest = PhylogenyMethods.getDistance( child, node ); + } + } + return farthest; + } + + // public static PhylogenyMethods getInstance() { + // if ( PhylogenyMethods._instance == null ) { + // PhylogenyMethods._instance = new PhylogenyMethods(); + // } + // return PhylogenyMethods._instance; + // } + /** + * Returns the largest confidence value found on phy. + */ + static public double getMaximumConfidenceValue( final Phylogeny phy ) { + double max = -Double.MAX_VALUE; + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final double s = PhylogenyMethods.getConfidenceValue( iter.next() ); + if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) { + max = s; + } + } + return max; + } + + static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) { + int min = Integer.MAX_VALUE; + int d = 0; + PhylogenyNode n; + for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) { + n = it.next(); + if ( n.isInternal() ) { + d = n.getNumberOfDescendants(); + if ( d < min ) { + min = d; + } + } + } + return min; + } + + /** + * Convenience method for display purposes. + * Not intended for algorithms. + */ + public static String getSpecies( final PhylogenyNode node ) { + if ( !node.getNodeData().isHasTaxonomy() ) { + return ""; + } + else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) { + return node.getNodeData().getTaxonomy().getScientificName(); + } + if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) { + return node.getNodeData().getTaxonomy().getTaxonomyCode(); + } + else { + return node.getNodeData().getTaxonomy().getCommonName(); + } + } + + /** + * Convenience method for display purposes. + * Not intended for algorithms. + */ + public static String getTaxonomyIdentifier( final PhylogenyNode node ) { + if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) { + return ""; + } + return node.getNodeData().getTaxonomy().getIdentifier().getValue(); + } + + public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) { + if ( n.isExternal() ) { + return true; + } + else { + if ( n.isDuplication() ) { + for( final PhylogenyNode desc : n.getDescendants() ) { + if ( !isAllDecendentsAreDuplications( desc ) ) { + return false; + } + } + return true; + } + else { + return false; + } + } + } + + public static boolean isHasExternalDescendant( final PhylogenyNode node ) { + for( int i = 0; i < node.getNumberOfDescendants(); ++i ) { + if ( node.getChildNode( i ).isExternal() ) { + return true; + } + } + return false; + } + + /* + * This is case insensitive. + * + */ + public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax, + final String[] providers ) { + if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) { + final String my_tax_prov = tax.getIdentifier().getProvider(); + for( final String provider : providers ) { + if ( provider.equalsIgnoreCase( my_tax_prov ) ) { + return true; + } + } + return false; + } + else { + return false; + } + } + + public static void midpointRoot( final Phylogeny phylogeny ) { + if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) { + return; + } + int counter = 0; + final int total_nodes = phylogeny.getNodeCount(); + while ( true ) { + if ( ++counter > total_nodes ) { + throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" ); + } + PhylogenyNode a = null; + double da = 0; + double db = 0; + for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) { + final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) ); + final double df = getDistance( f, phylogeny.getRoot() ); + if ( df > 0 ) { + if ( df > da ) { + db = da; + da = df; + a = f; + } + else if ( df > db ) { + db = df; + } + } + } + final double diff = da - db; + if ( diff < 0.000001 ) { + break; + } + double x = da - ( diff / 2.0 ); + while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) { + x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 ); + a = a.getParent(); + } + phylogeny.reRoot( a, x ); + } + phylogeny.recalculateNumberOfExternalDescendants( true ); + } + + public static void normalizeBootstrapValues( final Phylogeny phylogeny, + final double max_bootstrap_value, + final double max_normalized_value ) { + for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + if ( node.isInternal() ) { + final double confidence = getConfidenceValue( node ); + if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) { + if ( confidence >= max_bootstrap_value ) { + setBootstrapConfidence( node, max_normalized_value ); + } + else { + setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value ); + } + } + } + } + } + + public static List obtainAllNodesAsList( final Phylogeny phy ) { + final List nodes = new ArrayList(); + if ( phy.isEmpty() ) { + return nodes; + } + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + nodes.add( iter.next() ); + } + return nodes; + } + + /** + * Returns a map of distinct taxonomies of + * all external nodes of node. + * If at least one of the external nodes has no taxonomy, + * null is returned. + * + */ + public static Map obtainDistinctTaxonomyCounts( final PhylogenyNode node ) { + final List descs = node.getAllExternalDescendants(); + final Map tax_map = new HashMap(); + for( final PhylogenyNode n : descs ) { + if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) { + return null; + } + final Taxonomy t = n.getNodeData().getTaxonomy(); + if ( tax_map.containsKey( t ) ) { + tax_map.put( t, tax_map.get( t ) + 1 ); + } + else { + tax_map.put( t, 1 ); + } + } + return tax_map; + } + + /** + * Arranges the order of childern for each node of this Phylogeny in such a + * way that either the branch with more children is on top (right) or on + * bottom (left), dependent on the value of boolean order. + * + * @param order + * decides in which direction to order + * @param pri + */ + public static void orderAppearance( final PhylogenyNode n, + final boolean order, + final boolean order_ext_alphabetically, + final DESCENDANT_SORT_PRIORITY pri ) { + if ( n.isExternal() ) { + return; + } + else { + PhylogenyNode temp = null; + if ( ( n.getNumberOfDescendants() == 2 ) + && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() ) + && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) { + temp = n.getChildNode1(); + n.setChild1( n.getChildNode2() ); + n.setChild2( temp ); + } + else if ( order_ext_alphabetically ) { + boolean all_ext = true; + for( final PhylogenyNode i : n.getDescendants() ) { + if ( !i.isExternal() ) { + all_ext = false; + break; + } + } + if ( all_ext ) { + PhylogenyMethods.sortNodeDescendents( n, pri ); + } + } + for( int i = 0; i < n.getNumberOfDescendants(); ++i ) { + orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri ); + } + } + } + + public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) { + for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + double red = 0.0; + double green = 0.0; + double blue = 0.0; + int n = 0; + if ( node.isInternal() ) { + //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) { + for( int i = 0; i < node.getNumberOfDescendants(); ++i ) { + final PhylogenyNode child_node = node.getChildNode( i ); + final Color child_color = getBranchColorValue( child_node ); + if ( child_color != null ) { + ++n; + red += child_color.getRed(); + green += child_color.getGreen(); + blue += child_color.getBlue(); + } + } + setBranchColorValue( node, + new Color( ForesterUtil.roundToInt( red / n ), + ForesterUtil.roundToInt( green / n ), + ForesterUtil.roundToInt( blue / n ) ) ); + } + } + } + + public static final void preOrderReId( final Phylogeny phy ) { + if ( phy.isEmpty() ) { + return; + } + phy.setIdToNodeMap( null ); + long i = PhylogenyNode.getNodeCount(); + for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) { + it.next().setId( i++ ); + } + PhylogenyNode.setNodeCount( i ); + } + + public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException { + final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance(); + final Phylogeny[] trees = factory.create( file, parser ); + if ( ( trees == null ) || ( trees.length == 0 ) ) { + throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file ); + } + return trees; + } + + public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List files ) + throws IOException { + final List tree_list = new ArrayList(); + for( final File file : files ) { + final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance(); + final Phylogeny[] trees = factory.create( file, parser ); + if ( ( trees == null ) || ( trees.length == 0 ) ) { + throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file ); + } + tree_list.addAll( Arrays.asList( trees ) ); + } + return tree_list.toArray( new Phylogeny[ tree_list.size() ] ); + } + + public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) { + if ( remove_me.isRoot() ) { + if ( remove_me.getNumberOfDescendants() == 1 ) { + final PhylogenyNode desc = remove_me.getDescendants().get( 0 ); + desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(), + desc.getDistanceToParent() ) ); + desc.setParent( null ); + phylogeny.setRoot( desc ); + phylogeny.clearHashIdToNodeMap(); + } + else { + throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" ); + } + } + else if ( remove_me.isExternal() ) { + phylogeny.deleteSubtree( remove_me, false ); + phylogeny.clearHashIdToNodeMap(); + phylogeny.externalNodesHaveChanged(); + } + else { + final PhylogenyNode parent = remove_me.getParent(); + final List descs = remove_me.getDescendants(); + parent.removeChildNode( remove_me ); + for( final PhylogenyNode desc : descs ) { + parent.addAsChild( desc ); + desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(), + desc.getDistanceToParent() ) ); + } + remove_me.setParent( null ); + phylogeny.clearHashIdToNodeMap(); + phylogeny.externalNodesHaveChanged(); + } + } + + public static List searchData( final String query, + final Phylogeny phy, + final boolean case_sensitive, + final boolean partial, + final boolean search_domains ) { + final List nodes = new ArrayList(); + if ( phy.isEmpty() || ( query == null ) ) { + return nodes; + } + if ( ForesterUtil.isEmpty( query ) ) { + return nodes; + } + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + boolean match = false; + if ( match( node.getName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && ( node.getNodeData().getTaxonomy().getIdentifier() != null ) + && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(), + query, + case_sensitive, + partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) { + final List syns = node.getNodeData().getTaxonomy().getSynonyms(); + I: for( final String syn : syns ) { + if ( match( syn, query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match + && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getAccession() != null ) + && match( node.getNodeData().getSequence().getAccession().getValue(), + query, + case_sensitive, + partial ) ) { + match = true; + } + if ( search_domains && !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) { + final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture(); + I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) { + if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + // + if ( !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getAnnotations() != null ) ) { + for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) { + if ( match( ann.getDesc(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( ann.getRef(), query, case_sensitive, partial ) ) { + match = true; + break; + } + } + } + if ( !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) { + for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) { + if ( match( x.getComment(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( x.getSource(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( x.getValue(), query, case_sensitive, partial ) ) { + match = true; + break; + } + } + } + // + if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) { + Iterator it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator(); + I: while ( it.hasNext() ) { + if ( match( it.next(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator(); + I: while ( it.hasNext() ) { + if ( match( it.next(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + if ( match ) { + nodes.add( node ); + } + } + return nodes; + } + + public static List searchDataLogicalAnd( final String[] queries, + final Phylogeny phy, + final boolean case_sensitive, + final boolean partial, + final boolean search_domains ) { + final List nodes = new ArrayList(); + if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) { + return nodes; + } + for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) { + final PhylogenyNode node = iter.next(); + boolean all_matched = true; + for( final String query : queries ) { + boolean match = false; + if ( ForesterUtil.isEmpty( query ) ) { + continue; + } + if ( match( node.getName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && ( node.getNodeData().getTaxonomy().getIdentifier() != null ) + && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(), + query, + case_sensitive, + partial ) ) { + match = true; + } + else if ( node.getNodeData().isHasTaxonomy() + && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) { + final List syns = node.getNodeData().getTaxonomy().getSynonyms(); + I: for( final String syn : syns ) { + if ( match( syn, query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match && node.getNodeData().isHasSequence() + && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) { + match = true; + } + if ( !match + && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getAccession() != null ) + && match( node.getNodeData().getSequence().getAccession().getValue(), + query, + case_sensitive, + partial ) ) { + match = true; + } + if ( search_domains && !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) { + final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture(); + I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) { + if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + // + if ( !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getAnnotations() != null ) ) { + for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) { + if ( match( ann.getDesc(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( ann.getRef(), query, case_sensitive, partial ) ) { + match = true; + break; + } + } + } + if ( !match && node.getNodeData().isHasSequence() + && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) { + for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) { + if ( match( x.getComment(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( x.getSource(), query, case_sensitive, partial ) ) { + match = true; + break; + } + if ( match( x.getValue(), query, case_sensitive, partial ) ) { + match = true; + break; + } + } + } + // + if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) { + Iterator it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator(); + I: while ( it.hasNext() ) { + if ( match( it.next(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator(); + I: while ( it.hasNext() ) { + if ( match( it.next(), query, case_sensitive, partial ) ) { + match = true; + break I; + } + } + } + if ( !match ) { + all_matched = false; + break; + } + } + if ( all_matched ) { + nodes.add( node ); + } + } + return nodes; + } + + public static void setAllIndicatorsToZero( final Phylogeny phy ) { + for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) { + it.next().setIndicator( ( byte ) 0 ); + } + } + + /** + * Convenience method. + * Sets value for the first confidence value (created if not present, values overwritten otherwise). + */ + public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) { + setConfidence( node, bootstrap_confidence_value, "bootstrap" ); + } + + public static void setBranchColorValue( final PhylogenyNode node, final Color color ) { + if ( node.getBranchData().getBranchColor() == null ) { + node.getBranchData().setBranchColor( new BranchColor() ); + } + node.getBranchData().getBranchColor().setValue( color ); + } + + /** + * Convenience method + */ + public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) { + node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) ); + } + + /** + * Convenience method. + * Sets value for the first confidence value (created if not present, values overwritten otherwise). + */ + public static void setConfidence( final PhylogenyNode node, final double confidence_value ) { + setConfidence( node, confidence_value, "" ); + } + + /** + * Convenience method. + * Sets value for the first confidence value (created if not present, values overwritten otherwise). + */ + public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) { + Confidence c = null; + if ( node.getBranchData().getNumberOfConfidences() > 0 ) { + c = node.getBranchData().getConfidence( 0 ); + } + else { + c = new Confidence(); + node.getBranchData().addConfidence( c ); + } + c.setType( type ); + c.setValue( confidence_value ); + } + + public static void setScientificName( final PhylogenyNode node, final String scientific_name ) { + if ( !node.getNodeData().isHasTaxonomy() ) { + node.getNodeData().setTaxonomy( new Taxonomy() ); + } + node.getNodeData().getTaxonomy().setScientificName( scientific_name ); + } + + /** + * Convenience method to set the taxonomy code of a phylogeny node. + * + * + * @param node + * @param taxonomy_code + * @throws PhyloXmlDataFormatException + */ + public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code ) + throws PhyloXmlDataFormatException { + if ( !node.getNodeData().isHasTaxonomy() ) { + node.getNodeData().setTaxonomy( new Taxonomy() ); + } + node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code ); + } + + final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) { + class PhylogenyNodeSortTaxonomyPriority implements Comparator { + + @Override + public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { + if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { + return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { + return n1.getNodeData().getTaxonomy().getTaxonomyCode() + .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { + return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); + } + } + if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { + return n1.getNodeData().getSequence().getName().toLowerCase() + .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { + return n1.getNodeData().getSequence().getSymbol() + .compareTo( n2.getNodeData().getSequence().getSymbol() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { + return n1.getNodeData().getSequence().getGeneName() + .compareTo( n2.getNodeData().getSequence().getGeneName() ); + } + if ( ( n1.getNodeData().getSequence().getAccession() != null ) + && ( n2.getNodeData().getSequence().getAccession() != null ) + && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) + && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { + return n1.getNodeData().getSequence().getAccession().getValue() + .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); + } + } + if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { + return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); + } + return 0; + } + } + class PhylogenyNodeSortSequencePriority implements Comparator { + + @Override + public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { + if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { + return n1.getNodeData().getSequence().getName().toLowerCase() + .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { + return n1.getNodeData().getSequence().getSymbol() + .compareTo( n2.getNodeData().getSequence().getSymbol() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { + return n1.getNodeData().getSequence().getGeneName() + .compareTo( n2.getNodeData().getSequence().getGeneName() ); + } + if ( ( n1.getNodeData().getSequence().getAccession() != null ) + && ( n2.getNodeData().getSequence().getAccession() != null ) + && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) + && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { + return n1.getNodeData().getSequence().getAccession().getValue() + .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); + } + } + if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { + return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { + return n1.getNodeData().getTaxonomy().getTaxonomyCode() + .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { + return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); + } + } + if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { + return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); + } + return 0; + } + } + class PhylogenyNodeSortNodeNamePriority implements Comparator { + + @Override + public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) { + if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) { + return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() ); + } + if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) { + return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) { + return n1.getNodeData().getTaxonomy().getTaxonomyCode() + .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) { + return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase() + .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() ); + } + } + if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) { + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) { + return n1.getNodeData().getSequence().getName().toLowerCase() + .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) { + return n1.getNodeData().getSequence().getSymbol() + .compareTo( n2.getNodeData().getSequence().getSymbol() ); + } + if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) ) + && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) { + return n1.getNodeData().getSequence().getGeneName() + .compareTo( n2.getNodeData().getSequence().getGeneName() ); + } + if ( ( n1.getNodeData().getSequence().getAccession() != null ) + && ( n2.getNodeData().getSequence().getAccession() != null ) + && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() ) + && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) { + return n1.getNodeData().getSequence().getAccession().getValue() + .compareTo( n2.getNodeData().getSequence().getAccession().getValue() ); + } + } + return 0; + } + } + Comparator c; + switch ( pri ) { + case SEQUENCE: + c = new PhylogenyNodeSortSequencePriority(); + break; + case NODE_NAME: + c = new PhylogenyNodeSortNodeNamePriority(); + break; + default: + c = new PhylogenyNodeSortTaxonomyPriority(); + } + final List descs = node.getDescendants(); + Collections.sort( descs, c ); + int i = 0; + for( final PhylogenyNode desc : descs ) { + node.setChildNode( i++, desc ); + } + } + + /** + * Removes from Phylogeny to_be_stripped all external Nodes which are + * associated with a species NOT found in Phylogeny reference. + * + * @param reference + * a reference Phylogeny + * @param to_be_stripped + * Phylogeny to be stripped + * @return nodes removed from to_be_stripped + */ + public static List taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, + final Phylogeny to_be_stripped ) { + final Set ref_ext_taxo = new HashSet(); + for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode n = it.next(); + if ( !n.getNodeData().isHasTaxonomy() ) { + throw new IllegalArgumentException( "no taxonomic data in node: " + n ); + } + if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) { + ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() ); + } + if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) { + ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() ); + } + if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) + && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) { + ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ); + } + } + final ArrayList nodes_to_delete = new ArrayList(); + for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) { + final PhylogenyNode n = it.next(); + if ( !n.getNodeData().isHasTaxonomy() ) { + nodes_to_delete.add( n ); + } + else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) ) + && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) + && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n + .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) { + nodes_to_delete.add( n ); + } + } + for( final PhylogenyNode n : nodes_to_delete ) { + to_be_stripped.deleteSubtree( n, true ); + } + to_be_stripped.clearHashIdToNodeMap(); + to_be_stripped.externalNodesHaveChanged(); + return nodes_to_delete; + } + + final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) { + final PhylogenyNodeIterator it = phy.iteratorPostorder(); + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) { + double value = -1; + try { + value = Double.parseDouble( n.getName() ); + } + catch ( final NumberFormatException e ) { + throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: " + + e.getLocalizedMessage() ); + } + if ( value >= 0.0 ) { + n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) ); + n.setName( "" ); + } + } + } + } + + final static public boolean isInternalNamesLookLikeConfidences( final Phylogeny phy ) { + final PhylogenyNodeIterator it = phy.iteratorPostorder(); + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + if ( !n.isExternal() && !n.isRoot() ) { + if ( !ForesterUtil.isEmpty( n.getName() ) ) { + double value = -1; + try { + value = Double.parseDouble( n.getName() ); + } + catch ( final NumberFormatException e ) { + return false; + } + if ( ( value < 0.0 ) || ( value > 100 ) ) { + return false; + } + } + } + } + return true; + } + + final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy, final String confidence_type ) { + final PhylogenyNodeIterator it = phy.iteratorPostorder(); + while ( it.hasNext() ) { + transferInternalNodeNameToConfidence( confidence_type, it.next() ); + } + } + + private static void transferInternalNodeNameToConfidence( final String confidence_type, final PhylogenyNode n ) { + if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) { + if ( !ForesterUtil.isEmpty( n.getName() ) ) { + double d = -1.0; + try { + d = Double.parseDouble( n.getName() ); + } + catch ( final Exception e ) { + d = -1.0; + } + if ( d >= 0.0 ) { + n.getBranchData().addConfidence( new Confidence( d, confidence_type ) ); + n.setName( "" ); + } + } + } + } + + final static public void transferNodeNameToField( final Phylogeny phy, + final PhylogenyNodeField field, + final boolean external_only ) throws PhyloXmlDataFormatException { + final PhylogenyNodeIterator it = phy.iteratorPostorder(); + while ( it.hasNext() ) { + final PhylogenyNode n = it.next(); + if ( external_only && n.isInternal() ) { + continue; + } + final String name = n.getName().trim(); + if ( !ForesterUtil.isEmpty( name ) ) { + switch ( field ) { + case TAXONOMY_CODE: + n.setName( "" ); + setTaxonomyCode( n, name ); + break; + case TAXONOMY_SCIENTIFIC_NAME: + n.setName( "" ); + if ( !n.getNodeData().isHasTaxonomy() ) { + n.getNodeData().setTaxonomy( new Taxonomy() ); + } + n.getNodeData().getTaxonomy().setScientificName( name ); + break; + case TAXONOMY_COMMON_NAME: + n.setName( "" ); + if ( !n.getNodeData().isHasTaxonomy() ) { + n.getNodeData().setTaxonomy( new Taxonomy() ); + } + n.getNodeData().getTaxonomy().setCommonName( name ); + break; + case SEQUENCE_SYMBOL: + n.setName( "" ); + if ( !n.getNodeData().isHasSequence() ) { + n.getNodeData().setSequence( new Sequence() ); + } + n.getNodeData().getSequence().setSymbol( name ); + break; + case SEQUENCE_NAME: + n.setName( "" ); + if ( !n.getNodeData().isHasSequence() ) { + n.getNodeData().setSequence( new Sequence() ); + } + n.getNodeData().getSequence().setName( name ); + break; + case TAXONOMY_ID_UNIPROT_1: { + if ( !n.getNodeData().isHasTaxonomy() ) { + n.getNodeData().setTaxonomy( new Taxonomy() ); + } + String id = name; + final int i = name.indexOf( '_' ); + if ( i > 0 ) { + id = name.substring( 0, i ); + } + else { + n.setName( "" ); + } + n.getNodeData().getTaxonomy() + .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) ); + break; + } + case TAXONOMY_ID_UNIPROT_2: { + if ( !n.getNodeData().isHasTaxonomy() ) { + n.getNodeData().setTaxonomy( new Taxonomy() ); + } + String id = name; + final int i = name.indexOf( '_' ); + if ( i > 0 ) { + id = name.substring( i + 1, name.length() ); + } + else { + n.setName( "" ); + } + n.getNodeData().getTaxonomy() + .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) ); + break; + } + case TAXONOMY_ID: { + if ( !n.getNodeData().isHasTaxonomy() ) { + n.getNodeData().setTaxonomy( new Taxonomy() ); + } + n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) ); + break; + } + } + } + } + } + + static double addPhylogenyDistances( final double a, final double b ) { + if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) { + return a + b; + } + else if ( a >= 0.0 ) { + return a; + } + else if ( b >= 0.0 ) { + return b; + } + return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT; + } + + static double calculateDistanceToAncestor( final PhylogenyNode anc, PhylogenyNode desc ) { + double d = 0; + boolean all_default = true; + while ( anc != desc ) { + if ( desc.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) { + d += desc.getDistanceToParent(); + if ( all_default ) { + all_default = false; + } + } + desc = desc.getParent(); + } + if ( all_default ) { + return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT; + } + return d; + } + + /** + * Deep copies the phylogeny originating from this node. + */ + static PhylogenyNode copySubTree( final PhylogenyNode source ) { + if ( source == null ) { + return null; + } + else { + final PhylogenyNode newnode = source.copyNodeData(); + if ( !source.isExternal() ) { + for( int i = 0; i < source.getNumberOfDescendants(); ++i ) { + newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) ); + } + } + return newnode; + } + } + + /** + * Shallow copies the phylogeny originating from this node. + */ + static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) { + if ( source == null ) { + return null; + } + else { + final PhylogenyNode newnode = source.copyNodeDataShallow(); + if ( !source.isExternal() ) { + for( int i = 0; i < source.getNumberOfDescendants(); ++i ) { + newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) ); + } + } + return newnode; + } + } + + private final static List divideIntoSubTreesHelper( final PhylogenyNode node, + final double min_distance_to_root ) { + final List l = new ArrayList(); + final PhylogenyNode r = moveTowardsRoot( node, min_distance_to_root ); + for( final PhylogenyNode ext : r.getAllExternalDescendants() ) { + if ( ext.getIndicator() != 0 ) { + throw new RuntimeException( "this should not have happened" ); + } + ext.setIndicator( ( byte ) 1 ); + l.add( ext ); + } + return l; + } + + /** + * Calculates the distance between PhylogenyNodes n1 and n2. + * PRECONDITION: n1 is a descendant of n2. + * + * @param n1 + * a descendant of n2 + * @param n2 + * @return distance between n1 and n2 + */ + private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) { + double d = 0.0; + while ( n1 != n2 ) { + if ( n1.getDistanceToParent() > 0.0 ) { + d += n1.getDistanceToParent(); + } + n1 = n1.getParent(); + } + return d; + } + + private static boolean match( final String s, + final String query, + final boolean case_sensitive, + final boolean partial ) { + if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) { + return false; + } + String my_s = s.trim(); + String my_query = query.trim(); + if ( !case_sensitive ) { + my_s = my_s.toLowerCase(); + my_query = my_query.toLowerCase(); + } + if ( partial ) { + return my_s.indexOf( my_query ) >= 0; + } + else { + return Pattern.compile( "(\\b|_)" + Pattern.quote( my_query ) + "(\\b|_)" ).matcher( my_s ).find(); + } + } + + private final static PhylogenyNode moveTowardsRoot( final PhylogenyNode node, final double min_distance_to_root ) { + PhylogenyNode n = node; + PhylogenyNode prev = node; + while ( min_distance_to_root < n.calculateDistanceToRoot() ) { + prev = n; + n = n.getParent(); + } + return prev; + } + + public static enum DESCENDANT_SORT_PRIORITY { + NODE_NAME, SEQUENCE, TAXONOMY; + } + + public static enum PhylogenyNodeField { + CLADE_NAME, + SEQUENCE_NAME, + SEQUENCE_SYMBOL, + TAXONOMY_CODE, + TAXONOMY_COMMON_NAME, + TAXONOMY_ID, + TAXONOMY_ID_UNIPROT_1, + TAXONOMY_ID_UNIPROT_2, + TAXONOMY_SCIENTIFIC_NAME; + } +} diff --git a/forester/java/src/org/forester/util/ForesterConstants.java b/forester/java/src/org/forester/util/ForesterConstants.java index 700d120..41ce1f0 100644 --- a/forester/java/src/org/forester/util/ForesterConstants.java +++ b/forester/java/src/org/forester/util/ForesterConstants.java @@ -27,8 +27,8 @@ package org.forester.util; public final class ForesterConstants { - public final static String FORESTER_VERSION = "1.033"; - public final static String FORESTER_DATE = "140514"; + public final static String FORESTER_VERSION = "1.034"; + public final static String FORESTER_DATE = "140605"; public final static String PHYLO_XML_VERSION = "1.10"; public final static String PHYLO_XML_LOCATION = "http://www.phyloxml.org"; public final static String PHYLO_XML_XSD = "phyloxml.xsd"; -- 1.7.10.2