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;
28 import jalview.util.Comparison;
30 import java.awt.Color;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.LinkedHashMap;
35 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
41 * A file parse for T-Coffee score ascii format. This file contains the
42 * alignment consensus for each resude in any sequence.
44 * This file is procuded by <code>t_coffee</code> providing the option
45 * <code>-output=score_ascii </code> to the program command line
47 * An example file is the following
50 * T-COFFEE, Version_9.02.r1228 (2012-02-16 18:15:12 - Revision 1228 - Build 336)
67 * 1PHT 999999999999999999999999998762112222543211112134
68 * 1BB9 99999999999999999999999999987-------4322----2234
69 * 1UHC 99999999999999999999999999987-------5321----2246
70 * 1YCS 99999999999999999999999999986-------4321----1-35
71 * 1OOT 999999999999999999999999999861-------3------1135
72 * 1ABO 99999999999999999999999999986-------422-------34
73 * 1FYN 99999999999999999999999999985-------32--------35
74 * 1QCF 99999999999999999999999999974-------2---------24
75 * cons 999999999999999999999999999851000110321100001134
78 * 1PHT ----------5666642367889999999999889
79 * 1BB9 1111111111676653-355679999999999889
80 * 1UHC ----------788774--66789999999999889
81 * 1YCS ----------78777--356789999999999889
82 * 1OOT ----------78877--356789999999997-67
83 * 1ABO ----------687774--56779999999999889
84 * 1FYN ----------6888842356789999999999889
85 * 1QCF ----------6878742356789999999999889
86 * cons 00100000006877641356789999999999889
90 * @author Paolo Di Tommaso
93 public class TCoffeeScoreFile extends AlignFile
95 public TCoffeeScoreFile(String inFile, String type) throws IOException
101 public TCoffeeScoreFile(FileParse source) throws IOException
106 /** The {@link Header} structure holder */
110 * Holds the consensues values for each sequences. It uses a LinkedHashMap to
111 * maintaint the insertion order.
113 LinkedHashMap<String, StringBuilder> scores;
118 * Parse the provided reader for the T-Coffee scores file format
121 * public static TCoffeeScoreFile load(Reader reader) {
123 * try { BufferedReader in = (BufferedReader) (reader instanceof
124 * BufferedReader ? reader : new BufferedReader(reader));
125 * TCoffeeScoreFile result = new TCoffeeScoreFile();
126 * result.doParsing(in); return result.header != null &&
127 * result.scores != null ? result : null; } catch( Exception e) {
128 * throw new RuntimeException(e); } }
132 * @return The 'height' of the score matrix i.e. the numbers of score rows
133 * that should matches the number of sequences in the alignment
135 public int getHeight()
137 // the last entry will always be the 'global' alingment consensus scores, so
139 // from the 'height' count to make this value compatible with the number of
140 // sequences in the MSA
141 return scores != null && scores.size() > 0 ? scores.size() - 1 : 0;
145 * @return The 'width' of the score matrix i.e. the number of columns. Since
146 * the score value are supposed to be calculated for an 'aligned' MSA,
147 * all the entries have to have the same width.
149 public int getWidth()
151 return fWidth != null ? fWidth : 0;
155 * Get the string of score values for the specified seqeunce ID.
159 * @return The scores as a string of values e.g. {@code 99999987-------432}.
160 * It return an empty string when the specified ID is missing.
162 public String getScoresFor(String id)
164 return scores != null && scores.containsKey(id) ? scores.get(id)
169 * @return The list of score string as a {@link List} object, in the same
170 * ordeer of the insertion i.e. in the MSA
172 public List<String> getScoresList()
178 List<String> result = new ArrayList<String>(scores.size());
179 for (Map.Entry<String, StringBuilder> it : scores.entrySet())
181 result.add(it.getValue().toString());
188 * @return The parsed score values a matrix of bytes
190 public byte[][] getScoresArray()
196 byte[][] result = new byte[scores.size()][];
199 for (Map.Entry<String, StringBuilder> it : scores.entrySet())
201 String line = it.getValue().toString();
202 byte[] seqValues = new byte[line.length()];
203 for (int j = 0, c = line.length(); j < c; j++)
206 byte val = (byte) (line.charAt(j) - '0');
208 seqValues[j] = (val >= 0 && val <= 9) ? val : -1;
211 result[rowCount++] = seqValues;
217 public void parse() throws IOException
222 header = readHeader(this);
229 scores = new LinkedHashMap<String, StringBuilder>();
232 * initilize the structure
234 for (Map.Entry<String, Integer> entry : header.scores.entrySet())
236 scores.put(entry.getKey(), new StringBuilder());
240 * go with the reading
243 while ((block = readBlock(this, header.scores.size())) != null)
247 * append sequences read in the block
249 for (Map.Entry<String, String> entry : block.items.entrySet())
251 StringBuilder scoreStringBuilder = scores.get(entry.getKey());
252 if (scoreStringBuilder == null)
255 errormessage = String
256 .format("Invalid T-Coffee score file: Sequence ID '%s' is not declared in header section",
261 scoreStringBuilder.append(entry.getValue());
266 * verify that all rows have the same width
268 for (StringBuilder str : scores.values())
272 fWidth = str.length();
274 else if (fWidth != str.length())
277 errormessage = "Invalid T-Coffee score file: All the score sequences must have the same length";
285 static int parseInt(String str)
289 return Integer.parseInt(str);
290 } catch (NumberFormatException e)
292 // TODO report a warning ?
298 * Reaad the header section in the T-Coffee score file format
302 * @return The parser {@link Header} instance
303 * @throws RuntimeException
304 * when the header is not in the expected format
306 static Header readHeader(FileParse reader) throws IOException
309 Header result = null;
312 result = new Header();
313 result.head = reader.nextLine();
317 while ((line = reader.nextLine()) != null)
319 if (line.startsWith("SCORE="))
321 result.score = parseInt(line.substring(6).trim());
326 if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
329 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
332 if ((line = reader.nextLine()) == null
333 || !"BAD AVG GOOD".equals(line.trim()))
336 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
339 if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
342 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
347 * now are expected a list if sequences ID up to the first blank line
349 while ((line = reader.nextLine()) != null)
356 int p = line.indexOf(":");
359 // TODO report a warning
363 String id = line.substring(0, p).trim();
364 int val = parseInt(line.substring(p + 1).trim());
367 // TODO report warning
371 result.scores.put(id, val);
376 error(reader, "T-COFFEE score file had no per-sequence scores");
379 } catch (IOException e)
381 error(reader, "Unexpected problem parsing T-Coffee score ascii file");
388 private static void error(FileParse reader, String errm)
391 if (reader.errormessage == null)
393 reader.errormessage = errm;
397 reader.errormessage += "\n" + errm;
401 static Pattern SCORES_WITH_RESIDUE_NUMS = Pattern
402 .compile("^\\d+\\s([^\\s]+)\\s+\\d+$");
405 * Read a scores block ihe provided stream.
408 * The stream to parse
410 * The expected number of the sequence to be read
411 * @return The {@link Block} instance read or {link null} null if the end of
413 * @throws IOException
414 * Something went wrong on the 'wire'
416 static Block readBlock(FileParse reader, int size) throws IOException
418 Block result = new Block(size);
422 * read blank lines (eventually)
424 while ((line = reader.nextLine()) != null && "".equals(line.trim()))
426 // consume blank lines
435 * read the scores block
439 if ("".equals(line.trim()))
445 // split the line on the first blank
446 // the first part have to contain the sequence id
447 // the remaining part are the scores values
448 int p = line.indexOf(" ");
451 if (reader.warningMessage == null)
453 reader.warningMessage = "";
455 reader.warningMessage += "Possible parsing error - expected to find a space in line: '"
460 String id = line.substring(0, p).trim();
461 String val = line.substring(p + 1).trim();
463 Matcher m = SCORES_WITH_RESIDUE_NUMS.matcher(val);
469 result.items.put(id, val);
471 } while ((line = reader.nextLine()) != null);
477 * The score file header
485 LinkedHashMap<String, Integer> scores = new LinkedHashMap<String, Integer>();
487 public int getScoreAvg()
492 public int getScoreFor(String ID)
495 return scores.containsKey(ID) ? scores.get(ID) : -1;
501 * Hold a single block values block in the score file
507 Map<String, String> items;
509 public Block(int size)
512 this.items = new HashMap<String, String>(size);
515 String getScoresFor(String id)
517 return items.get(id);
520 String getConsensus()
522 return items.get("cons");
527 * TCOFFEE score colourscheme
529 static final Color[] colors =
530 { new Color(102, 102, 255), // #6666FF
531 new Color(0, 255, 0), // #00FF00
532 new Color(102, 255, 0), // #66FF00
533 new Color(204, 255, 0), // #CCFF00
534 new Color(255, 255, 0), // #FFFF00
535 new Color(255, 204, 0), // #FFCC00
536 new Color(255, 153, 0), // #FF9900
537 new Color(255, 102, 0), // #FF6600
538 new Color(255, 51, 0), // #FF3300
539 new Color(255, 34, 0) // #FF2000
542 public final static String TCOFFEE_SCORE = "TCoffeeScore";
545 * generate annotation for this TCoffee score set on the given alignment
548 * alignment to annotate
550 * if true, annotate sequences based on matching sequence names
551 * @return true if alignment annotation was modified, false otherwise.
553 public boolean annotateAlignment(AlignmentI al, boolean matchids)
555 if (al.getHeight() != getHeight() || al.getWidth() != getWidth())
557 String info = String.format(
558 "align w: %s, h: %s; score: w: %s; h: %s ", al.getWidth(),
559 al.getHeight(), getWidth(), getHeight());
560 warningMessage = "Alignment shape does not match T-Coffee score file shape -- "
564 boolean added = false;
566 SequenceIdMatcher sidmatcher = new SequenceIdMatcher(
567 al.getSequencesArray());
568 byte[][] scoreMatrix = getScoresArray();
569 // for 2.8 - we locate any existing TCoffee annotation and remove it first
570 // before adding this.
571 for (Map.Entry<String, StringBuilder> id : scores.entrySet())
573 byte[] srow = scoreMatrix[i];
577 s = sidmatcher.findIdMatch(id.getKey());
581 s = al.getSequenceAt(i);
584 if (s == null && i != scores.size() && !id.getKey().equals("cons"))
586 System.err.println("No "
587 + (matchids ? "match " : " sequences left ")
588 + " for TCoffee score set : " + id.getKey());
591 int jSize = al.getWidth() < srow.length ? al.getWidth() : srow.length;
592 Annotation[] annotations = new Annotation[al.getWidth()];
593 for (int j = 0; j < jSize; j++)
596 if (s != null && Comparison.isGap(s.getCharAt(j)))
598 annotations[j] = null;
602 .println("Warning: non-zero value for positional T-COFFEE score for gap at "
603 + j + " in sequence " + s.getName());
608 annotations[j] = new Annotation(s == null ? "" + val : null,
609 s == null ? "" + val : null, '\0', val * 1f, val >= 0
610 && val < colors.length ? colors[val]
614 // this will overwrite any existing t-coffee scores for the alignment
615 AlignmentAnnotation aa = al.findOrCreateAnnotation(TCOFFEE_SCORE,
616 TCOFFEE_SCORE, false, s, null);
619 aa.label = "T-COFFEE";
620 aa.description = "" + id.getKey();
621 aa.annotations = annotations;
623 aa.belowAlignment = false;
624 aa.setScore(header.getScoreFor(id.getKey()));
625 aa.createSequenceMapping(s, s.getStart(), true);
626 s.addAlignmentAnnotation(aa);
627 aa.adjustForAlignment();
631 aa.graph = AlignmentAnnotation.NO_GRAPH;
632 aa.label = "T-COFFEE";
633 aa.description = "TCoffee column reliability score";
634 aa.annotations = annotations;
635 aa.belowAlignment = true;
637 aa.setScore(header.getScoreAvg());
639 aa.showAllColLabels = true;
640 aa.validateRangeAndDisplay();
648 public String print()
650 // TODO Auto-generated method stub