3 import java.io.BufferedReader;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7 import java.io.IOException;
9 import java.util.ArrayList;
10 import java.util.HashMap;
11 import java.util.LinkedHashMap;
12 import java.util.List;
16 * A file parse for T-Coffee score ascii format. This file contains the alignment consensus
17 * for each resude in any sequence.
19 * This file is procuded by <code>t_coffee</code> providing the option
20 * <code>-output=score_ascii </code> to the program command line
22 * An example file is the following
25 * T-COFFEE, Version_9.02.r1228 (2012-02-16 18:15:12 - Revision 1228 - Build 336)
42 * 1PHT 999999999999999999999999998762112222543211112134
43 * 1BB9 99999999999999999999999999987-------4322----2234
44 * 1UHC 99999999999999999999999999987-------5321----2246
45 * 1YCS 99999999999999999999999999986-------4321----1-35
46 * 1OOT 999999999999999999999999999861-------3------1135
47 * 1ABO 99999999999999999999999999986-------422-------34
48 * 1FYN 99999999999999999999999999985-------32--------35
49 * 1QCF 99999999999999999999999999974-------2---------24
50 * cons 999999999999999999999999999851000110321100001134
53 * 1PHT ----------5666642367889999999999889
54 * 1BB9 1111111111676653-355679999999999889
55 * 1UHC ----------788774--66789999999999889
56 * 1YCS ----------78777--356789999999999889
57 * 1OOT ----------78877--356789999999997-67
58 * 1ABO ----------687774--56779999999999889
59 * 1FYN ----------6888842356789999999999889
60 * 1QCF ----------6878742356789999999999889
61 * cons 00100000006877641356789999999999889
65 * @author Paolo Di Tommaso
68 public class TCoffeeScoreFile {
70 /** The {@link Header} structure holder */
74 * Holds the consensues values for each sequences. It uses a LinkedHashMap to maintaint the
77 LinkedHashMap<String,StringBuilder> scores = new LinkedHashMap<String,StringBuilder>();
81 * Parse the specified file.
83 * @param file The file to be parsed
85 public static TCoffeeScoreFile load(File file) {
87 return load(new FileReader(file));
89 catch (FileNotFoundException e) {
90 throw new RuntimeException(e);
95 * Parse the provided reader for the T-Coffee scores file format
99 public static TCoffeeScoreFile load(Reader reader) {
102 BufferedReader in = (BufferedReader) (reader instanceof BufferedReader ? reader : new BufferedReader(reader));
103 TCoffeeScoreFile result = new TCoffeeScoreFile();
104 result.doParsing(in);
105 return result.header != null && result.scores != null ? result : null;
107 catch( Exception e) {
108 throw new RuntimeException(e);
113 * The default constructor is marked as {@code protected} since this class is meant to created
114 * through the {@link #load(File)} or {@link #load(Reader)} factory methods
116 protected TCoffeeScoreFile() { }
119 * Get the string of score values for the specified seqeunce ID.
120 * @param id The sequence ID
121 * @return The scores as a string of values e.g. {@code 99999987-------432}.
122 * It return an empty string when the specified ID is missing.
124 public String getScoresFor( String id ) {
125 return scores.containsKey(id) ? scores.get(id).toString() : "";
129 * @return The list of score string as a {@link List} object, in the same ordeer of the insertion i.e. in the MSA
131 public List<String> getScoresList() {
132 List<String> result = new ArrayList<String>( scores.size() );
133 for( Map.Entry<String,StringBuilder> it : scores.entrySet() ) {
134 result.add(it.getValue().toString());
141 * @return The parsed score values a matrix of bytes
143 public byte[][] getScoresArray() {
144 byte[][] result = new byte[ scores.size() ][];
147 for( Map.Entry<String,StringBuilder> it : scores.entrySet() ) {
148 String line = it.getValue().toString();
149 byte[] seqValues = new byte[ line.length() ];
150 for( int j=0, c=line.length(); j<c; j++ ) {
152 byte val = (byte)(line.charAt(j) - '0');
154 seqValues[j] = ( val >= 0 && val <= 9 ) ? val : -1;
157 result[rowCount++] = seqValues;
164 private void doParsing(BufferedReader in) throws IOException {
169 header = readHeader(in);
171 if( header == null ) { return; }
175 * initilize the structure
177 for( Map.Entry<String,Integer> entry : header.scores.entrySet() ) {
178 scores.put( entry.getKey(), new StringBuilder());
182 * go with the reading
185 while( (block = readBlock(in, header.scores.size())) != null ) {
188 * append sequences read in the block
190 for( Map.Entry<String,String> entry : block.items.entrySet() ) {
191 StringBuilder scoreStringBuilder = scores.get(entry.getKey());
192 if( scoreStringBuilder == null ) {
193 throw new RuntimeException(String.format("Invalid T-Coffee score file. Sequence ID '%s' is not declared in header section", entry.getKey()));
196 scoreStringBuilder.append( entry.getValue() );
204 static int parseInt( String str ) {
206 return Integer.parseInt(str);
208 catch( NumberFormatException e ) {
209 // TODO report a warning ?
215 * Reaad the header section in the T-Coffee score file format
217 * @param reader The scores reader
218 * @return The parser {@link Header} instance
219 * @throws RuntimeException when the header is not in the expected format
221 static Header readHeader(BufferedReader reader) {
223 Header result = null;
225 result = new Header();
226 result.head = reader.readLine();
230 while( (line = reader.readLine()) != null ) {
231 if( line.startsWith("SCORE=")) {
232 result.score = parseInt( line.substring(6).trim() );
237 if( (line=reader.readLine())==null || !"*".equals(line.trim())) return null;
238 if( (line=reader.readLine())==null || !"BAD AVG GOOD".equals(line.trim())) return null;
239 if( (line=reader.readLine())==null || !"*".equals(line.trim())) return null;
242 * now are expected a list if sequences ID up to the first blank line
244 while( (line=reader.readLine()) != null ) {
245 if( "".equals(line) ) {
249 int p = line.indexOf(":");
251 // TODO report a warning
255 String id = line.substring(0,p).trim();
256 int val = parseInt(line.substring(p+1).trim());
257 if( "".equals(id) ) {
258 // TODO report warning
262 result.scores.put(id,val);
266 catch( IOException e ) {
267 throw new RuntimeException("Cannot parse T-Coffee score ascii file", e);
274 * Read a scores block ihe provided stream.
276 * @param reader The stream to parse
277 * @param size The expected number of the sequence to be read
278 * @return The {@link Block} instance read or {link null} null if the end of file has reached.
279 * @throws IOException Something went wrong on the 'wire'
281 static Block readBlock( BufferedReader reader, int size ) throws IOException {
282 Block result = new Block(size);
286 * read blank lines (eventually)
288 while( (line=reader.readLine()) != null && "".equals(line.trim())) {
289 // consume blank lines
292 if( line == null ) return null;
295 * read the scores block
298 if( "".equals(line.trim()) ) {
303 // split the line on the first blank
304 // the first part have to contain the sequence id
305 // theramining part are the scores values
306 int p = line.indexOf(" ");
308 //TODO This is an unexpected condition, log a warning or throw an exception ?
312 String id = line.substring(0,p).trim();
313 String val = line.substring(p+1).trim();
315 result.items.put(id, val);
317 } while( (line = reader.readLine()) != null );
324 * The score file header
326 static class Header {
330 LinkedHashMap<String,Integer> scores = new LinkedHashMap<String,Integer>();
332 public int getScoreAvg() { return score; }
334 public int getScoreFor( String ID ) {
336 return scores.containsKey(ID) ? scores.get(ID) : -1;
342 * Hold a single block values block in the score file
346 Map<String,String> items;
348 public Block( int size ) {
350 this.items = new HashMap<String,String>(size);
353 String getScoresFor( String id ) {
354 return items.get(id);
357 String getConsensus() {
358 return items.get("cons");