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