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