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