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