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