Fixed issue with reading from TreeBase
[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.AptxConstants;
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.data.Sequence;
49 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
50 import org.forester.sequence.BasicSequence;
51 import org.forester.sequence.MolecularSequence;
52 import org.forester.util.ForesterUtil;
53
54 public final class NexusPhylogeniesParser implements IteratingPhylogenyParser, PhylogenyParser {
55
56     final private static boolean DEBUG                               = false;
57     
58     final private static String            begin_trees               = NexusConstants.BEGIN_TREES.toLowerCase();
59     final private static String            end                       = NexusConstants.END.toLowerCase();
60     final private static String            endblock                  = "endblock";
61     final private static Pattern           ROOTEDNESS_PATTERN        = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
62     final private static String            taxlabels                 = NexusConstants.TAXLABELS.toLowerCase();
63     final private static Pattern           TITLE_PATTERN             = Pattern.compile( "TITLE.?\\s+([^;]+)",
64                                                                                         Pattern.CASE_INSENSITIVE );
65     final private static String            translate                 = NexusConstants.TRANSLATE.toLowerCase();
66     final private static String            data                      = NexusConstants.BEGIN_CHARACTERS.toLowerCase();
67     final private static String            characters                = NexusConstants.BEGIN_DATA.toLowerCase();
68     final private static String            tree                      = NexusConstants.TREE.toLowerCase();
69     final private static Pattern           TREE_NAME_PATTERN         = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
70                                                                                         Pattern.CASE_INSENSITIVE );
71     final private static Pattern           TRANSLATE_PATTERN         = Pattern.compile( "([0-9A-Za-z]+)\\s+(.+)" );
72     final private static Pattern           ALN_PATTERN               = Pattern.compile( "(.+)\\s+([A-Za-z-_\\*\\?]+)" );
73     final private static Pattern           DATATYPE_PATTERN          = Pattern.compile( "datatype\\s?.\\s?([a-z]+)" );
74     //final private static Pattern           LINK_TAXA_PATTERN         = Pattern.compile( "link\\s+taxa\\s?.\\s?([^;]+)",
75     //                                                                                    Pattern.CASE_INSENSITIVE );
76     final private static String            utree                     = NexusConstants.UTREE.toLowerCase();
77     private BufferedReader                 _br;
78     private boolean                        _ignore_quotes_in_nh_data = AptxConstants.NH_PARSING_IGNORE_QUOTES_DEFAULT;
79     private boolean                        _in_taxalabels;
80     private boolean                        _in_translate;
81     private boolean                        _in_tree;
82     private boolean                        _in_trees_block;
83     private boolean                        _in_data_block;
84     private boolean                        _is_rooted;
85     private String                         _datatype;
86     private String                         _name;
87     private Phylogeny                      _next;
88     private Object                         _nexus_source;
89     private StringBuilder                  _nh;
90     private boolean                        _replace_underscores      = NHXParser.REPLACE_UNDERSCORES_DEFAULT;
91     private boolean                        _rooted_info_present;
92     private List<String>                   _taxlabels;
93     private TAXONOMY_EXTRACTION            _taxonomy_extraction      = TAXONOMY_EXTRACTION.NO;
94     private String                         _title;
95     private Map<String, String>            _translate_map;
96     private StringBuilder                  _translate_sb;
97     private Map<String, MolecularSequence> _seqs;
98     private final boolean                  _add_sequences            = true;
99
100     @Override
101     public String getName() {
102         return "Nexus Phylogenies Parser";
103     }
104
105     @Override
106     public final boolean hasNext() {
107         return _next != null;
108     }
109
110     @Override
111     public final Phylogeny next() throws NHXFormatException, IOException {
112         final Phylogeny phy = _next;
113         getNext();
114         return phy;
115     }
116
117     @Override
118     public final Phylogeny[] parse() throws IOException {
119         final List<Phylogeny> l = new ArrayList<Phylogeny>();
120         while ( hasNext() ) {
121             l.add( next() );
122         }
123         final Phylogeny[] p = new Phylogeny[ l.size() ];
124         for( int i = 0; i < l.size(); ++i ) {
125             p[ i ] = l.get( i );
126         }
127         reset();
128         return p;
129     }
130
131     @Override
132     public final void reset() throws FileNotFoundException, IOException {
133         _taxlabels = new ArrayList<String>();
134         _translate_map = new HashMap<String, String>();
135         _nh = new StringBuilder();
136         _name = "";
137         _title = "";
138         _translate_sb = null;
139         _next = null;
140         _in_trees_block = false;
141         _in_taxalabels = false;
142         _in_translate = false;
143         _in_tree = false;
144         _rooted_info_present = false;
145         _is_rooted = false;
146         _seqs = new HashMap<String, MolecularSequence>();
147         _br = ParserUtils.createReader( _nexus_source );
148         getNext();
149     }
150
151     public final void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
152         _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
153     }
154
155     public final void setReplaceUnderscores( final boolean replace_underscores ) {
156         _replace_underscores = replace_underscores;
157     }
158
159     @Override
160     public final void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
161         if ( nexus_source == null ) {
162             throw new PhylogenyParserException( "attempt to parse null object" );
163         }
164         _nexus_source = nexus_source;
165         reset();
166     }
167
168     public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
169         _taxonomy_extraction = taxonomy_extraction;
170     }
171
172     private final void createPhylogeny( final String title,
173                                         final String name,
174                                         final StringBuilder nhx,
175                                         final boolean rooted_info_present,
176                                         final boolean is_rooted ) throws IOException {
177         _next = null;
178         final NHXParser pars = new NHXParser();
179         pars.setTaxonomyExtraction( _taxonomy_extraction );
180         pars.setReplaceUnderscores( _replace_underscores );
181         pars.setIgnoreQuotes( _ignore_quotes_in_nh_data );
182         if ( rooted_info_present ) {
183             pars.setGuessRootedness( false );
184         }
185         pars.setSource( nhx );
186         final Phylogeny p = pars.next();
187         if ( p == null ) {
188             throw new PhylogenyParserException( "failed to create phylogeny" );
189         }
190         String myname = null;
191         if ( !ForesterUtil.isEmpty( title ) && !ForesterUtil.isEmpty( name ) ) {
192             myname = title.replace( '_', ' ' ).trim() + " (" + name.trim() + ")";
193         }
194         else if ( !ForesterUtil.isEmpty( title ) ) {
195             myname = title.replace( '_', ' ' ).trim();
196         }
197         else if ( !ForesterUtil.isEmpty( name ) ) {
198             myname = name.trim();
199         }
200         if ( !ForesterUtil.isEmpty( myname ) ) {
201             p.setName( myname );
202         }
203         if ( rooted_info_present ) {
204             p.setRooted( is_rooted );
205         }
206         if ( ( _taxlabels.size() > 0 ) || ( _translate_map.size() > 0 ) ) {
207             final PhylogenyNodeIterator it = p.iteratorExternalForward();
208             while ( it.hasNext() ) {
209                 final PhylogenyNode node = it.next();
210                 if ( ( _translate_map.size() > 0 ) && _translate_map.containsKey( node.getName() ) ) {
211                     node.setName( _translate_map.get( node.getName() ).replaceAll( "['\"]+", "" ) );
212                 }
213                 else if ( _taxlabels.size() > 0 ) {
214                     int i = -1;
215                     try {
216                         i = Integer.parseInt( node.getName() );
217                     }
218                     catch ( final NumberFormatException e ) {
219                         // Ignore.
220                     }
221                     if ( i > 0 ) {
222                         node.setName( _taxlabels.get( i - 1 ).replaceAll( "['\"]+", "" ) );
223                     }
224                 }
225                 if ( !_replace_underscores && ( ( _taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
226                     ParserUtils.extractTaxonomyDataFromNodeName( node, _taxonomy_extraction );
227                 }
228                 else if ( _replace_underscores ) {
229                     if ( !ForesterUtil.isEmpty( node.getName() ) ) {
230                         node.setName( node.getName().replace( '_', ' ' ).trim() );
231                     }
232                 }
233                 if ( _add_sequences ) {
234                     if ( _seqs.containsKey( node.getName() ) ) {
235                         final MolecularSequence s = _seqs.get( node.getName() );
236                         //TODO need to check for uniqueness when adding seqs....
237                         final Sequence ns = new Sequence( s );
238                         ns.setMolecularSequenceAligned( true ); //TODO need to check if all same length
239                         node.getNodeData().addSequence( ns );
240                     }
241                 }
242             }
243         }
244         _next = p;
245     }
246
247     private final void getNext() throws IOException, NHXFormatException {
248         _next = null;
249         String line;
250         while ( ( line = _br.readLine() ) != null ) {
251             if ( DEBUG ) {
252                 System.out.println( line );
253             }
254             line = line.trim();
255             if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
256                 line = ForesterUtil.collapseWhiteSpace( line );
257                 line = removeWhiteSpaceBeforeSemicolon( line );
258                 final String line_lc = line.toLowerCase();
259                 if ( line_lc.startsWith( begin_trees ) ) {
260                     _in_trees_block = true;
261                     _in_taxalabels = false;
262                     _in_translate = false;
263                     _in_data_block = false;
264                     _datatype = null;
265                     _title = "";
266                 }
267                 else if ( line_lc.startsWith( taxlabels ) ) {
268                     //TODO need to be taxa block instead
269                     _in_trees_block = false;
270                     _in_taxalabels = true;
271                     _in_translate = false;
272                     _in_data_block = false;
273                     _datatype = null;
274                 }
275                 else if ( line_lc.startsWith( translate ) ) {
276                     _translate_sb = new StringBuilder();
277                     _in_taxalabels = false;
278                     _in_translate = true;
279                     _in_data_block = false;
280                     _datatype = null;
281                 }
282                 else if ( line_lc.startsWith( characters ) || line_lc.startsWith( data ) ) {
283                     _in_taxalabels = false;
284                     _in_trees_block = false;
285                     _in_translate = false;
286                     _in_data_block = true;
287                     _datatype = null;
288                 }
289                 else if ( _in_trees_block ) {
290                     if ( line_lc.startsWith( "title" ) ) {
291                         final Matcher title_m = TITLE_PATTERN.matcher( line );
292                         if ( title_m.lookingAt() ) {
293                             _title = title_m.group( 1 );
294                         }
295                     }
296                     else if ( line_lc.startsWith( "link" ) ) {
297                         //final Matcher link_m = LINK_TAXA_PATTERN.matcher( line );
298                         //if ( link_m.lookingAt() ) {
299                             //final String link = link_m.group( 1 );  //TODO why?
300                        // }
301                     }
302                     else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
303                         _in_trees_block = false;
304                         _in_tree = false;
305                         _in_translate = false;
306                         if ( _nh.length() > 0 ) {
307                             createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
308                             _nh = new StringBuilder();
309                             _name = "";
310                             _rooted_info_present = false;
311                             _is_rooted = false;
312                             if ( _next != null ) {
313                                 return;
314                             }
315                         }
316                     }
317                     else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
318                         boolean might = false;
319                         if ( _nh.length() > 0 ) {
320                             might = true;
321                             createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
322                             _nh = new StringBuilder();
323                             _name = "";
324                             _rooted_info_present = false;
325                             _is_rooted = false;
326                         }
327                         _in_tree = true;
328                         _nh.append( line.substring( line.indexOf( '=' ) ) );
329                         final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
330                         if ( name_matcher.matches() ) {
331                             _name = name_matcher.group( 1 );
332                             _name = _name.replaceAll( "['\"]+", "" );
333                         }
334                         final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
335                         if ( rootedness_matcher.matches() ) {
336                             final String s = rootedness_matcher.group( 1 );
337                             line = line.replaceAll( "\\[\\&.\\]", "" );
338                             _rooted_info_present = true;
339                             if ( s.toUpperCase().equals( "R" ) ) {
340                                 _is_rooted = true;
341                             }
342                         }
343                         if ( might && ( _next != null ) ) {
344                             return;
345                         }
346                     }
347                     else if ( _in_tree && !_in_translate ) {
348                         _nh.append( line );
349                     }
350                     if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !_in_translate
351                             && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
352                         _in_tree = false;
353                         _in_translate = false;
354                         createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
355                         _nh = new StringBuilder();
356                         _name = "";
357                         _rooted_info_present = false;
358                         _is_rooted = false;
359                         if ( _next != null ) {
360                             return;
361                         }
362                     }
363                 }
364                 if ( _in_taxalabels ) {
365                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
366                         _in_taxalabels = false;
367                     }
368                     else {
369                         final String[] labels = line.split( "\\s+" );
370                         for( String label : labels ) {
371                             if ( !label.toLowerCase().equals( taxlabels ) ) {
372                                 if ( label.endsWith( ";" ) ) {
373                                     _in_taxalabels = false;
374                                     label = label.substring( 0, label.length() - 1 );
375                                 }
376                                 if ( label.length() > 0 ) {
377                                     _taxlabels.add( label );
378                                 }
379                             }
380                         }
381                     }
382                 }
383                 if ( _in_translate ) {
384                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
385                         _in_translate = false;
386                     }
387                     else {
388                         _translate_sb.append( " " );
389                         _translate_sb.append( line.trim() );
390                         if ( line.endsWith( ";" ) ) {
391                             _in_translate = false;
392                             setTranslateKeyValuePairs( _translate_sb );
393                         }
394                     }
395                 }
396                 if ( _in_data_block ) {
397                     if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
398                         _in_data_block = false;
399                         _datatype = null;
400                     }
401                     else if ( line_lc.startsWith( "link" ) ) {
402                      //   final Matcher link_m = LINK_TAXA_PATTERN.matcher( line );
403                      //   if ( link_m.lookingAt() ) {
404                      //       final String link = link_m.group( 1 );
405                      //   }
406                     }
407                     else {
408                         final Matcher datatype_matcher = DATATYPE_PATTERN.matcher( line_lc );
409                         if ( datatype_matcher.find() ) {
410                             _datatype = datatype_matcher.group( 1 );
411                         }
412                         else {
413                             if ( ( _datatype != null )
414                                     && ( _datatype.equals( "protein" ) || _datatype.equals( "dna" ) || _datatype
415                                             .equals( "rna" ) ) ) {
416                                 if ( line.endsWith( ";" ) ) {
417                                     _in_data_block = false;
418                                     line = line.substring( 0, line.length() - 1 );
419                                 }
420                                 final Matcher aln_matcher = ALN_PATTERN.matcher( line );
421                                 if ( aln_matcher.matches() ) {
422                                     final String id = aln_matcher.group( 1 );
423                                     final String seq = aln_matcher.group( 2 );
424                                     MolecularSequence s = null;
425                                     if ( _datatype.equals( "protein" ) ) {
426                                         s = BasicSequence.createAaSequence( id, seq );
427                                     }
428                                     else if ( _datatype.equals( "dna" ) ) {
429                                         s = BasicSequence.createDnaSequence( id, seq );
430                                     }
431                                     else {
432                                         s = BasicSequence.createRnaSequence( id, seq );
433                                     }
434                                     _seqs.put( id, s );
435                                 }
436                             }
437                         }
438                     }
439                 }
440             }
441         }
442         if ( _nh.length() > 0 ) {
443             createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
444             if ( _next != null ) {
445                 return;
446             }
447         }
448     }
449
450     private final void setTranslateKeyValuePairs( final StringBuilder translate_sb ) throws IOException {
451         String s = translate_sb.toString().trim();
452         if ( s.endsWith( ";" ) ) {
453             s = s.substring( 0, s.length() - 1 ).trim();
454         }
455         for( String pair : s.split( "," ) ) {
456             String key = "";
457             String value = "";
458             final int ti = pair.toLowerCase().indexOf( "translate" );
459             if ( ti > -1 ) {
460                 pair = pair.substring( ti + 9 );
461             }
462             final Matcher m = TRANSLATE_PATTERN.matcher( pair );
463             if ( m.find() ) {
464                 key = m.group( 1 );
465                 value = m.group( 2 ).replaceAll( "\'", "" ).replaceAll( "\"", "" ).trim();
466             }
467             else {
468                 throw new IOException( "ill-formatted translate values: " + pair );
469             }
470             if ( value.endsWith( ";" ) ) {
471                 value = value.substring( 0, value.length() - 1 );
472             }
473             _translate_map.put( key, value );
474         }
475     }
476
477     private final static String removeWhiteSpaceBeforeSemicolon( final String s ) {
478         return s.replaceAll( "\\s+;", ";" );
479     }
480 }