46f6548afe566cdcb398313e021fd7852cd0a9f3
[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: https://sites.google.com/site/cmzmasek/home/software/forester
25
26 package org.forester.io.parsers.nexus;
27
28 import java.io.BufferedReader;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 import org.forester.archaeopteryx.Constants;
39 import org.forester.io.parsers.IteratingPhylogenyParser;
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.nhx.NHXFormatException;
42 import org.forester.io.parsers.nhx.NHXParser;
43 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
44 import org.forester.io.parsers.util.ParserUtils;
45 import org.forester.io.parsers.util.PhylogenyParserException;
46 import org.forester.phylogeny.Phylogeny;
47 import org.forester.phylogeny.PhylogenyNode;
48 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
49 import org.forester.util.ForesterUtil;
50
51 public final class NexusPhylogeniesParser implements IteratingPhylogenyParser, PhylogenyParser {
52
53     final private static String  begin_trees               = NexusConstants.BEGIN_TREES.toLowerCase();
54     final private static String  taxlabels                 = NexusConstants.TAXLABELS.toLowerCase();
55     final private static String  translate                 = NexusConstants.TRANSLATE.toLowerCase();
56     final private static String  tree                      = NexusConstants.TREE.toLowerCase();
57     final private static String  utree                     = NexusConstants.UTREE.toLowerCase();
58     final private static String  end                       = NexusConstants.END.toLowerCase();
59     final private static String  endblock                  = "endblock";
60     final private static Pattern TREE_NAME_PATTERN         = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
61                                                                               Pattern.CASE_INSENSITIVE );
62     final private static Pattern ROOTEDNESS_PATTERN        = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
63     private Object               _nexus_source;
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     private TAXONOMY_EXTRACTION  _taxonomy_extraction      = TAXONOMY_EXTRACTION.NO;
69     private Phylogeny            _next;
70     private BufferedReader       _br;
71     private boolean              _in_trees_block;
72     private StringBuilder        _nh;
73     private String               _name;
74     private StringBuilder        _translate_sb;
75     private boolean              _in_taxalabels;
76     private boolean              _in_translate;
77     private boolean              _is_rooted;
78     private boolean              _rooted_info_present;
79     private boolean              _in_tree;
80
81     @Override
82     public final boolean hasNext() {
83         return _next != null;
84     }
85
86     @Override
87     public final Phylogeny next() throws NHXFormatException, IOException {
88         final Phylogeny phy = _next;
89         getNext();
90         return phy;
91     }
92
93     @Override
94     public final Phylogeny[] parse() throws IOException {
95         final List<Phylogeny> l = new ArrayList<Phylogeny>();
96         while ( hasNext() ) {
97             l.add( next() );
98         }
99         final Phylogeny[] p = new Phylogeny[ l.size() ];
100         for( int i = 0; i < l.size(); ++i ) {
101             p[ i ] = l.get( i );
102         }
103         reset();
104         return p;
105     }
106
107     @Override
108     public final void reset() throws FileNotFoundException, IOException {
109         _taxlabels = new ArrayList<String>();
110         _translate_map = new HashMap<String, String>();
111         _nh = new StringBuilder();
112         _name = "";
113         _translate_sb = new StringBuilder();
114         _next = null;
115         _in_trees_block = false;
116         _in_taxalabels = false;
117         _in_translate = false;
118         _in_tree = false;
119         _rooted_info_present = false;
120         _is_rooted = false;
121         _br = ParserUtils.createReader( _nexus_source );
122         getNext();
123     }
124
125     public final void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
126         _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
127     }
128
129     public final void setReplaceUnderscores( final boolean replace_underscores ) {
130         _replace_underscores = replace_underscores;
131     }
132
133     @Override
134     public final void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
135         if ( nexus_source == null ) {
136             throw new PhylogenyParserException( "attempt to parse null object" );
137         }
138         _nexus_source = nexus_source;
139         reset();
140     }
141
142     public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
143         _taxonomy_extraction = taxonomy_extraction;
144     }
145
146     private final void createPhylogeny( final String name,
147                                         final StringBuilder nhx,
148                                         final boolean rooted_info_present,
149                                         final boolean is_rooted ) throws IOException {
150         _next = null;
151         final NHXParser pars = new NHXParser();
152         pars.setTaxonomyExtraction( _taxonomy_extraction );
153         pars.setReplaceUnderscores( _replace_underscores );
154         pars.setIgnoreQuotes( _ignore_quotes_in_nh_data );
155         if ( rooted_info_present ) {
156             pars.setGuessRootedness( false );
157         }
158         pars.setSource( nhx );
159         final Phylogeny p = pars.next();
160         if ( p == null ) {
161             throw new PhylogenyParserException( "failed to create phylogeny" );
162         }
163         p.setName( name );
164         if ( rooted_info_present ) {
165             p.setRooted( is_rooted );
166         }
167         if ( ( _taxlabels.size() > 0 ) || ( _translate_map.size() > 0 ) ) {
168             final PhylogenyNodeIterator it = p.iteratorExternalForward();
169             while ( it.hasNext() ) {
170                 final PhylogenyNode node = it.next();
171                 if ( ( _translate_map.size() > 0 ) && _translate_map.containsKey( node.getName() ) ) {
172                     node.setName( _translate_map.get( node.getName() ).replaceAll( "['\"]+", "" ) );
173                 }
174                 else if ( _taxlabels.size() > 0 ) {
175                     int i = -1;
176                     try {
177                         i = Integer.parseInt( node.getName() );
178                     }
179                     catch ( final NumberFormatException e ) {
180                         // Ignore.
181                     }
182                     if ( i > 0 ) {
183                         node.setName( _taxlabels.get( i - 1 ).replaceAll( "['\"]+", "" ) );
184                     }
185                 }
186                 if ( !_replace_underscores && ( ( _taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
187                     ParserUtils.extractTaxonomyDataFromNodeName( node, _taxonomy_extraction );
188                 }
189             }
190         }
191         _next = p;
192     }
193
194     private final void getNext() throws IOException, NHXFormatException {
195         _next = null;
196         String line;
197         while ( ( line = _br.readLine() ) != null ) {
198             line = line.trim();
199             if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
200                 line = ForesterUtil.collapseWhiteSpace( line );
201                 line = removeWhiteSpaceBeforeSemicolon( line );
202                 final String line_lc = line.toLowerCase();
203                 if ( line_lc.startsWith( begin_trees ) ) {
204                     _in_trees_block = true;
205                     _in_taxalabels = false;
206                     _in_translate = false;
207                 }
208                 else if ( line_lc.startsWith( taxlabels ) ) {
209                     _in_trees_block = false;
210                     _in_taxalabels = true;
211                     _in_translate = false;
212                 }
213                 else if ( line_lc.startsWith( translate ) ) {
214                     _in_taxalabels = false;
215                     _in_translate = true;
216                 }
217                 else if ( _in_trees_block ) {
218                     //FIXME TODO need to work on this "title" and "link"
219                     if ( line_lc.startsWith( "title" ) || line_lc.startsWith( "link" ) ) {
220                         // Do nothing.
221                     }
222                     else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
223                         _in_trees_block = false;
224                         _in_tree = false;
225                         _in_translate = false;
226                         if ( _nh.length() > 0 ) {
227                             createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
228                             _nh = new StringBuilder();
229                             _name = "";
230                             _rooted_info_present = false;
231                             _is_rooted = false;
232                             if ( _next != null ) {
233                                 return;
234                             }
235                         }
236                     }
237                     else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
238                         boolean might = false;
239                         if ( _nh.length() > 0 ) {
240                             might = true;
241                             createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
242                             _nh = new StringBuilder();
243                             _name = "";
244                             _rooted_info_present = false;
245                             _is_rooted = false;
246                         }
247                         _in_tree = true;
248                         _nh.append( line.substring( line.indexOf( '=' ) ) );
249                         final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
250                         if ( name_matcher.matches() ) {
251                             _name = name_matcher.group( 1 );
252                             _name = _name.replaceAll( "['\"]+", "" );
253                         }
254                         final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
255                         if ( rootedness_matcher.matches() ) {
256                             final String s = rootedness_matcher.group( 1 );
257                             line = line.replaceAll( "\\[\\&.\\]", "" );
258                             _rooted_info_present = true;
259                             if ( s.toUpperCase().equals( "R" ) ) {
260                                 _is_rooted = true;
261                             }
262                         }
263                         if ( might && ( _next != null ) ) {
264                             return;
265                         }
266                     }
267                     else if ( _in_tree && !_in_translate ) {
268                         _nh.append( line );
269                     }
270                     if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !_in_translate
271                             && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
272                         _in_tree = false;
273                         _in_translate = false;
274                         createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
275                         _nh = new StringBuilder();
276                         _name = "";
277                         _rooted_info_present = false;
278                         _is_rooted = false;
279                         if ( _next != null ) {
280                             return;
281                         }
282                     }
283                 }
284                 if ( _in_taxalabels ) {
285                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
286                         _in_taxalabels = false;
287                     }
288                     else {
289                         final String[] labels = line.split( "\\s+" );
290                         for( String label : labels ) {
291                             if ( !label.toLowerCase().equals( taxlabels ) ) {
292                                 if ( label.endsWith( ";" ) ) {
293                                     _in_taxalabels = false;
294                                     label = label.substring( 0, label.length() - 1 );
295                                 }
296                                 if ( label.length() > 0 ) {
297                                     _taxlabels.add( label );
298                                 }
299                             }
300                         }
301                     }
302                 }
303                 if ( _in_translate ) {
304                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
305                         _in_translate = false;
306                     }
307                     else {
308                         _translate_sb.append( " " );
309                         _translate_sb.append( line.trim() );
310                         if ( line.endsWith( ";" ) ) {
311                             _in_translate = false;
312                             setTranslateKeyValuePairs( _translate_sb );
313                         }
314                     }
315                 }
316             }
317         }
318         if ( _nh.length() > 0 ) {
319             createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
320             if ( _next != null ) {
321                 return;
322             }
323         }
324     }
325
326     private final void setTranslateKeyValuePairs( final StringBuilder translate_sb ) throws IOException {
327         String s = translate_sb.toString().trim();
328         if ( s.endsWith( ";" ) ) {
329             s = s.substring( 0, s.length() - 1 ).trim();
330         }
331         for( final String pair : s.split( "," ) ) {
332             final String[] kv = pair.trim().split( "\\s+" );
333             if ( ( kv.length < 2 ) || ( kv.length > 3 ) ) {
334                 throw new IOException( "ill-formatted translate values: " + translate_sb );
335             }
336             if ( ( kv.length == 3 ) && !kv[ 0 ].toLowerCase().trim().equals( translate ) ) {
337                 throw new IOException( "ill-formatted translate values: " + translate_sb );
338             }
339             String key = "";
340             String value = "";
341             if ( kv.length == 3 ) {
342                 key = kv[ 1 ];
343                 value = kv[ 2 ];
344             }
345             else {
346                 key = kv[ 0 ];
347                 value = kv[ 1 ];
348             }
349             if ( value.endsWith( ";" ) ) {
350                 value = value.substring( 0, value.length() - 1 );
351             }
352             _translate_map.put( key, value );
353         }
354     }
355
356     private final static String removeWhiteSpaceBeforeSemicolon( final String s ) {
357         return s.replaceAll( "\\s+;", ";" );
358     }
359
360     @Override
361     public String getName() {
362         return "Nexus Phylogenies Parser";
363     }
364 }