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