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