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