6d4520732bbec2cfcbf5e1a104af8bfa7b823e4e
[jalview.git] / forester / java / src / org / forester / application / phyloxml_converter.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
26
27 package org.forester.application;
28
29 import java.io.File;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.List;
33
34 import org.forester.io.parsers.PhylogenyParser;
35 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
36 import org.forester.io.parsers.nhx.NHXParser;
37 import org.forester.io.parsers.util.ParserUtils;
38 import org.forester.io.writers.PhylogenyWriter;
39 import org.forester.phylogeny.Phylogeny;
40 import org.forester.phylogeny.PhylogenyMethods;
41 import org.forester.phylogeny.PhylogenyMethods.DESCENDANT_SORT_PRIORITY;
42 import org.forester.phylogeny.PhylogenyNode;
43 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
44 import org.forester.phylogeny.factories.PhylogenyFactory;
45 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
46 import org.forester.util.CommandLineArguments;
47 import org.forester.util.ForesterUtil;
48
49 public class phyloxml_converter {
50
51     final static private String  HELP_OPTION_1                     = "help";
52     final static private String  HELP_OPTION_2                     = "h";
53     final static private String  FIELD_OPTION                      = "f";
54     final static private String  FIELD_CLADE_NAME                  = "nn";
55     final static private String  FIELD_TAXONOMY_CODE               = "tc";
56     final static private String  FIELD_TAXONOMY_SCI_NAME           = "sn";
57     final static private String  FIELD_TAXONOMY_COMM_NAME          = "cn";
58     final static private String  FIELD_SEQUENCE_GENE_NAME          = "gn";
59     final static private String  FIELD_SEQUENCE_SYMBOL             = "sy";
60     final static private String  FIELD_UNIPROT_TAXONOMY_ID_SPLIT_1 = "i1";
61     final static private String  FIELD_UNIPROT_TAXONOMY_ID_SPLIT_2 = "i2";
62     final static private String  FIELD_DUMMY                       = "dummy";
63     final static private String  INTERNAL_NAMES_ARE_BOOT_SUPPPORT  = "i";
64     final static private String  MIDPOINT_REROOT                   = "m";
65     final static private String  EXTRACT_TAXONOMY                  = "xt";
66     final static private String  EXTRACT_TAXONOMY_PF               = "xp";
67     final static private String  ORDER_SUBTREES                    = "o";
68     final static private String  NO_TREE_LEVEL_INDENDATION         = "ni";
69     final static private String  REPLACE_UNDER_SCORES              = "ru";
70     final static private String  PRG_NAME                          = "phyloxml_converter";
71     final static private String  PRG_VERSION                       = "1.30";
72     final static private String  PRG_DATE                          = "2011.03.01";
73     final static private String  E_MAIL                            = "phylosoft@gmail.com";
74     final static private String  WWW                               = "www.phylosoft.org/forester/";
75     final static private boolean SPECIAL                           = false;
76
77     public static void main( final String args[] ) {
78         ForesterUtil.printProgramInformation( PRG_NAME, PRG_VERSION, PRG_DATE, E_MAIL, WWW );
79         CommandLineArguments cla = null;
80         try {
81             cla = new CommandLineArguments( args );
82         }
83         catch ( final Exception e ) {
84             ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
85         }
86         if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 ) || ( args.length == 0 ) ) {
87             printHelp();
88             System.exit( 0 );
89         }
90         if ( args.length < 3 ) {
91             System.out.println();
92             System.out.println( "[" + PRG_NAME + "] incorrect number of arguments" );
93             System.out.println();
94             printHelp();
95             System.exit( -1 );
96         }
97         final List<String> allowed_options = new ArrayList<String>();
98         allowed_options.add( NO_TREE_LEVEL_INDENDATION );
99         allowed_options.add( FIELD_OPTION );
100         allowed_options.add( MIDPOINT_REROOT );
101         allowed_options.add( ORDER_SUBTREES );
102         allowed_options.add( INTERNAL_NAMES_ARE_BOOT_SUPPPORT );
103         allowed_options.add( REPLACE_UNDER_SCORES );
104         allowed_options.add( EXTRACT_TAXONOMY );
105         allowed_options.add( EXTRACT_TAXONOMY_PF );
106         if ( cla.getNumberOfNames() != 2 ) {
107             System.out.println();
108             System.out.println( "[" + PRG_NAME + "] incorrect number of arguments" );
109             System.out.println();
110             printHelp();
111             System.exit( -1 );
112         }
113         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
114         if ( dissallowed_options.length() > 0 ) {
115             ForesterUtil.fatalError( PRG_NAME, "unknown option(s): " + dissallowed_options );
116         }
117         final List<String> mandatory_options = new ArrayList<String>();
118         mandatory_options.add( FIELD_OPTION );
119         final String missing_options = cla.validateMandatoryOptionsAsString( mandatory_options );
120         if ( missing_options.length() > 0 ) {
121             ForesterUtil.fatalError( PRG_NAME, "missing option(s): " + missing_options );
122         }
123         if ( !cla.isOptionValueSet( FIELD_OPTION ) ) {
124             System.out.println();
125             printHelp();
126             System.exit( -1 );
127         }
128         final String field_option_value = cla.getOptionValue( FIELD_OPTION );
129         PhylogenyMethods.PhylogenyNodeField field = null;
130         if ( field_option_value.equals( FIELD_CLADE_NAME ) ) {
131             field = PhylogenyMethods.PhylogenyNodeField.CLADE_NAME;
132         }
133         else if ( field_option_value.equals( FIELD_TAXONOMY_CODE ) ) {
134             field = PhylogenyMethods.PhylogenyNodeField.TAXONOMY_CODE;
135         }
136         else if ( field_option_value.equals( FIELD_TAXONOMY_SCI_NAME ) ) {
137             field = PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME;
138         }
139         else if ( field_option_value.equals( FIELD_TAXONOMY_COMM_NAME ) ) {
140             field = PhylogenyMethods.PhylogenyNodeField.TAXONOMY_COMMON_NAME;
141         }
142         else if ( field_option_value.equals( FIELD_SEQUENCE_GENE_NAME ) ) {
143             field = PhylogenyMethods.PhylogenyNodeField.SEQUENCE_NAME;
144         }
145         else if ( field_option_value.equals( FIELD_SEQUENCE_SYMBOL ) ) {
146             field = PhylogenyMethods.PhylogenyNodeField.SEQUENCE_SYMBOL;
147         }
148         else if ( field_option_value.equals( FIELD_UNIPROT_TAXONOMY_ID_SPLIT_1 ) ) {
149             field = PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID_UNIPROT_1;
150         }
151         else if ( field_option_value.equals( FIELD_UNIPROT_TAXONOMY_ID_SPLIT_2 ) ) {
152             field = PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID_UNIPROT_2;
153         }
154         else if ( field_option_value.equals( FIELD_DUMMY ) ) {
155         }
156         else {
157             ForesterUtil.fatalError( PRG_NAME, "unknown value for -\"" + FIELD_OPTION + "\" option: \""
158                     + field_option_value + "\"" );
159         }
160         boolean int_values_are_boots = false;
161         if ( cla.isOptionSet( INTERNAL_NAMES_ARE_BOOT_SUPPPORT ) ) {
162             int_values_are_boots = true;
163         }
164         boolean midpoint_reroot = false;
165         if ( cla.isOptionSet( MIDPOINT_REROOT ) ) {
166             midpoint_reroot = true;
167         }
168         boolean order_subtrees = false;
169         if ( cla.isOptionSet( ORDER_SUBTREES ) ) {
170             order_subtrees = true;
171         }
172         boolean replace_underscores = false;
173         if ( cla.isOptionSet( REPLACE_UNDER_SCORES ) ) {
174             replace_underscores = true;
175         }
176         boolean no_indendation = false;
177         if ( cla.isOptionSet( NO_TREE_LEVEL_INDENDATION ) ) {
178             no_indendation = true;
179         }
180         boolean extr_taxonomy = false;
181         if ( cla.isOptionSet( EXTRACT_TAXONOMY ) ) {
182             extr_taxonomy = true;
183         }
184         boolean extr_taxonomy_pf_only = false;
185         if ( cla.isOptionSet( EXTRACT_TAXONOMY_PF ) ) {
186             extr_taxonomy_pf_only = true;
187         }
188         final File infile = cla.getFile( 0 );
189         final File outfile = cla.getFile( 1 );
190         if ( outfile.exists() ) {
191             ForesterUtil.fatalError( PRG_NAME, "[" + outfile + "] already exists" );
192         }
193         if ( !infile.exists() ) {
194             ForesterUtil.fatalError( PRG_NAME, "[" + infile + "] does not exist" );
195         }
196         Phylogeny[] phys = null;
197         try {
198             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
199             final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType( infile, true );
200             if ( parser instanceof NHXParser ) {
201                 if ( ( field != PhylogenyMethods.PhylogenyNodeField.TAXONOMY_CODE )
202                         && ( field != PhylogenyMethods.PhylogenyNodeField.TAXONOMY_COMMON_NAME )
203                         && ( field != PhylogenyMethods.PhylogenyNodeField.TAXONOMY_SCIENTIFIC_NAME ) ) {
204                     if ( extr_taxonomy_pf_only ) {
205                         ( ( NHXParser ) parser )
206                                 .setTaxonomyExtraction( PhylogenyMethods.TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY );
207                         replace_underscores = false;
208                     }
209                     else if ( extr_taxonomy ) {
210                         ( ( NHXParser ) parser ).setTaxonomyExtraction( PhylogenyMethods.TAXONOMY_EXTRACTION.YES );
211                         replace_underscores = false;
212                     }
213                 }
214                 else {
215                     ( ( NHXParser ) parser ).setTaxonomyExtraction( PhylogenyMethods.TAXONOMY_EXTRACTION.NO );
216                 }
217                 ( ( NHXParser ) parser ).setReplaceUnderscores( replace_underscores );
218                 ( ( NHXParser ) parser ).setIgnoreQuotes( false );
219             }
220             else if ( parser instanceof NexusPhylogeniesParser ) {
221                 ( ( NexusPhylogeniesParser ) parser ).setReplaceUnderscores( replace_underscores );
222                 ( ( NexusPhylogeniesParser ) parser ).setIgnoreQuotes( false );
223             }
224             phys = factory.create( infile, parser );
225         }
226         catch ( final IOException e ) {
227             ForesterUtil.fatalError( PRG_NAME, "failed to read phylogeny from [" + infile + "]: " + e.getMessage() );
228         }
229         if ( SPECIAL ) {
230             for( final Phylogeny phy : phys ) {
231                 performSpecialProcessing( phy );
232             }
233         }
234         if ( int_values_are_boots ) {
235             for( final Phylogeny phy : phys ) {
236                 PhylogenyMethods.transferInternalNamesToBootstrapSupport( phy );
237             }
238         }
239         if ( field != null ) {
240             for( final Phylogeny phy : phys ) {
241                 PhylogenyMethods.transferNodeNameToField( phy, field );
242             }
243         }
244         if ( midpoint_reroot ) {
245             try {
246                 for( final Phylogeny phy : phys ) {
247                     PhylogenyMethods.midpointRoot( phy );
248                 }
249             }
250             catch ( final Exception e ) {
251                 System.out.println( "" );
252                 ForesterUtil.printWarningMessage( PRG_NAME, "midpoint rerooting failed: " + e.getLocalizedMessage() );
253             }
254         }
255         if ( order_subtrees ) {
256             for( final Phylogeny phy : phys ) {
257                 PhylogenyMethods.orderAppearance( phy.getRoot(), true, true, DESCENDANT_SORT_PRIORITY.TAXONOMY );
258                 phy.externalNodesHaveChanged();
259                 phy.hashIDs();
260                 phy.recalculateNumberOfExternalDescendants( true );
261             }
262         }
263         try {
264             final PhylogenyWriter writer = new PhylogenyWriter();
265             if ( no_indendation ) {
266                 writer.setIndentPhyloxml( false );
267             }
268             writer.toPhyloXML( phys, 0, outfile, ForesterUtil.LINE_SEPARATOR );
269         }
270         catch ( final IOException e ) {
271             ForesterUtil.fatalError( PRG_NAME, "failed to write to [" + outfile + "]: " + e.getMessage() );
272         }
273         System.out.println( "[" + PRG_NAME + "] wrote: [" + outfile + "]" );
274         System.out.println( "[" + PRG_NAME + "] OK" );
275         System.out.println();
276     }
277
278     private static void performSpecialProcessing( final Phylogeny phy ) {
279         // Can place some kind of custom processing here.
280         //        final List<PhylogenyNode> remove_us = new ArrayList<PhylogenyNode>();
281         //        int counter = 0;
282         //        for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
283         //            final PhylogenyNode node = it.next();
284         //            final String name = node.getNodeName().toLowerCase();
285         //            if ( name.startsWith( "environmental_samples" ) || name.startsWith( "unclassified" )
286         //                    || name.startsWith( "bacteria" ) || name.startsWith( "other" )
287         //                    || name.startsWith( "viroids" ) || name.startsWith( "viruses" ) ) {
288         //                remove_us.add( node );
289         //                System.out.println( counter++ );
290         //            }
291         //        }
292         //        phy.hashIDs();
293         //        for( final PhylogenyNode node : remove_us ) {
294         //            if ( phy.getNode( node.getNodeId() ) != null ) {
295         //                phy.deleteSubtree( node );
296         //                System.out.println( "deleted: " + node );
297         //            }
298         //        }
299         //        phy.hashIDs();
300         //
301         //        for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
302         //            final PhylogenyNode node = it.next();
303         //            node.getNodeData().setTaxonomy( null );
304         //        }
305         //        phy.reRoot( phy.getFirstExternalNode() );
306         //        PhylogenyMethods.midpointRoot( phy );
307         //        phy.orderAppearance( true );
308         for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
309             final PhylogenyNode node = it.next();
310             final String name = node.getName();
311             if ( !ForesterUtil.isEmpty( name ) ) {
312                 //                final Taxonomy taxo = new Taxonomy();
313                 //                if ( node.isExternal() ) {
314                 //                    taxo.setTaxonomyCode( name );
315                 //                    node.getNodeData().setTaxonomy( taxo );
316                 //                }
317                 //                else if ( name.indexOf( '_' ) == -1 || name.length() > 6 ) {
318                 //                    taxo.setScientificName( name );
319                 //                    node.getNodeData().setTaxonomy( taxo );
320                 //                }
321                 //                node.setName( "" );
322                 //                if ( name.indexOf( "BF" ) >= 0 ) {
323                 //                    taxo.setTaxonomyCode( "BACFR" );
324                 //                }
325                 //                else if ( name.indexOf( "BT" ) >= 0 ) {
326                 //                    taxo.setTaxonomyCode( "BACTN" );
327                 //                }
328                 //                else if ( name.indexOf( "MXAN" ) >= 0 ) {
329                 //                    taxo.setTaxonomyCode( "MYXXD" );
330                 //                }
331                 //                else if ( name.indexOf( "STIAU" ) >= 0 ) {
332                 //                    taxo.setTaxonomyCode( "STIAU" );
333                 //                }
334                 //                else if ( name.indexOf( "BOVA" ) >= 0 ) {
335                 //                    taxo.setTaxonomyCode( "BACOV" );
336                 //                }
337                 //                else if ( name.indexOf( "BUNI" ) >= 0 ) {
338                 //                    taxo.setTaxonomyCode( "BACUN" );
339                 //                }
340                 //                else if ( name.indexOf( "Pgin" ) >= 0 ) {
341                 //                    taxo.setTaxonomyCode( "PORGI" );
342                 //                }
343                 //                else if ( name.equals( "3CGH" ) || name.equals( "3CK7" ) ) {
344                 //                    taxo.setTaxonomyCode( "BACTN" );
345                 //                }
346                 // node.getNodeData().setTaxonomy( taxo );
347             }
348         }
349     }
350
351     private static void printHelp() {
352         System.out.println( "Usage:" );
353         System.out.println();
354         System.out
355                 .println( PRG_NAME
356                         + " -"
357                         + FIELD_OPTION
358                         + "=<field option> [options] <infile in New Hamphshire, NHX, Nexus, ToL XML, or phyloXML format> <outfile>" );
359         System.out.println();
360         System.out.println( " field options: " );
361         System.out.println();
362         System.out.println( "   " + FIELD_CLADE_NAME + ": transfer name to node/clade name" );
363         System.out.println( "   " + FIELD_TAXONOMY_CODE + ": transfer name to taxonomy code" );
364         System.out.println( "   " + FIELD_TAXONOMY_SCI_NAME + ": transfer name to taxonomy scientific name" );
365         System.out.println( "   " + FIELD_TAXONOMY_COMM_NAME + ": transfer name to taxonomy common name" );
366         System.out.println( "   " + FIELD_SEQUENCE_GENE_NAME + ": transfer name to sequence name" );
367         System.out.println( "   " + FIELD_SEQUENCE_SYMBOL + ": transfer name to sequence symbol" );
368         System.out
369                 .println( "   "
370                         + FIELD_UNIPROT_TAXONOMY_ID_SPLIT_1
371                         + ": transfer/split name to taxonomy uniprot identifier\n       (split at underscore if \"id_name\" pattern, e.g. \"817_SusD\")" );
372         System.out
373                 .println( "   "
374                         + FIELD_UNIPROT_TAXONOMY_ID_SPLIT_2
375                         + ": transfer/split name to taxonomy uniprot identifier\n       (split at underscore if \"name_id\" pattern, e.g. \"SusD_817\")" );
376         System.out.println();
377         System.out.println( " options: " );
378         System.out.println( " -" + INTERNAL_NAMES_ARE_BOOT_SUPPPORT
379                 + " : internal names in NH or NHX tree are bootstrap support values" );
380         System.out.println( " -" + REPLACE_UNDER_SCORES + ": replace all underscores with spaces" );
381         System.out.println( " -" + MIDPOINT_REROOT + " : midpoint reroot" );
382         System.out.println( " -" + ORDER_SUBTREES + " : order subtrees" );
383         System.out
384                 .println( " -"
385                         + EXTRACT_TAXONOMY
386                         + ": extract taxonomy to taxonomy code from \"seqname_TAXON\"-style names (cannot be used with the following field options: "
387                         + FIELD_TAXONOMY_CODE + ", " + FIELD_TAXONOMY_COMM_NAME + ", " + FIELD_TAXONOMY_SCI_NAME + ")" );
388         System.out
389                 .println( " -"
390                         + EXTRACT_TAXONOMY_PF
391                         + ": extract taxonomy to taxonomy code from Pfam (\"seqname_TAXON/x-y\") style names only (cannot be used with the following field options: "
392                         + FIELD_TAXONOMY_CODE + ", " + FIELD_TAXONOMY_COMM_NAME + ", " + FIELD_TAXONOMY_SCI_NAME + ")" );
393         System.out.println( " -" + NO_TREE_LEVEL_INDENDATION + ": no tree level indendation in phyloXML output" );
394         System.out.println();
395     }
396 }