JAL-2416 add score model description field for tooltip in PCA panel
[jalview.git] / src / jalview / analysis / scoremodels / ScoreMatrix.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.analysis.scoremodels;
22
23 import jalview.api.analysis.PairwiseScoreModelI;
24 import jalview.api.analysis.SimilarityParamsI;
25 import jalview.api.analysis.SimilarityScoreModelI;
26 import jalview.datamodel.AlignmentView;
27 import jalview.math.Matrix;
28 import jalview.math.MatrixI;
29 import jalview.util.Comparison;
30
31 import java.util.Arrays;
32
33 public class ScoreMatrix implements SimilarityScoreModelI,
34         PairwiseScoreModelI
35 {
36   private static final char GAP_CHARACTER = Comparison.GAP_DASH;
37
38   /*
39    * Jalview 2.10.1 treated gaps as X (peptide) or N (nucleotide)
40    * for pairwise scoring; 2.10.2 uses gap score (last column) in
41    * score matrix (JAL-2397)
42    * Set this flag to true (via Groovy) for 2.10.1 behaviour
43    */
44   private static boolean scoreGapAsAny = false;
45
46   public static final short UNMAPPED = (short) -1;
47
48   private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
49
50   private static final int MAX_ASCII = 127;
51
52   /*
53    * the name of the model as shown in menus
54    * each score model in use should have a unique name
55    */
56   private String name;
57
58   /*
59    * a description for the model as shown in tooltips
60    */
61   private String description;
62
63   /*
64    * the characters that the model provides scores for
65    */
66   private char[] symbols;
67
68   /*
69    * the score matrix; both dimensions must equal the number of symbols
70    * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j]
71    */
72   private float[][] matrix;
73
74   /*
75    * quick lookup to convert from an ascii character value to the index
76    * of the corresponding symbol in the score matrix 
77    */
78   private short[] symbolIndex;
79
80   /*
81    * true for Protein Score matrix, false for dna score matrix
82    */
83   private boolean peptide;
84
85   /**
86    * Constructor given a name, symbol alphabet, and matrix of scores for pairs
87    * of symbols. The matrix should be square and of the same size as the
88    * alphabet, for example 20x20 for a 20 symbol alphabet.
89    * 
90    * @param theName
91    *          Unique, human readable name for the matrix
92    * @param alphabet
93    *          the symbols to which scores apply
94    * @param values
95    *          Pairwise scores indexed according to the symbol alphabet
96    */
97   public ScoreMatrix(String theName, char[] alphabet, float[][] values)
98   {
99     if (alphabet.length != values.length)
100     {
101       throw new IllegalArgumentException(
102               "score matrix size must match alphabet size");
103     }
104     for (float[] row : values)
105     {
106       if (row.length != alphabet.length)
107       {
108         throw new IllegalArgumentException(
109                 "score matrix size must be square");
110       }
111     }
112
113     this.matrix = values;
114     this.name = theName;
115     this.symbols = alphabet;
116
117     symbolIndex = buildSymbolIndex(alphabet);
118
119     /*
120      * crude heuristic for now...
121      */
122     peptide = alphabet.length >= 20;
123   }
124
125   /**
126    * Returns an array A where A[i] is the position in the alphabet array of the
127    * character whose value is i. For example if the alphabet is { 'A', 'D', 'X'
128    * } then A['D'] = A[68] = 1.
129    * <p>
130    * Unmapped characters (not in the alphabet) get an index of -1.
131    * <p>
132    * Mappings are added automatically for lower case symbols (for non case
133    * sensitive scoring), unless they are explicitly present in the alphabet (are
134    * scored separately in the score matrix).
135    * 
136    * @param alphabet
137    * @return
138    */
139   static short[] buildSymbolIndex(char[] alphabet)
140   {
141     short[] index = new short[MAX_ASCII + 1];
142     Arrays.fill(index, UNMAPPED);
143     short pos = 0;
144     for (char c : alphabet)
145     {
146       if (c <= MAX_ASCII)
147       {
148         index[c] = pos;
149       }
150
151       /*
152        * also map lower-case character (unless separately mapped)
153        */
154       if (c >= 'A' && c <= 'Z')
155       {
156         short lowerCase = (short) (c + ('a' - 'A'));
157         if (index[lowerCase] == UNMAPPED)
158         {
159           index[lowerCase] = pos;
160         }
161       }
162       pos++;
163     }
164     return index;
165   }
166
167   @Override
168   public String getName()
169   {
170     return name;
171   }
172
173   @Override
174   public String getDescription()
175   {
176     return description;
177   }
178
179   @Override
180   public boolean isDNA()
181   {
182     return !peptide;
183   }
184
185   @Override
186   public boolean isProtein()
187   {
188     return peptide;
189   }
190
191   /**
192    * Returns a copy of the score matrix as used in getPairwiseScore. If using
193    * this matrix directly, callers <em>must</em> also call
194    * <code>getMatrixIndex</code> in order to get the matrix index for each
195    * character (symbol).
196    * 
197    * @return
198    * @see #getMatrixIndex(char)
199    */
200   public float[][] getMatrix()
201   {
202     float[][] v = new float[matrix.length][matrix.length];
203     for (int i = 0; i < matrix.length; i++)
204     {
205       v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
206     }
207     return v;
208   }
209
210   /**
211    * Answers the matrix index for a given character, or -1 if unmapped in the
212    * matrix. Use this method only if using <code>getMatrix</code> in order to
213    * compute scores directly (without symbol lookup) for efficiency.
214    * 
215    * @param c
216    * @return
217    * @see #getMatrix()
218    */
219   public int getMatrixIndex(char c)
220   {
221     if (c < symbolIndex.length)
222     {
223       return symbolIndex[c];
224     }
225     else
226     {
227       return UNMAPPED;
228     }
229   }
230
231   /**
232    * Returns the pairwise score for substituting c with d, or zero if c or d is
233    * an unscored or unexpected character
234    */
235   @Override
236   public float getPairwiseScore(char c, char d)
237   {
238     if (c >= symbolIndex.length)
239     {
240       System.err.println(String.format(BAD_ASCII_ERROR, c));
241       return 0;
242     }
243     if (d >= symbolIndex.length)
244     {
245       System.err.println(String.format(BAD_ASCII_ERROR, d));
246       return 0;
247     }
248
249     int cIndex = symbolIndex[c];
250     int dIndex = symbolIndex[d];
251     if (cIndex != UNMAPPED && dIndex != UNMAPPED)
252     {
253       return matrix[cIndex][dIndex];
254     }
255     return 0;
256   }
257
258   /**
259    * pretty print the matrix
260    */
261   @Override
262   public String toString()
263   {
264     return outputMatrix(false);
265   }
266
267   /**
268    * Print the score matrix, optionally formatted as html, with the alphabet
269    * symbols as column headings and at the start of each row.
270    * <p>
271    * The non-html format should give an output which can be parsed as a score
272    * matrix file
273    * 
274    * @param html
275    * @return
276    */
277   public String outputMatrix(boolean html)
278   {
279     StringBuilder sb = new StringBuilder(512);
280
281     /*
282      * heading row with alphabet
283      */
284     if (html)
285     {
286       sb.append("<table border=\"1\">");
287       sb.append(html ? "<tr><th></th>" : "");
288     }
289     else
290     {
291       sb.append("ScoreMatrix ").append(getName()).append("\n");
292       sb.append(symbols).append("\n");
293     }
294     for (char sym : symbols)
295     {
296       if (html)
297       {
298         sb.append("<th>&nbsp;").append(sym).append("&nbsp;</th>");
299       }
300       else
301       {
302         sb.append("\t").append(sym);
303       }
304     }
305     sb.append(html ? "</tr>\n" : "\n");
306
307     /*
308      * table of scores
309      */
310     for (char c1 : symbols)
311     {
312       if (html)
313       {
314         sb.append("<tr><td>");
315       }
316       sb.append(c1).append(html ? "</td>" : "");
317       for (char c2 : symbols)
318       {
319         sb.append(html ? "<td>" : "\t")
320                 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
321                 .append(html ? "</td>" : "");
322       }
323       sb.append(html ? "</tr>\n" : "\n");
324     }
325     if (html)
326     {
327       sb.append("</table>");
328     }
329     return sb.toString();
330   }
331
332   /**
333    * Answers the number of symbols coded for (also equal to the number of rows
334    * and columns of the score matrix)
335    * 
336    * @return
337    */
338   public int getSize()
339   {
340     return symbols.length;
341   }
342
343   /**
344    * Computes an NxN matrix where N is the number of sequences, and entry [i, j]
345    * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores
346    * computed using the current score matrix. For example
347    * <ul>
348    * <li>Sequences:</li>
349    * <li>FKL</li>
350    * <li>R-D</li>
351    * <li>QIA</li>
352    * <li>GWC</li>
353    * <li>Score matrix is BLOSUM62</li>
354    * <li>Gaps treated same as X (unknown)</li>
355    * <li>product [0, 0] = F.F + K.K + L.L = 6 + 5 + 4 = 15</li>
356    * <li>product [1, 1] = R.R + -.- + D.D = 5 + -1 + 6 = 10</li>
357    * <li>product [2, 2] = Q.Q + I.I + A.A = 5 + 4 + 4 = 13</li>
358    * <li>product [3, 3] = G.G + W.W + C.C = 6 + 11 + 9 = 26</li>
359    * <li>product[0, 1] = F.R + K.- + L.D = -3 + -1 + -3 = -8
360    * <li>and so on</li>
361    * </ul>
362    */
363   @Override
364   public MatrixI findSimilarities(AlignmentView seqstrings,
365           SimilarityParamsI options)
366   {
367     char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X')
368             : Comparison.GAP_DASH;
369     String[] seqs = seqstrings.getSequenceStrings(gapChar);
370     return findSimilarities(seqs, options);
371   }
372
373   /**
374    * Computes pairwise similarities of a set of sequences using the given
375    * parameters
376    * 
377    * @param seqs
378    * @param params
379    * @return
380    */
381   protected MatrixI findSimilarities(String[] seqs, SimilarityParamsI params)
382   {
383     double[][] values = new double[seqs.length][];
384     for (int row = 0; row < seqs.length; row++)
385     {
386       values[row] = new double[seqs.length];
387       for (int col = 0; col < seqs.length; col++)
388       {
389         double total = computeSimilarity(seqs[row], seqs[col], params);
390         values[row][col] = total;
391       }
392     }
393     return new Matrix(values);
394   }
395
396   /**
397    * Calculates the pairwise similarity of two strings using the given
398    * calculation parameters
399    * 
400    * @param seq1
401    * @param seq2
402    * @param params
403    * @return
404    */
405   protected double computeSimilarity(String seq1, String seq2,
406           SimilarityParamsI params)
407   {
408     int len1 = seq1.length();
409     int len2 = seq2.length();
410     double total = 0;
411
412     int width = Math.max(len1, len2);
413     for (int i = 0; i < width; i++)
414     {
415       if (i >= len1 || i >= len2)
416       {
417         /*
418          * off the end of one sequence; stop if we are only matching
419          * on the shorter sequence length, else treat as trailing gap
420          */
421         if (params.denominateByShortestLength())
422         {
423           break;
424         }
425       }
426
427       char c1 = i >= len1 ? GAP_CHARACTER : seq1.charAt(i);
428       char c2 = i >= len2 ? GAP_CHARACTER : seq2.charAt(i);
429       boolean gap1 = Comparison.isGap(c1);
430       boolean gap2 = Comparison.isGap(c2);
431
432       if (gap1 && gap2)
433       {
434         /*
435          * gap-gap: include if options say so, else ignore
436          */
437         if (!params.includeGappedColumns())
438         {
439           continue;
440         }
441       }
442       else if (gap1 || gap2)
443       {
444         /*
445          * gap-residue: score if options say so
446          */
447         if (!params.includeGaps())
448         {
449           continue;
450         }
451       }
452       float score = getPairwiseScore(c1, c2);
453       total += score;
454     }
455     return total;
456   }
457
458   /**
459    * Answers a hashcode computed from the symbol alphabet and the matrix score
460    * values
461    */
462   @Override
463   public int hashCode()
464   {
465     int hs = Arrays.hashCode(symbols);
466     for (float[] row : matrix)
467     {
468       hs = hs * 31 + Arrays.hashCode(row);
469     }
470     return hs;
471   }
472
473   /**
474    * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
475    * and score values, else false
476    */
477   @Override
478   public boolean equals(Object obj)
479   {
480     if (!(obj instanceof ScoreMatrix))
481     {
482       return false;
483     }
484     ScoreMatrix sm = (ScoreMatrix) obj;
485     if (Arrays.equals(symbols, sm.symbols)
486             && Arrays.deepEquals(matrix, sm.matrix))
487     {
488       return true;
489     }
490     return false;
491   }
492
493   /**
494    * Returns the alphabet the matrix scores for, as a string of characters
495    * 
496    * @return
497    */
498   public String getSymbols()
499   {
500     return new String(symbols);
501   }
502
503   public void setDescription(String desc)
504   {
505     description = desc;
506   }
507 }