in progress
[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             }
259         }
260         try {
261             final PhylogenyWriter writer = new PhylogenyWriter();
262             if ( no_indendation ) {
263                 writer.setIndentPhyloxml( false );
264             }
265             writer.toPhyloXML( phys, 0, outfile, ForesterUtil.LINE_SEPARATOR );
266         }
267         catch ( final IOException e ) {
268             ForesterUtil.fatalError( PRG_NAME, "failed to write to [" + outfile + "]: " + e.getMessage() );
269         }
270         System.out.println( "[" + PRG_NAME + "] wrote: [" + outfile + "]" );
271         System.out.println( "[" + PRG_NAME + "] OK" );
272         System.out.println();
273     }
274
275     private static void performSpecialProcessing( final Phylogeny phy ) {
276         // Can place some kind of custom processing here.
277         //        final List<PhylogenyNode> remove_us = new ArrayList<PhylogenyNode>();
278         //        int counter = 0;
279         //        for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
280         //            final PhylogenyNode node = it.next();
281         //            final String name = node.getNodeName().toLowerCase();
282         //            if ( name.startsWith( "environmental_samples" ) || name.startsWith( "unclassified" )
283         //                    || name.startsWith( "bacteria" ) || name.startsWith( "other" )
284         //                    || name.startsWith( "viroids" ) || name.startsWith( "viruses" ) ) {
285         //                remove_us.add( node );
286         //                System.out.println( counter++ );
287         //            }
288         //        }
289         //        phy.hashIDs();
290         //        for( final PhylogenyNode node : remove_us ) {
291         //            if ( phy.getNode( node.getNodeId() ) != null ) {
292         //                phy.deleteSubtree( node );
293         //                System.out.println( "deleted: " + node );
294         //            }
295         //        }
296         //        phy.hashIDs();
297         //
298         //        for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
299         //            final PhylogenyNode node = it.next();
300         //            node.getNodeData().setTaxonomy( null );
301         //        }
302         //        phy.reRoot( phy.getFirstExternalNode() );
303         //        PhylogenyMethods.midpointRoot( phy );
304         //        phy.orderAppearance( true );
305         for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
306             final PhylogenyNode node = it.next();
307             final String name = node.getName();
308             if ( !ForesterUtil.isEmpty( name ) ) {
309                 //                final Taxonomy taxo = new Taxonomy();
310                 //                if ( node.isExternal() ) {
311                 //                    taxo.setTaxonomyCode( name );
312                 //                    node.getNodeData().setTaxonomy( taxo );
313                 //                }
314                 //                else if ( name.indexOf( '_' ) == -1 || name.length() > 6 ) {
315                 //                    taxo.setScientificName( name );
316                 //                    node.getNodeData().setTaxonomy( taxo );
317                 //                }
318                 //                node.setName( "" );
319                 //                if ( name.indexOf( "BF" ) >= 0 ) {
320                 //                    taxo.setTaxonomyCode( "BACFR" );
321                 //                }
322                 //                else if ( name.indexOf( "BT" ) >= 0 ) {
323                 //                    taxo.setTaxonomyCode( "BACTN" );
324                 //                }
325                 //                else if ( name.indexOf( "MXAN" ) >= 0 ) {
326                 //                    taxo.setTaxonomyCode( "MYXXD" );
327                 //                }
328                 //                else if ( name.indexOf( "STIAU" ) >= 0 ) {
329                 //                    taxo.setTaxonomyCode( "STIAU" );
330                 //                }
331                 //                else if ( name.indexOf( "BOVA" ) >= 0 ) {
332                 //                    taxo.setTaxonomyCode( "BACOV" );
333                 //                }
334                 //                else if ( name.indexOf( "BUNI" ) >= 0 ) {
335                 //                    taxo.setTaxonomyCode( "BACUN" );
336                 //                }
337                 //                else if ( name.indexOf( "Pgin" ) >= 0 ) {
338                 //                    taxo.setTaxonomyCode( "PORGI" );
339                 //                }
340                 //                else if ( name.equals( "3CGH" ) || name.equals( "3CK7" ) ) {
341                 //                    taxo.setTaxonomyCode( "BACTN" );
342                 //                }
343                 // node.getNodeData().setTaxonomy( taxo );
344             }
345         }
346     }
347
348     private static void printHelp() {
349         System.out.println( "Usage:" );
350         System.out.println();
351         System.out
352                 .println( PRG_NAME
353                         + " -"
354                         + FIELD_OPTION
355                         + "=<field option> [options] <infile in New Hamphshire, NHX, Nexus, ToL XML, or phyloXML format> <outfile>" );
356         System.out.println();
357         System.out.println( " field options: " );
358         System.out.println();
359         System.out.println( "   " + FIELD_CLADE_NAME + ": transfer name to node/clade name" );
360         System.out.println( "   " + FIELD_TAXONOMY_CODE + ": transfer name to taxonomy code" );
361         System.out.println( "   " + FIELD_TAXONOMY_SCI_NAME + ": transfer name to taxonomy scientific name" );
362         System.out.println( "   " + FIELD_TAXONOMY_COMM_NAME + ": transfer name to taxonomy common name" );
363         System.out.println( "   " + FIELD_SEQUENCE_GENE_NAME + ": transfer name to sequence name" );
364         System.out.println( "   " + FIELD_SEQUENCE_SYMBOL + ": transfer name to sequence symbol" );
365         System.out
366                 .println( "   "
367                         + FIELD_UNIPROT_TAXONOMY_ID_SPLIT_1
368                         + ": transfer/split name to taxonomy uniprot identifier\n       (split at underscore if \"id_name\" pattern, e.g. \"817_SusD\")" );
369         System.out
370                 .println( "   "
371                         + FIELD_UNIPROT_TAXONOMY_ID_SPLIT_2
372                         + ": transfer/split name to taxonomy uniprot identifier\n       (split at underscore if \"name_id\" pattern, e.g. \"SusD_817\")" );
373         System.out.println();
374         System.out.println( " options: " );
375         System.out.println( " -" + INTERNAL_NAMES_ARE_BOOT_SUPPPORT
376                 + " : internal names in NH or NHX tree are bootstrap support values" );
377         System.out.println( " -" + REPLACE_UNDER_SCORES + ": replace all underscores with spaces" );
378         System.out.println( " -" + MIDPOINT_REROOT + " : midpoint reroot" );
379         System.out.println( " -" + ORDER_SUBTREES + " : order subtrees" );
380         System.out
381                 .println( " -"
382                         + EXTRACT_TAXONOMY
383                         + ": extract taxonomy to taxonomy code from \"seqname_TAXON\"-style names (cannot be used with the following field options: "
384                         + FIELD_TAXONOMY_CODE + ", " + FIELD_TAXONOMY_COMM_NAME + ", " + FIELD_TAXONOMY_SCI_NAME + ")" );
385         System.out
386                 .println( " -"
387                         + EXTRACT_TAXONOMY_PF
388                         + ": extract taxonomy to taxonomy code from Pfam (\"seqname_TAXON/x-y\") style names only (cannot be used with the following field options: "
389                         + FIELD_TAXONOMY_CODE + ", " + FIELD_TAXONOMY_COMM_NAME + ", " + FIELD_TAXONOMY_SCI_NAME + ")" );
390         System.out.println( " -" + NO_TREE_LEVEL_INDENDATION + ": no tree level indendation in phyloXML output" );
391         System.out.println();
392     }
393 }