648954f366affa781cb5d9d87945d9195d00a23d
[jalview.git] / src / jalview / io / TCoffeeScoreFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.io;
22
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
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;
35 import java.util.Map;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 /**
40  * A file parser for T-Coffee score ascii format. This file contains the
41  * alignment consensus for each residue in any sequence.
42  * <p>
43  * This file is produced by <code>t_coffee</code> providing the option
44  * <code>-output=score_ascii </code> to the program command line
45  * 
46  * An example file is the following
47  * 
48  * <pre>
49  * T-COFFEE, Version_9.02.r1228 (2012-02-16 18:15:12 - Revision 1228 - Build 336)
50  * Cedric Notredame 
51  * CPU TIME:0 sec.
52  * SCORE=90
53  * *
54  *  BAD AVG GOOD
55  * *
56  * 1PHT   :  89
57  * 1BB9   :  90
58  * 1UHC   :  94
59  * 1YCS   :  94
60  * 1OOT   :  93
61  * 1ABO   :  94
62  * 1FYN   :  94
63  * 1QCF   :  94
64  * cons   :  90
65  * 
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
75  * 
76  * 
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
86  * </pre>
87  * 
88  * 
89  * @author Paolo Di Tommaso
90  * 
91  */
92 public class TCoffeeScoreFile extends AlignFile
93 {
94
95   /**
96    * TCOFFEE score colourscheme
97    */
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
108   };
109
110   public final static String TCOFFEE_SCORE = "TCoffeeScore";
111
112   static Pattern SCORES_WITH_RESIDUE_NUMS = Pattern
113           .compile("^\\d+\\s([^\\s]+)\\s+\\d+$");
114
115   /** The {@link Header} structure holder */
116   Header header;
117
118   /**
119    * Holds the consensues values for each sequences. It uses a LinkedHashMap to
120    * maintaint the insertion order.
121    */
122   LinkedHashMap<String, StringBuilder> scores;
123
124   Integer fWidth;
125
126   public TCoffeeScoreFile(String inFile, DataSourceType fileSourceType)
127           throws IOException
128   {
129     super(inFile, fileSourceType);
130
131   }
132
133   public TCoffeeScoreFile(FileParse source) throws IOException
134   {
135     super(source);
136   }
137
138   /**
139    * Parse the provided reader for the T-Coffee scores file format
140    * 
141    * @param reader
142    *          public static TCoffeeScoreFile load(Reader reader) {
143    * 
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); } }
150    */
151
152   /**
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
155    */
156   public int getHeight()
157   {
158     // the last entry will always be the 'global' alingment consensus scores, so
159     // it is removed
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;
163   }
164
165   /**
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.
169    */
170   public int getWidth()
171   {
172     return fWidth != null ? fWidth : 0;
173   }
174
175   /**
176    * Get the string of score values for the specified seqeunce ID.
177    * 
178    * @param id
179    *          The sequence 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.
182    */
183   public String getScoresFor(String id)
184   {
185     return scores != null && scores.containsKey(id) ? scores.get(id)
186             .toString() : "";
187   }
188
189   /**
190    * @return The list of score string as a {@link List} object, in the same
191    *         ordeer of the insertion i.e. in the MSA
192    */
193   public List<String> getScoresList()
194   {
195     if (scores == null)
196     {
197       return null;
198     }
199     List<String> result = new ArrayList<String>(scores.size());
200     for (Map.Entry<String, StringBuilder> it : scores.entrySet())
201     {
202       result.add(it.getValue().toString());
203     }
204
205     return result;
206   }
207
208   /**
209    * @return The parsed score values a matrix of bytes
210    */
211   public byte[][] getScoresArray()
212   {
213     if (scores == null)
214     {
215       return null;
216     }
217     byte[][] result = new byte[scores.size()][];
218
219     int rowCount = 0;
220     for (Map.Entry<String, StringBuilder> it : scores.entrySet())
221     {
222       String line = it.getValue().toString();
223       byte[] seqValues = new byte[line.length()];
224       for (int j = 0, c = line.length(); j < c; j++)
225       {
226
227         byte val = (byte) (line.charAt(j) - '0');
228
229         seqValues[j] = (val >= 0 && val <= 9) ? val : -1;
230       }
231
232       result[rowCount++] = seqValues;
233     }
234
235     return result;
236   }
237
238   @Override
239   public void parse() throws IOException
240   {
241     /*
242      * read the header
243      */
244     header = readHeader(this);
245
246     if (header == null)
247     {
248       error = true;
249       return;
250     }
251     scores = new LinkedHashMap<String, StringBuilder>();
252
253     /*
254      * initilize the structure
255      */
256     for (Map.Entry<String, Integer> entry : header.scores.entrySet())
257     {
258       scores.put(entry.getKey(), new StringBuilder());
259     }
260
261     /*
262      * go with the reading
263      */
264     Block block;
265     while ((block = readBlock(this, header.scores.size())) != null)
266     {
267
268       /*
269        * append sequences read in the block
270        */
271       for (Map.Entry<String, String> entry : block.items.entrySet())
272       {
273         StringBuilder scoreStringBuilder = scores.get(entry.getKey());
274         if (scoreStringBuilder == null)
275         {
276           error = true;
277           errormessage = String
278                   .format("Invalid T-Coffee score file: Sequence ID '%s' is not declared in header section",
279                           entry.getKey());
280           return;
281         }
282
283         scoreStringBuilder.append(entry.getValue());
284       }
285     }
286
287     /*
288      * verify that all rows have the same width
289      */
290     for (StringBuilder str : scores.values())
291     {
292       if (fWidth == null)
293       {
294         fWidth = str.length();
295       }
296       else if (fWidth != str.length())
297       {
298         error = true;
299         errormessage = "Invalid T-Coffee score file: All the score sequences must have the same length";
300         return;
301       }
302     }
303
304     return;
305   }
306
307   static int parseInt(String str)
308   {
309     try
310     {
311       return Integer.parseInt(str);
312     } catch (NumberFormatException e)
313     {
314       // TODO report a warning ?
315       return 0;
316     }
317   }
318
319   /**
320    * Reaad the header section in the T-Coffee score file format
321    * 
322    * @param reader
323    *          The scores reader
324    * @return The parser {@link Header} instance
325    * @throws RuntimeException
326    *           when the header is not in the expected format
327    */
328   static Header readHeader(FileParse reader) throws IOException
329   {
330
331     Header result = null;
332     try
333     {
334       result = new Header();
335       result.head = reader.nextLine();
336
337       String line;
338
339       while ((line = reader.nextLine()) != null)
340       {
341         if (line.startsWith("SCORE="))
342         {
343           result.score = parseInt(line.substring(6).trim());
344           break;
345         }
346       }
347
348       if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
349       {
350         error(reader,
351                 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
352         return null;
353       }
354       if ((line = reader.nextLine()) == null
355               || !"BAD AVG GOOD".equals(line.trim()))
356       {
357         error(reader,
358                 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
359         return null;
360       }
361       if ((line = reader.nextLine()) == null || !"*".equals(line.trim()))
362       {
363         error(reader,
364                 "Invalid T-COFFEE score format (NO BAD/AVG/GOOD header)");
365         return null;
366       }
367
368       /*
369        * now are expected a list if sequences ID up to the first blank line
370        */
371       while ((line = reader.nextLine()) != null)
372       {
373         if ("".equals(line))
374         {
375           break;
376         }
377
378         int p = line.indexOf(":");
379         if (p == -1)
380         {
381           // TODO report a warning
382           continue;
383         }
384
385         String id = line.substring(0, p).trim();
386         int val = parseInt(line.substring(p + 1).trim());
387         if ("".equals(id))
388         {
389           // TODO report warning
390           continue;
391         }
392
393         result.scores.put(id, val);
394       }
395
396       if (result == null)
397       {
398         error(reader, "T-COFFEE score file had no per-sequence scores");
399       }
400
401     } catch (IOException e)
402     {
403       error(reader, "Unexpected problem parsing T-Coffee score ascii file");
404       throw e;
405     }
406
407     return result;
408   }
409
410   private static void error(FileParse reader, String errm)
411   {
412     reader.error = true;
413     if (reader.errormessage == null)
414     {
415       reader.errormessage = errm;
416     }
417     else
418     {
419       reader.errormessage += "\n" + errm;
420     }
421   }
422
423   /**
424    * Read a scores block ihe provided stream.
425    * 
426    * @param reader
427    *          The stream to parse
428    * @param size
429    *          The expected number of the sequence to be read
430    * @return The {@link Block} instance read or {link null} null if the end of
431    *         file has reached.
432    * @throws IOException
433    *           Something went wrong on the 'wire'
434    */
435   static Block readBlock(FileParse reader, int size) throws IOException
436   {
437     Block result = new Block(size);
438     String line;
439
440     /*
441      * read blank lines (eventually)
442      */
443     while ((line = reader.nextLine()) != null && "".equals(line.trim()))
444     {
445       // consume blank lines
446     }
447
448     if (line == null)
449     {
450       return null;
451     }
452
453     /*
454      * read the scores block
455      */
456     do
457     {
458       if ("".equals(line.trim()))
459       {
460         // terminated
461         break;
462       }
463
464       // split the line on the first blank
465       // the first part have to contain the sequence id
466       // the remaining part are the scores values
467       int p = line.indexOf(" ");
468       if (p == -1)
469       {
470         if (reader.warningMessage == null)
471         {
472           reader.warningMessage = "";
473         }
474         reader.warningMessage += "Possible parsing error - expected to find a space in line: '"
475                 + line + "'\n";
476         continue;
477       }
478
479       String id = line.substring(0, p).trim();
480       String val = line.substring(p + 1).trim();
481
482       Matcher m = SCORES_WITH_RESIDUE_NUMS.matcher(val);
483       if (m.matches())
484       {
485         val = m.group(1);
486       }
487
488       result.items.put(id, val);
489
490     } while ((line = reader.nextLine()) != null);
491
492     return result;
493   }
494
495   /*
496    * The score file header
497    */
498   static class Header
499   {
500     String head;
501
502     int score;
503
504     LinkedHashMap<String, Integer> scores = new LinkedHashMap<String, Integer>();
505
506     public int getScoreAvg()
507     {
508       return score;
509     }
510
511     public int getScoreFor(String ID)
512     {
513
514       return scores.containsKey(ID) ? scores.get(ID) : -1;
515
516     }
517   }
518
519   /*
520    * Hold a single block values block in the score file
521    */
522   static class Block
523   {
524     int size;
525
526     Map<String, String> items;
527
528     public Block(int size)
529     {
530       this.size = size;
531       this.items = new HashMap<String, String>(size);
532     }
533
534     String getScoresFor(String id)
535     {
536       return items.get(id);
537     }
538
539     String getConsensus()
540     {
541       return items.get("cons");
542     }
543   }
544
545   /**
546    * generate annotation for this TCoffee score set on the given alignment
547    * 
548    * @param al
549    *          alignment to annotate
550    * @param matchids
551    *          if true, annotate sequences based on matching sequence names
552    * @return true if alignment annotation was modified, false otherwise.
553    */
554   public boolean annotateAlignment(AlignmentI al, boolean matchids)
555   {
556     if (al.getHeight() != getHeight() || al.getWidth() != getWidth())
557     {
558       String info = String.format(
559               "align w: %s, h: %s; score: w: %s; h: %s ", al.getWidth(),
560               al.getHeight(), getWidth(), getHeight());
561       warningMessage = "Alignment shape does not match T-Coffee score file shape -- "
562               + info;
563       return false;
564     }
565     boolean added = false;
566     int i = 0;
567     SequenceIdMatcher sidmatcher = new SequenceIdMatcher(
568             al.getSequencesArray());
569     byte[][] scoreMatrix = getScoresArray();
570     // for 2.8 - we locate any existing TCoffee annotation and remove it first
571     // before adding this.
572     for (Map.Entry<String, StringBuilder> id : scores.entrySet())
573     {
574       byte[] srow = scoreMatrix[i];
575       SequenceI s;
576       if (matchids)
577       {
578         s = sidmatcher.findIdMatch(id.getKey());
579       }
580       else
581       {
582         s = al.getSequenceAt(i);
583       }
584       i++;
585       if (s == null && i != scores.size() && !id.getKey().equals("cons"))
586       {
587         System.err.println("No "
588                 + (matchids ? "match " : " sequences left ")
589                 + " for TCoffee score set : " + id.getKey());
590         continue;
591       }
592       int jSize = al.getWidth() < srow.length ? al.getWidth() : srow.length;
593       Annotation[] annotations = new Annotation[al.getWidth()];
594       for (int j = 0; j < jSize; j++)
595       {
596         byte val = srow[j];
597         if (s != null && jalview.util.Comparison.isGap(s.getCharAt(j)))
598         {
599           annotations[j] = null;
600           if (val > 0)
601           {
602             System.err
603                     .println("Warning: non-zero value for positional T-COFFEE score for gap at "
604                             + j + " in sequence " + s.getName());
605           }
606         }
607         else
608         {
609           annotations[j] = new Annotation(s == null ? "" + val : null,
610                   s == null ? "" + val : null, '\0', val * 1f, val >= 0
611                           && val < colors.length ? colors[val]
612                           : Color.white);
613         }
614       }
615       // this will overwrite any existing t-coffee scores for the alignment
616       AlignmentAnnotation aa = al.findOrCreateAnnotation(TCOFFEE_SCORE,
617               TCOFFEE_SCORE, false, s, null);
618       if (s != null)
619       {
620         aa.label = "T-COFFEE";
621         aa.description = "" + id.getKey();
622         aa.annotations = annotations;
623         aa.visible = false;
624         aa.belowAlignment = false;
625         aa.setScore(header.getScoreFor(id.getKey()));
626         aa.createSequenceMapping(s, s.getStart(), true);
627         s.addAlignmentAnnotation(aa);
628         aa.adjustForAlignment();
629       }
630       else
631       {
632         aa.graph = AlignmentAnnotation.NO_GRAPH;
633         aa.label = "T-COFFEE";
634         aa.description = "TCoffee column reliability score";
635         aa.annotations = annotations;
636         aa.belowAlignment = true;
637         aa.visible = true;
638         aa.setScore(header.getScoreAvg());
639       }
640       aa.showAllColLabels = true;
641       aa.validateRangeAndDisplay();
642       added = true;
643     }
644
645     return added;
646   }
647
648   @Override
649   public String print(SequenceI[] sqs, boolean jvsuffix)
650   {
651     // TODO Auto-generated method stub
652     return "Not valid.";
653   }
654 }