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