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