added mapping
[jalview.git] / forester / java / src / org / forester / application / cladinator.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2017 Christian M. Zmasek
6 // Copyright (C) 2017 J. Craig Venter Institute
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phyloxml @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.application;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.text.DecimalFormat;
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.SortedMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import java.util.regex.PatternSyntaxException;
37
38 import org.forester.clade_analysis.AnalysisMulti;
39 import org.forester.clade_analysis.Prefix;
40 import org.forester.clade_analysis.ResultMulti;
41 import org.forester.io.parsers.PhylogenyParser;
42 import org.forester.io.parsers.util.ParserUtils;
43 import org.forester.phylogeny.Phylogeny;
44 import org.forester.phylogeny.PhylogenyNode;
45 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
46 import org.forester.phylogeny.factories.PhylogenyFactory;
47 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
48 import org.forester.util.BasicTable;
49 import org.forester.util.BasicTableParser;
50 import org.forester.util.CommandLineArguments;
51 import org.forester.util.EasyWriter;
52 import org.forester.util.ForesterUtil;
53
54 public final class cladinator {
55
56     final static private String        PRG_NAME                 = "cladinator";
57     final static private String        PRG_VERSION              = "1.01";
58     final static private String        PRG_DATE                 = "170906";
59     final static private String        PRG_DESC                 = "clades within clades of annotated labels -- analysis of pplacer-type outputs";
60     final static private String        E_MAIL                   = "phyloxml@gmail.com";
61     final static private String        WWW                      = "https://sites.google.com/site/cmzmasek/home/software/forester";
62     final static private String        HELP_OPTION_1            = "help";
63     final static private String        HELP_OPTION_2            = "h";
64     final static private String        SEP_OPTION               = "s";
65     final static private String        QUERY_PATTERN_OPTION     = "q";
66     final static private String        SPECIFICS_CUTOFF_OPTION  = "c";
67     final static private String        MAPPING_FILE_OPTION      = "m";
68     final static private double        SPECIFICS_CUTOFF_DEFAULT = 0.8;
69     final static private String        SEP_DEFAULT              = ".";
70     final static private Pattern       QUERY_PATTERN_DEFAULT    = AnalysisMulti.DEFAULT_QUERY_PATTERN_FOR_PPLACER_TYPE;
71     private final static DecimalFormat df                       = new DecimalFormat( "0.0#######" );
72
73     public static void main( final String args[] ) {
74         try {
75             ForesterUtil.printProgramInformation( PRG_NAME,
76                                                   PRG_DESC,
77                                                   PRG_VERSION,
78                                                   PRG_DATE,
79                                                   E_MAIL,
80                                                   WWW,
81                                                   ForesterUtil.getForesterLibraryInformation() );
82             CommandLineArguments cla = null;
83             try {
84                 cla = new CommandLineArguments( args );
85             }
86             catch ( final Exception e ) {
87                 ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
88             }
89             if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 ) ) {
90                 System.out.println();
91                 print_help();
92                 System.exit( 0 );
93             }
94             if ( ( cla.getNumberOfNames() != 1 ) && ( cla.getNumberOfNames() != 2 ) ) {
95                 print_help();
96                 System.exit( -1 );
97             }
98             final List<String> allowed_options = new ArrayList<>();
99             allowed_options.add( SEP_OPTION );
100             allowed_options.add( QUERY_PATTERN_OPTION );
101             allowed_options.add( SPECIFICS_CUTOFF_OPTION );
102             allowed_options.add( MAPPING_FILE_OPTION );
103             final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
104             if ( dissallowed_options.length() > 0 ) {
105                 ForesterUtil.fatalError( PRG_NAME, "unknown option(s): " + dissallowed_options );
106             }
107             double cutoff_specifics = SPECIFICS_CUTOFF_DEFAULT;
108             if ( cla.isOptionSet( SPECIFICS_CUTOFF_OPTION ) ) {
109                 if ( cla.isOptionValueSet( SPECIFICS_CUTOFF_OPTION ) ) {
110                     cutoff_specifics = cla.getOptionValueAsDouble( SPECIFICS_CUTOFF_OPTION );
111                     if ( cutoff_specifics < 0 ) {
112                         ForesterUtil.fatalError( PRG_NAME, "cutoff cannot be negative" );
113                     }
114                 }
115                 else {
116                     ForesterUtil.fatalError( PRG_NAME, "no value for cutoff for specifics" );
117                 }
118             }
119             String separator = SEP_DEFAULT;
120             if ( cla.isOptionSet( SEP_OPTION ) ) {
121                 if ( cla.isOptionValueSet( SEP_OPTION ) ) {
122                     separator = cla.getOptionValue( SEP_OPTION );
123                 }
124                 else {
125                     ForesterUtil.fatalError( PRG_NAME, "no value for separator option" );
126                 }
127             }
128             Pattern compiled_query_str = null;
129             if ( cla.isOptionSet( QUERY_PATTERN_OPTION ) ) {
130                 if ( cla.isOptionValueSet( QUERY_PATTERN_OPTION ) ) {
131                     final String query_str = cla.getOptionValue( QUERY_PATTERN_OPTION );
132                     try {
133                         compiled_query_str = Pattern.compile( query_str );
134                     }
135                     catch ( final PatternSyntaxException e ) {
136                         ForesterUtil.fatalError( PRG_NAME, "error in regular expression: " + e.getMessage() );
137                     }
138                 }
139                 else {
140                     ForesterUtil.fatalError( PRG_NAME, "no value for query pattern option" );
141                 }
142             }
143             File mapping_file = null;
144             if ( cla.isOptionSet( MAPPING_FILE_OPTION ) ) {
145                 if ( cla.isOptionValueSet( MAPPING_FILE_OPTION ) ) {
146                     final String mapping_file_str = cla.getOptionValue( MAPPING_FILE_OPTION );
147                     final String error = ForesterUtil.isReadableFile( mapping_file_str );
148                     if ( !ForesterUtil.isEmpty( error ) ) {
149                         ForesterUtil.fatalError( PRG_NAME, error );
150                     }
151                     mapping_file = new File( mapping_file_str );
152                 }
153                 else {
154                     ForesterUtil.fatalError( PRG_NAME, "no value for mapping file" );
155                 }
156             }
157             final Pattern pattern = ( compiled_query_str != null ) ? compiled_query_str : QUERY_PATTERN_DEFAULT;
158             final File intreefile = cla.getFile( 0 );
159             final String error_intreefile = ForesterUtil.isReadableFile( intreefile );
160             if ( !ForesterUtil.isEmpty( error_intreefile ) ) {
161                 ForesterUtil.fatalError( PRG_NAME, error_intreefile );
162             }
163             final File outtablefile;
164             if ( cla.getNumberOfNames() > 1 ) {
165                 outtablefile = cla.getFile( 1 );
166                 final String error_outtablefile = ForesterUtil.isWritableFile( outtablefile );
167                 if ( !ForesterUtil.isEmpty( error_outtablefile ) ) {
168                     ForesterUtil.fatalError( PRG_NAME, error_outtablefile );
169                 }
170             }
171             else {
172                 outtablefile = null;
173             }
174             final BasicTable<String> t;
175             final SortedMap<String, String> map;
176             if ( mapping_file != null ) {
177                 t = BasicTableParser.parse( mapping_file, '\t' );
178                 if ( t.getNumberOfColumns() != 2 ) {
179                     ForesterUtil.fatalError( PRG_NAME,
180                                              "mapping file needs to have 2 tab-separated columns, not "
181                                                      + t.getNumberOfColumns() );
182                 }
183                 map = t.getColumnsAsMap( 0, 1 );
184             }
185             else {
186                 t = null;
187                 map = null;
188             }
189             System.out.println( "Input tree                 : " + intreefile );
190             System.out.println( "Specific-hit support cutoff: " + cutoff_specifics );
191             if ( mapping_file != null ) {
192                 System.out.println( "Mapping file               : " + mapping_file + " (" + t.getNumberOfRows()
193                         + " rows)" );
194             }
195             System.out.println( "Annotation-separator       : " + separator );
196             System.out.println( "Query pattern              : " + pattern );
197             if ( outtablefile != null ) {
198                 System.out.println( "Output table               : " + outtablefile );
199             }
200             Phylogeny p = null;
201             try {
202                 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
203                 final PhylogenyParser pp = ParserUtils.createParserDependingOnFileType( intreefile, true );
204                 p = factory.create( intreefile, pp )[ 0 ];
205             }
206             catch ( final IOException e ) {
207                 ForesterUtil.fatalError( PRG_NAME, "Could not read \"" + intreefile + "\" [" + e.getMessage() + "]" );
208                 System.exit( -1 );
209             }
210             System.out.println( "Ext. nodes in input tree   : " + p.getNumberOfExternalNodes() );
211             if ( map != null ) {
212                 performMapping( pattern, map, p );
213             }
214             final ResultMulti res = AnalysisMulti.execute( p, pattern, separator, cutoff_specifics );
215             printResult( res );
216             if ( outtablefile != null ) {
217                 writeResultToTable( res, outtablefile );
218             }
219         }
220         catch ( final IllegalArgumentException e ) {
221             ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
222         }
223         catch ( final IOException e ) {
224             ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
225         }
226         catch ( final Exception e ) {
227             e.printStackTrace();
228             ForesterUtil.fatalError( PRG_NAME, "Unexpected errror!" );
229         }
230     }
231
232     private final static void performMapping( final Pattern pattern,
233                                               final SortedMap<String, String> map,
234                                               Phylogeny p ) {
235         final PhylogenyNodeIterator it = p.iteratorExternalForward();
236         while ( it.hasNext() ) {
237             final PhylogenyNode node = it.next();
238             final String name = node.getName();
239             if ( ForesterUtil.isEmpty( name ) ) {
240                 ForesterUtil.fatalError( PRG_NAME, "external node with empty name found" );
241             }
242             final Matcher m = pattern.matcher( name );
243             if ( !m.find() ) {
244                 if ( !map.containsKey( name ) ) {
245                     ForesterUtil.fatalError( PRG_NAME, "no mapping for \"" + name + "\" found" );
246                 }
247                 node.setName( map.get( name ) );
248             }
249         }
250     }
251
252     private final static void printResult( final ResultMulti res ) {
253         System.out.println();
254         System.out.println( "Result:" );
255         System.out.println();
256         if ( ( res.getAllMultiHitPrefixes() == null ) | ( res.getAllMultiHitPrefixes().size() < 1 ) ) {
257             System.out.println( "No match to query pattern!" );
258         }
259         else {
260             System.out.println( "Matching Clade(s):" );
261             for( final Prefix prefix : res.getCollapsedMultiHitPrefixes() ) {
262                 System.out.println( prefix );
263             }
264             if ( res.isHasSpecificMultiHitsPrefixes() ) {
265                 System.out.println();
266                 System.out.println( "Specific-hit(s):" );
267                 for( final Prefix prefix : res.getSpecificMultiHitPrefixes() ) {
268                     System.out.println( prefix );
269                 }
270                 System.out.println();
271                 System.out.println( "Matching Clade(s) with Specific-hit(s):" );
272                 for( final Prefix prefix : res.getCollapsedMultiHitPrefixes() ) {
273                     System.out.println( prefix );
274                     for( final Prefix spec : res.getSpecificMultiHitPrefixes() ) {
275                         if ( spec.getPrefix().startsWith( prefix.getPrefix() ) ) {
276                             System.out.println( "    " + spec );
277                         }
278                     }
279                 }
280             }
281             if ( !ForesterUtil.isEmpty( res.getAllMultiHitPrefixesDown() ) ) {
282                 System.out.println();
283                 System.out.println( "Matching Down-tree Bracketing Clade(s):" );
284                 for( final Prefix prefix : res.getCollapsedMultiHitPrefixesDown() ) {
285                     System.out.println( prefix );
286                 }
287             }
288             if ( !ForesterUtil.isEmpty( res.getAllMultiHitPrefixesUp() ) ) {
289                 System.out.println();
290                 System.out.println( "Matching Up-tree Bracketing Clade(s):" );
291                 for( final Prefix prefix : res.getCollapsedMultiHitPrefixesUp() ) {
292                     System.out.println( prefix );
293                 }
294             }
295         }
296         System.out.println();
297     }
298
299     private final static void writeResultToTable( final ResultMulti res, final File outtablefile ) throws IOException {
300         final EasyWriter w = ForesterUtil.createEasyWriter( outtablefile );
301         if ( ( res.getAllMultiHitPrefixes() == null ) | ( res.getAllMultiHitPrefixes().size() < 1 ) ) {
302             w.println( "No match to query pattern!" );
303         }
304         else {
305             for( final Prefix prefix : res.getCollapsedMultiHitPrefixes() ) {
306                 w.print( "Matching Clades" );
307                 w.print( "\t" );
308                 w.print( prefix.getPrefix() );
309                 w.print( "\t" );
310                 w.print( df.format( prefix.getConfidence() ) );
311                 w.println();
312             }
313             if ( res.isHasSpecificMultiHitsPrefixes() ) {
314                 for( final Prefix prefix : res.getSpecificMultiHitPrefixes() ) {
315                     w.print( "Specific-hits" );
316                     w.print( "\t" );
317                     w.print( prefix.getPrefix() );
318                     w.print( "\t" );
319                     w.print( df.format( prefix.getConfidence() ) );
320                     w.println();
321                 }
322             }
323             if ( !ForesterUtil.isEmpty( res.getAllMultiHitPrefixesDown() ) ) {
324                 for( final Prefix prefix : res.getCollapsedMultiHitPrefixesDown() ) {
325                     w.print( "Matching Down-tree Bracketing Clades" );
326                     w.print( "\t" );
327                     w.print( prefix.getPrefix() );
328                     w.print( "\t" );
329                     w.print( df.format( prefix.getConfidence() ) );
330                     w.println();
331                 }
332             }
333             if ( !ForesterUtil.isEmpty( res.getAllMultiHitPrefixesUp() ) ) {
334                 for( final Prefix prefix : res.getCollapsedMultiHitPrefixesUp() ) {
335                     w.print( "Matching Up-tree Bracketing Clades" );
336                     w.print( "\t" );
337                     w.print( prefix.getPrefix() );
338                     w.print( "\t" );
339                     w.print( df.format( prefix.getConfidence() ) );
340                     w.println();
341                 }
342             }
343         }
344         w.flush();
345         w.close();
346     }
347
348     private final static void print_help() {
349         System.out.println( "Usage:" );
350         System.out.println();
351         System.out.println( PRG_NAME + " [options] <input tree file> [output table file]" );
352         System.out.println();
353         System.out.println( " options:" );
354         System.out.println( "  -" + SPECIFICS_CUTOFF_OPTION
355                 + "=<double>: the cutoff for \"specific-hit\" support values (default: " + SPECIFICS_CUTOFF_DEFAULT
356                 + ")" );
357         System.out.println( "  -" + SEP_OPTION + "=<separator>: the annotation-separator to be used (default: "
358                 + SEP_DEFAULT + ")" );
359         System.out.println( "  -" + MAPPING_FILE_OPTION
360                 + "=<mapping table>: to map node names to appropriate annotations (tab-separated, two columns) (default: no mapping)" );
361         System.out.println( "  -" + QUERY_PATTERN_OPTION
362                 + "=<query pattern>: the regular expression for the query (default: \"" + QUERY_PATTERN_DEFAULT
363                 + "\" for pplacer output)" );
364         System.out.println();
365         System.out.println( "Examples:" );
366         System.out.println();
367         System.out.println( " " + PRG_NAME + " my_tree.nh result.tsv" );
368         System.out.println( " " + PRG_NAME + " -c=0.5 -s=. my_tree.nh result.tsv" );
369         System.out.println( " " + PRG_NAME + " -c=0.9 -s=_ -m=map.tsv my_tree.nh result.tsv" );
370         System.out.println();
371     }
372 }