2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.SequenceI;
29 import java.awt.Color;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.LinkedHashMap;
34 import java.util.List;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
40 * A file parser for T-Coffee score ascii format. This file contains the
41 * alignment consensus for each residue in any sequence.
43 * This file is produced by <code>t_coffee</code> providing the option
44 * <code>-output=score_ascii </code> to the program command line
46 * An example file is the following
49 * T-COFFEE, Version_9.02.r1228 (2012-02-16 18:15:12 - Revision 1228 - Build 336)
66 * 1PHT 999999999999999999999999998762112222543211112134
67 * 1BB9 99999999999999999999999999987-------4322----2234
68 * 1UHC 99999999999999999999999999987-------5321----2246
69 * 1YCS 99999999999999999999999999986-------4321----1-35
70 * 1OOT 999999999999999999999999999861-------3------1135
71 * 1ABO 99999999999999999999999999986-------422-------34
72 * 1FYN 99999999999999999999999999985-------32--------35
73 * 1QCF 99999999999999999999999999974-------2---------24
74 * cons 999999999999999999999999999851000110321100001134
77 * 1PHT ----------5666642367889999999999889
78 * 1BB9 1111111111676653-355679999999999889
79 * 1UHC ----------788774--66789999999999889
80 * 1YCS ----------78777--356789999999999889
81 * 1OOT ----------78877--356789999999997-67
82 * 1ABO ----------687774--56779999999999889
83 * 1FYN ----------6888842356789999999999889
84 * 1QCF ----------6878742356789999999999889
85 * cons 00100000006877641356789999999999889
89 * @author Paolo Di Tommaso
92 public class TCoffeeScoreFile extends AlignFile
96 * TCOFFEE score colourscheme
98 static final Color[] colors = { new Color(102, 102, 255), // 0: lilac #6666FF
99 new Color(0, 255, 0), // 1: green #00FF00
100 new Color(102, 255, 0), // 2: lime green #66FF00
101 new Color(204, 255, 0), // 3: greeny yellow #CCFF00
102 new Color(255, 255, 0), // 4: yellow #FFFF00
103 new Color(255, 204, 0), // 5: orange #FFCC00
104 new Color(255, 153, 0), // 6: deep orange #FF9900
105 new Color(255, 102, 0), // 7: ochre #FF6600
106 new Color(255, 51, 0), // 8: red #FF3300
107 new Color(255, 34, 0) // 9: redder #FF2000
110 public final static String TCOFFEE_SCORE = "TCoffeeScore";
112 static Pattern SCORES_WITH_RESIDUE_NUMS = Pattern
113 .compile("^\\d+\\s([^\\s]+)\\s+\\d+$");
115 /** The {@link Header} structure holder */
119 * Holds the consensues values for each sequences. It uses a LinkedHashMap to
120 * maintaint the insertion order.
122 LinkedHashMap<String, StringBuilder> scores;
126 public TCoffeeScoreFile(String inFile, DataSourceType fileSourceType)
129 super(inFile, fileSourceType);
133 public TCoffeeScoreFile(FileParse source) throws IOException
139 * Parse the provided reader for the T-Coffee scores file format
142 * public static TCoffeeScoreFile load(Reader reader) {
144 * try { BufferedReader in = (BufferedReader) (reader instanceof
145 * BufferedReader ? reader : new BufferedReader(reader));
146 * TCoffeeScoreFile result = new TCoffeeScoreFile();
147 * result.doParsing(in); return result.header != null &&
148 * result.scores != null ? result : null; } catch( Exception e) {
149 * throw new RuntimeException(e); } }
153 * @return The 'height' of the score matrix i.e. the numbers of score rows
154 * that should matches the number of sequences in the alignment
156 public int getHeight()
158 // the last entry will always be the 'global' alingment consensus scores, so
160 // from the 'height' count to make this value compatible with the number of
161 // sequences in the MSA
162 return scores != null && scores.size() > 0 ? scores.size() - 1 : 0;
166 * @return The 'width' of the score matrix i.e. the number of columns. Since
167 * the score value are supposed to be calculated for an 'aligned' MSA,
168 * all the entries have to have the same width.
170 public int getWidth()
172 return fWidth != null ? fWidth : 0;
176 * Get the string of score values for the specified seqeunce ID.
180 * @return The scores as a string of values e.g. {@code 99999987-------432}.
181 * It return an empty string when the specified ID is missing.
183 public String getScoresFor(String id)
185 return scores != null && scores.containsKey(id)
186 ? scores.get(id).toString()
191 * @return The list of score string as a {@link List} object, in the same
192 * ordeer of the insertion i.e. in the MSA
194 public List<String> getScoresList()
200 List<String> result = new ArrayList<String>(scores.size());
201 for (Map.Entry<String, StringBuilder> it : scores.entrySet())
203 result.add(it.getValue().toString());
210 * @return The parsed score values a matrix of bytes
212 public byte[][] getScoresArray()
218 byte[][] result = new byte[scores.size()][];
221 for (Map.Entry<String, StringBuilder> it : scores.entrySet())
223 String line = it.getValue().toString();
224 byte[] seqValues = new byte[line.length()];
225 for (int j = 0, c = line.length(); j < c; j++)
228 byte val = (byte) (line.charAt(j) - '0');
230 seqValues[j] = (val >= 0 && val <= 9) ? val : -1;
233 result[rowCount++] = seqValues;
240 public void parse() throws IOException
245 header = readHeader(this);
252 scores = new LinkedHashMap<String, StringBuilder>();
255 * initilize the structure
257 for (Map.Entry<String, Integer> entry : header.scores.entrySet())
259 scores.put(entry.getKey(), new StringBuilder());
263 * go with the reading
266 while ((block = readBlock(this, header.scores.size())) != null)
270 * append sequences read in the block
272 for (Map.Entry<String, String> entry : block.items.entrySet())
274 StringBuilder scoreStringBuilder = scores.get(entry.getKey());
275 if (scoreStringBuilder == null)
278 errormessage = String.format(
279 "Invalid T-Coffee score file: Sequence ID '%s' is not declared in header section",
284 scoreStringBuilder.append(entry.getValue());
289 * verify that all rows have the same width
291 for (StringBuilder str : scores.values())
295 fWidth = str.length();
297 else if (fWidth != str.length())
300 errormessage = "Invalid T-Coffee score file: All the score sequences must have the same length";
308 static int parseInt(String str)
312 return Integer.parseInt(str);
313 } catch (NumberFormatException e)
315 // TODO report a warning ?
321 * Reaad the header section in the T-Coffee score file format
325 * @return The parser {@link Header} instance
326 * @throws RuntimeException
327 * when the header is not in the expected format
329 static Header readHeader(FileParse reader) throws IOException
332 Header result = null;
335 result = new Header();
336 result.head = reader.nextLine();
340 while ((line = reader.nextLine()) != null)
342 if (line.startsWith("SCORE="))
344 result.score = parseInt(line.substring(6).trim());
349 if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
352 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
355 if ((line = reader.nextLine()) == null
356 || !"BAD AVG GOOD".equals(line.trim()))
359 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
362 if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
365 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
370 * now are expected a list if sequences ID up to the first blank line
372 while ((line = reader.nextLine()) != null)
379 int p = line.indexOf(":");
382 // TODO report a warning
386 String id = line.substring(0, p).trim();
387 int val = parseInt(line.substring(p + 1).trim());
390 // TODO report warning
394 result.scores.put(id, val);
399 error(reader, "T-COFFEE score file had no per-sequence scores");
402 } catch (IOException e)
404 error(reader, "Unexpected problem parsing T-Coffee score ascii file");
411 private static void error(FileParse reader, String errm)
414 if (reader.errormessage == null)
416 reader.errormessage = errm;
420 reader.errormessage += "\n" + errm;
425 * Read a scores block ihe provided stream.
428 * The stream to parse
430 * The expected number of the sequence to be read
431 * @return The {@link Block} instance read or {link null} null if the end of
433 * @throws IOException
434 * Something went wrong on the 'wire'
436 static Block readBlock(FileParse reader, int size) throws IOException
438 Block result = new Block(size);
442 * read blank lines (eventually)
444 while ((line = reader.nextLine()) != null && "".equals(line.trim()))
446 // consume blank lines
455 * read the scores block
459 if ("".equals(line.trim()))
465 // split the line on the first blank
466 // the first part have to contain the sequence id
467 // the remaining part are the scores values
468 int p = line.indexOf(" ");
471 if (reader.warningMessage == null)
473 reader.warningMessage = "";
475 reader.warningMessage += "Possible parsing error - expected to find a space in line: '"
480 String id = line.substring(0, p).trim();
481 String val = line.substring(p + 1).trim();
483 Matcher m = SCORES_WITH_RESIDUE_NUMS.matcher(val);
489 result.items.put(id, val);
491 } while ((line = reader.nextLine()) != null);
497 * The score file header
505 LinkedHashMap<String, Integer> scores = new LinkedHashMap<String, Integer>();
507 public int getScoreAvg()
512 public int getScoreFor(String ID)
515 return scores.containsKey(ID) ? scores.get(ID) : -1;
521 * Hold a single block values block in the score file
527 Map<String, String> items;
529 public Block(int size)
532 this.items = new HashMap<String, String>(size);
535 String getScoresFor(String id)
537 return items.get(id);
540 String getConsensus()
542 return items.get("cons");
547 * generate annotation for this TCoffee score set on the given alignment
550 * alignment to annotate
552 * if true, annotate sequences based on matching sequence names
553 * @return true if alignment annotation was modified, false otherwise.
555 public boolean annotateAlignment(AlignmentI al, boolean matchids)
557 if (al.getHeight() != getHeight() || al.getWidth() != getWidth())
559 String info = String.format(
560 "align w: %s, h: %s; score: w: %s; h: %s ", al.getWidth(),
561 al.getHeight(), getWidth(), getHeight());
562 warningMessage = "Alignment shape does not match T-Coffee score file shape -- "
566 boolean added = false;
568 SequenceIdMatcher sidmatcher = new SequenceIdMatcher(
569 al.getSequencesArray());
570 byte[][] scoreMatrix = getScoresArray();
571 // for 2.8 - we locate any existing TCoffee annotation and remove it first
572 // before adding this.
573 for (Map.Entry<String, StringBuilder> id : scores.entrySet())
575 byte[] srow = scoreMatrix[i];
579 s = sidmatcher.findIdMatch(id.getKey());
583 s = al.getSequenceAt(i);
586 if (s == null && i != scores.size() && !id.getKey().equals("cons"))
589 .println("No " + (matchids ? "match " : " sequences left ")
590 + " for TCoffee score set : " + id.getKey());
593 int jSize = al.getWidth() < srow.length ? al.getWidth() : srow.length;
594 Annotation[] annotations = new Annotation[al.getWidth()];
595 for (int j = 0; j < jSize; j++)
598 if (s != null && jalview.util.Comparison.isGap(s.getCharAt(j)))
600 annotations[j] = null;
604 "Warning: non-zero value for positional T-COFFEE score for gap at "
605 + j + " in sequence " + s.getName());
610 annotations[j] = new Annotation(s == null ? "" + val : null,
611 s == null ? "" + val : null, '\0', val * 1f,
612 val >= 0 && val < colors.length ? colors[val]
616 // this will overwrite any existing t-coffee scores for the alignment
617 AlignmentAnnotation aa = al.findOrCreateAnnotation(TCOFFEE_SCORE,
618 TCOFFEE_SCORE, false, s, null);
621 aa.label = "T-COFFEE";
622 aa.description = "" + id.getKey();
623 aa.annotations = annotations;
625 aa.belowAlignment = false;
626 aa.setScore(header.getScoreFor(id.getKey()));
627 aa.createSequenceMapping(s, s.getStart(), true);
628 s.addAlignmentAnnotation(aa);
629 aa.adjustForAlignment();
633 aa.graph = AlignmentAnnotation.NO_GRAPH;
634 aa.label = "T-COFFEE";
635 aa.description = "TCoffee column reliability score";
636 aa.annotations = annotations;
637 aa.belowAlignment = true;
639 aa.setScore(header.getScoreAvg());
641 aa.showAllColLabels = true;
642 aa.validateRangeAndDisplay();
650 public String print(SequenceI[] sqs, boolean jvsuffix)
652 // TODO Auto-generated method stub