7b7bface1492133dc0ea736277687d4f32c12c8d
[jalview.git] / forester / java / src / org / forester / io / parsers / FastaParser.java
1 // $Id:
2 //
3 // forester -- software libraries and applications
4 // for genomics and evolutionary biology research.
5 //
6 // Copyright (C) 2010 Christian M Zmasek
7 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
8 // All rights reserved
9 //
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/forester
26
27 package org.forester.io.parsers;
28
29 import java.io.BufferedReader;
30 import java.io.ByteArrayInputStream;
31 import java.io.File;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.util.ArrayList;
37 import java.util.List;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import org.forester.msa.BasicMsa;
42 import org.forester.msa.Msa;
43 import org.forester.msa.MsaFormatException;
44 import org.forester.phylogeny.Phylogeny;
45 import org.forester.phylogeny.PhylogenyNode;
46 import org.forester.phylogeny.data.Accession;
47 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
48 import org.forester.sequence.BasicSequence;
49 import org.forester.sequence.Sequence;
50 import org.forester.util.ForesterUtil;
51
52 public class FastaParser {
53
54     private static final Pattern NAME_REGEX      = Pattern.compile( "^\\s*>\\s*(.+)" );
55     private static final Pattern SEQ_REGEX       = Pattern.compile( "^\\s*(.+)" );
56     private static final Pattern ANYTHING_REGEX  = Pattern.compile( "[\\d\\s]+" );
57     //>gi|71834668|ref|NP_001025424.1| Bcl2 [Danio rerio]
58     private static final Pattern FASTA_DESC_LINE = Pattern
59                                                          .compile( ">?\\s*([^|]+)\\|([^|]+)\\S*\\s+(.+)\\s+\\[(.+)\\]" );
60
61     public static void main( final String[] args ) {
62         final String a = ">gi|71834668|ref|NP_001025424.1| Bcl2 [Danio rerio]";
63         final Matcher name_m = FASTA_DESC_LINE.matcher( a );
64         if ( name_m.lookingAt() ) {
65             System.out.println();
66             System.out.println( name_m.group( 1 ) );
67             System.out.println( name_m.group( 2 ) );
68             System.out.println( name_m.group( 3 ) );
69             System.out.println( name_m.group( 4 ) );
70         }
71         else {
72             System.out.println( "Does not match." );
73         }
74     }
75
76     static public boolean isLikelyFasta( final InputStream is ) throws IOException {
77         final BufferedReader reader = new BufferedReader( new InputStreamReader( is, "UTF-8" ) );
78         String line = null;
79         while ( ( line = reader.readLine() ) != null ) {
80             final boolean is_name_line = NAME_REGEX.matcher( line ).lookingAt();
81             if ( canIgnore( line, true, false ) ) {
82                 continue;
83             }
84             else if ( is_name_line ) {
85                 reader.close();
86                 return true;
87             }
88             else if ( SEQ_REGEX.matcher( line ).lookingAt() ) {
89                 reader.close();
90                 return false;
91             }
92         }
93         reader.close();
94         return false;
95     }
96
97     static public Msa parseMsa( final File f ) throws IOException {
98         return parseMsa( new FileInputStream( f ) );
99     }
100
101     static public Msa parseMsa( final InputStream is ) throws IOException {
102         return BasicMsa.createInstance( parse( is ) );
103     }
104
105     static public Msa parseMsa( final String s ) throws IOException {
106         return parseMsa( s.getBytes() );
107     }
108
109     static public Msa parseMsa( final byte[] bytes ) throws IOException {
110         return parseMsa( new ByteArrayInputStream( bytes ) );
111     }
112
113     static public List<Sequence> parse( final File f ) throws IOException {
114         return parse( new FileInputStream( f ) );
115     }
116
117     static public List<Sequence> parse( final InputStream is ) throws IOException {
118         final BufferedReader reader = new BufferedReader( new InputStreamReader( is, "UTF-8" ) );
119         String line = null;
120         int line_counter = 0;
121         boolean saw_first_seq = false;
122         StringBuilder current_seq = null;
123         StringBuilder name = null;
124         final List<StringBuilder[]> temp_msa = new ArrayList<StringBuilder[]>();
125         while ( ( line = reader.readLine() ) != null ) {
126             ++line_counter;
127             final Matcher name_m = NAME_REGEX.matcher( line );
128             final boolean is_name_line = name_m.lookingAt();
129             if ( canIgnore( line, saw_first_seq, is_name_line ) ) {
130                 continue;
131             }
132             final Matcher seq_m = SEQ_REGEX.matcher( line );
133             if ( is_name_line ) {
134                 saw_first_seq = true;
135                 addSeq( name, current_seq, temp_msa );
136                 name = new StringBuilder( name_m.group( 1 ).trim() );
137                 current_seq = new StringBuilder();
138             }
139             else if ( seq_m.lookingAt() ) {
140                 if ( name.length() < 1 ) {
141                     reader.close();
142                     throw new MsaFormatException( "illegally formatted fasta msa (line: " + line_counter + "):\n\""
143                             + trim( line ) + "\"" );
144                 }
145                 current_seq.append( seq_m.group( 1 ).replaceAll( "\\s+", "" ) );
146             }
147             else {
148                 reader.close();
149                 throw new MsaFormatException( "illegally formatted fasta msa (line: " + line_counter + "):\n\""
150                         + trim( line ) + "\"" );
151             }
152         }
153         addSeq( name, current_seq, temp_msa );
154         reader.close();
155         final List<Sequence> seqs = new ArrayList<Sequence>();
156         for( int i = 0; i < temp_msa.size(); ++i ) {
157             seqs.add( BasicSequence.createAaSequence( temp_msa.get( i )[ 0 ].toString(),
158                                                       temp_msa.get( i )[ 1 ].toString() ) );
159         }
160         return seqs;
161     }
162
163     static private boolean canIgnore( final String line, final boolean saw_first_seq, final boolean is_name_line ) {
164         if ( ( line.length() < 1 ) || ANYTHING_REGEX.matcher( line ).matches() ) {
165             return true;
166         }
167         if ( !saw_first_seq && !is_name_line ) {
168             return true;
169         }
170         return false;
171     }
172
173     private static void addSeq( final StringBuilder name, final StringBuilder seq, final List<StringBuilder[]> temp_msa ) {
174         if ( ( name != null ) && ( seq != null ) && ( name.length() > 0 ) && ( seq.length() > 0 ) ) {
175             final StringBuilder[] ary = new StringBuilder[ 2 ];
176             ary[ 0 ] = name;
177             ary[ 1 ] = seq;
178             temp_msa.add( ary );
179         }
180     }
181
182     private static String trim( final String line ) {
183         if ( line.length() > 100 ) {
184             return line.substring( 0, 100 ) + " ...";
185         }
186         return line;
187     }
188
189     public static void extractFastaInformation( final Phylogeny phy ) {
190         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
191             final PhylogenyNode node = iter.next();
192             if ( !ForesterUtil.isEmpty( node.getName() ) ) {
193                 final Matcher name_m = FASTA_DESC_LINE.matcher( node.getName() );
194                 if ( name_m.lookingAt() ) {
195                     System.out.println();
196                     // System.out.println( name_m.group( 1 ) );
197                     // System.out.println( name_m.group( 2 ) );
198                     // System.out.println( name_m.group( 3 ) );
199                     // System.out.println( name_m.group( 4 ) );
200                     final String acc_source = name_m.group( 1 );
201                     final String acc = name_m.group( 2 );
202                     final String seq_name = name_m.group( 3 );
203                     final String tax_sn = name_m.group( 4 );
204                     if ( !ForesterUtil.isEmpty( acc_source ) && !ForesterUtil.isEmpty( acc ) ) {
205                         ForesterUtil.ensurePresenceOfSequence( node );
206                         node.getNodeData().getSequence( 0 ).setAccession( new Accession( acc, acc_source ) );
207                     }
208                     if ( !ForesterUtil.isEmpty( seq_name ) ) {
209                         ForesterUtil.ensurePresenceOfSequence( node );
210                         node.getNodeData().getSequence( 0 ).setName( seq_name );
211                     }
212                     if ( !ForesterUtil.isEmpty( tax_sn ) ) {
213                         ForesterUtil.ensurePresenceOfTaxonomy( node );
214                         node.getNodeData().getTaxonomy( 0 ).setScientificName( tax_sn );
215                     }
216                 }
217             }
218         }
219     }
220 }