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