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