clean up
[jalview.git] / forester / java / src / org / forester / io / parsers / nexus / NexusPhylogeniesParser.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.io.parsers.nexus;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36
37 import org.forester.archaeopteryx.Constants;
38 import org.forester.io.parsers.PhylogenyParser;
39 import org.forester.io.parsers.nhx.NHXFormatException;
40 import org.forester.io.parsers.nhx.NHXParser;
41 import org.forester.io.parsers.util.ParserUtils;
42 import org.forester.io.parsers.util.PhylogenyParserException;
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.ForesterUtil;
49
50 public class NexusPhylogeniesParser implements PhylogenyParser {
51
52     final private static String  begin_trees               = NexusConstants.BEGIN_TREES.toLowerCase();
53     final private static String  taxlabels                 = NexusConstants.TAXLABELS.toLowerCase();
54     final private static String  translate                 = NexusConstants.TRANSLATE.toLowerCase();
55     final private static String  tree                      = NexusConstants.TREE.toLowerCase();
56     final private static String  utree                     = NexusConstants.UTREE.toLowerCase();
57     final private static String  end                       = NexusConstants.END.toLowerCase();
58     final private static String  endblock                  = "endblock";
59     final private static Pattern TREE_NAME_PATTERN         = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
60                                                                               Pattern.CASE_INSENSITIVE );
61     final private static Pattern ROOTEDNESS_PATTERN        = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
62     private Object               _nexus_source;
63     private List<Phylogeny>      _phylogenies;
64     private List<String>         _taxlabels;
65     private Map<String, String>  _translate_map;
66     private boolean              _replace_underscores      = NHXParser.REPLACE_UNDERSCORES_DEFAULT;
67     private boolean              _ignore_quotes_in_nh_data = Constants.NH_PARSING_IGNORE_QUOTES_DEFAULT;
68
69     private void createPhylogeny( final String name,
70                                   final StringBuffer nhx,
71                                   final boolean rooted_info_present,
72                                   final boolean is_rooted ) throws IOException {
73         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
74         final NHXParser pars = new NHXParser();
75         pars.setTaxonomyExtraction( ForesterUtil.TAXONOMY_EXTRACTION.NO );
76         pars.setReplaceUnderscores( isReplaceUnderscores() );
77         pars.setIgnoreQuotes( isIgnoreQuotes() );
78         if ( rooted_info_present ) {
79             pars.setGuessRootedness( false );
80         }
81         final Phylogeny p = factory.create( nhx, pars )[ 0 ];
82         p.setName( name );
83         if ( rooted_info_present ) {
84             p.setRooted( is_rooted );
85         }
86         if ( ( getTaxlabels().size() > 0 ) || ( getTranslateMap().size() > 0 ) ) {
87             final PhylogenyNodeIterator it = p.iteratorExternalForward();
88             while ( it.hasNext() ) {
89                 final PhylogenyNode node = it.next();
90                 if ( ( getTranslateMap().size() > 0 ) && getTranslateMap().containsKey( node.getName() ) ) {
91                     node.setName( getTranslateMap().get( node.getName() ).replaceAll( "['\"]+", "" ) );
92                 }
93                 else if ( getTaxlabels().size() > 0 ) {
94                     int i = -1;
95                     try {
96                         i = Integer.parseInt( node.getName() );
97                     }
98                     catch ( final NumberFormatException e ) {
99                         // Ignore.
100                     }
101                     if ( i > 0 ) {
102                         node.setName( getTaxlabels().get( i - 1 ).replaceAll( "['\"]+", "" ) );
103                     }
104                 }
105             }
106         }
107         getPhylogenies().add( p );
108     }
109
110     private Object getNexusSource() {
111         return _nexus_source;
112     }
113
114     private List<Phylogeny> getPhylogenies() {
115         return _phylogenies;
116     }
117
118     private Phylogeny[] getPhylogeniesAsArray() {
119         final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
120         for( int i = 0; i < getPhylogenies().size(); ++i ) {
121             p[ i ] = getPhylogenies().get( i );
122         }
123         return p;
124     }
125
126     private List<String> getTaxlabels() {
127         return _taxlabels;
128     }
129
130     private Map<String, String> getTranslateMap() {
131         return _translate_map;
132     }
133
134     private boolean isIgnoreQuotes() {
135         return _ignore_quotes_in_nh_data;
136     }
137
138     private boolean isReplaceUnderscores() {
139         return _replace_underscores;
140     }
141
142     @Override
143     public Phylogeny[] parse() throws IOException, NHXFormatException {
144         reset();
145         final BufferedReader reader = ParserUtils.createReader( getNexusSource() );
146         String line;
147         String name = "";
148         StringBuffer nhx = new StringBuffer();
149         final StringBuffer translate_sb = new StringBuffer();
150         boolean in_trees_block = false;
151         boolean in_taxalabels = false;
152         boolean in_translate = false;
153         final boolean in_comment = false;
154         boolean in_tree = false;
155         boolean rooted_info_present = false;
156         boolean is_rooted = false;
157         while ( ( line = reader.readLine() ) != null ) {
158             line = line.trim();
159             if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
160                 line = ForesterUtil.collapseWhiteSpace( line );
161                 line = removeWhiteSpaceBeforeSemicolon( line );
162                 final String line_lc = line.toLowerCase();
163                 if ( line_lc.startsWith( begin_trees ) ) {
164                     in_trees_block = true;
165                     in_taxalabels = false;
166                     in_translate = false;
167                 }
168                 else if ( line_lc.startsWith( taxlabels ) ) {
169                     in_trees_block = false;
170                     in_taxalabels = true;
171                     in_translate = false;
172                 }
173                 else if ( line_lc.startsWith( translate ) ) {
174                     in_taxalabels = false;
175                     in_translate = true;
176                 }
177                 else if ( in_trees_block ) {
178                     //FIXME TODO need to work on this "title" and "link"
179                     if ( line_lc.startsWith( "title" ) || line_lc.startsWith( "link" ) ) {
180                         // Do nothing.
181                     }
182                     else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
183                         in_trees_block = false;
184                         in_tree = false;
185                         in_translate = false;
186                         if ( nhx.length() > 0 ) {
187                             createPhylogeny( name, nhx, rooted_info_present, is_rooted );
188                             nhx = new StringBuffer();
189                             name = "";
190                             rooted_info_present = false;
191                             is_rooted = false;
192                         }
193                     }
194                     else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
195                         if ( nhx.length() > 0 ) {
196                             createPhylogeny( name, nhx, rooted_info_present, is_rooted );
197                             nhx = new StringBuffer();
198                             name = "";
199                             rooted_info_present = false;
200                             is_rooted = false;
201                         }
202                         in_tree = true;
203                         nhx.append( line.substring( line.indexOf( '=' ) ) );
204                         final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
205                         if ( name_matcher.matches() ) {
206                             name = name_matcher.group( 1 );
207                             name = name.replaceAll( "['\"]+", "" );
208                         }
209                         final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
210                         if ( rootedness_matcher.matches() ) {
211                             final String s = rootedness_matcher.group( 1 );
212                             line = line.replaceAll( "\\[\\&.\\]", "" );
213                             rooted_info_present = true;
214                             if ( s.toUpperCase().equals( "R" ) ) {
215                                 is_rooted = true;
216                             }
217                         }
218                     }
219                     else if ( in_tree && !in_translate ) {
220                         nhx.append( line );
221                     }
222                     if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !in_translate
223                             && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
224                         in_tree = false;
225                         in_translate = false;
226                         createPhylogeny( name, nhx, rooted_info_present, is_rooted );
227                         nhx = new StringBuffer();
228                         name = "";
229                         rooted_info_present = false;
230                         is_rooted = false;
231                     }
232                 }
233                 if ( in_taxalabels ) {
234                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
235                         in_taxalabels = false;
236                     }
237                     else {
238                         final String[] labels = line.split( "\\s+" );
239                         for( String label : labels ) {
240                             if ( !label.toLowerCase().equals( taxlabels ) ) {
241                                 if ( label.endsWith( ";" ) ) {
242                                     in_taxalabels = false;
243                                     label = label.substring( 0, label.length() - 1 );
244                                 }
245                                 if ( label.length() > 0 ) {
246                                     getTaxlabels().add( label );
247                                 }
248                             }
249                         }
250                     }
251                 }
252                 if ( in_translate ) {
253                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
254                         in_translate = false;
255                     }
256                     else {
257                         translate_sb.append( " " );
258                         translate_sb.append( line.trim() );
259                         if ( line.endsWith( ";" ) ) {
260                             in_translate = false;
261                             setTranslateKeyValuePairs( translate_sb );
262                         }
263                     }
264                 }
265             }
266         }
267         if ( nhx.length() > 0 ) {
268             createPhylogeny( name, nhx, rooted_info_present, is_rooted );
269         }
270         return getPhylogeniesAsArray();
271     }
272
273     private void reset() {
274         setPhylogenies( new ArrayList<Phylogeny>() );
275         setTaxlabels( new ArrayList<String>() );
276         setTranslateMap( new HashMap<String, String>() );
277     }
278
279     public void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
280         _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
281     }
282
283     private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
284         _phylogenies = phylogenies;
285     }
286
287     public void setReplaceUnderscores( final boolean replace_underscores ) {
288         _replace_underscores = replace_underscores;
289     }
290
291     @Override
292     public void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
293         if ( nexus_source == null ) {
294             throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
295         }
296         _nexus_source = nexus_source;
297     }
298
299     private void setTaxlabels( final List<String> taxlabels ) {
300         _taxlabels = taxlabels;
301     }
302
303     private void setTranslateKeyValuePairs( final StringBuffer translate_sb ) throws IOException {
304         String s = translate_sb.toString().trim();
305         if ( s.endsWith( ";" ) ) {
306             s = s.substring( 0, s.length() - 1 ).trim();
307         }
308         for( final String pair : s.split( "," ) ) {
309             final String[] kv = pair.trim().split( "\\s+" );
310             if ( ( kv.length < 2 ) || ( kv.length > 3 ) ) {
311                 throw new IOException( "ill formatted translate values: " + translate_sb );
312             }
313             if ( ( kv.length == 3 ) && !kv[ 0 ].toLowerCase().trim().equals( translate ) ) {
314                 throw new IOException( "ill formatted translate values: " + translate_sb );
315             }
316             String key = "";
317             String value = "";
318             if ( kv.length == 3 ) {
319                 key = kv[ 1 ];
320                 value = kv[ 2 ];
321             }
322             else {
323                 key = kv[ 0 ];
324                 value = kv[ 1 ];
325             }
326             if ( value.endsWith( ";" ) ) {
327                 value = value.substring( 0, value.length() - 1 );
328             }
329             getTranslateMap().put( key, value );
330         }
331     }
332
333     private void setTranslateMap( final Map<String, String> translate_map ) {
334         _translate_map = translate_map;
335     }
336
337     private static String removeWhiteSpaceBeforeSemicolon( final String s ) {
338         return s.replaceAll( "\\s+;", ";" );
339     }
340 }