2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.analysis.scoremodels;
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;
29 import java.util.Arrays;
31 public class ScoreMatrix implements SimilarityScoreModelI,
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
40 private static boolean scoreGapAsAny = false;
42 public static final short UNMAPPED = (short) -1;
44 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
46 private static final int MAX_ASCII = 127;
49 * the name of the model as shown in menus
54 * the characters that the model provides scores for
56 private char[] symbols;
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]
62 private float[][] matrix;
65 * quick lookup to convert from an ascii character value to the index
66 * of the corresponding symbol in the score matrix
68 private short[] symbolIndex;
71 * true for Protein Score matrix, false for dna score matrix
73 private boolean peptide;
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.
81 * Unique, human readable name for the matrix
83 * the symbols to which scores apply
85 * Pairwise scores indexed according to the symbol alphabet
87 public ScoreMatrix(String name, char[] alphabet, float[][] matrix)
89 if (alphabet.length != matrix.length)
91 throw new IllegalArgumentException(
92 "score matrix size must match alphabet size");
94 for (float[] row : matrix)
96 if (row.length != alphabet.length)
98 throw new IllegalArgumentException(
99 "score matrix size must be square");
103 this.matrix = matrix;
105 this.symbols = alphabet;
107 symbolIndex = buildSymbolIndex(alphabet);
110 * crude heuristic for now...
112 peptide = alphabet.length >= 20;
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.
120 * Unmapped characters (not in the alphabet) get an index of -1.
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).
129 static short[] buildSymbolIndex(char[] alphabet)
131 short[] index = new short[MAX_ASCII + 1];
132 Arrays.fill(index, UNMAPPED);
134 for (char c : alphabet)
142 * also map lower-case character (unless separately mapped)
144 if (c >= 'A' && c <= 'Z')
146 short lowerCase = (short) (c + ('a' - 'A'));
147 if (index[lowerCase] == UNMAPPED)
149 index[lowerCase] = pos;
158 public String getName()
164 public boolean isDNA()
170 public boolean isProtein()
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).
182 * @see #getMatrixIndex(char)
184 public float[][] getMatrix()
186 float[][] v = new float[matrix.length][matrix.length];
187 for (int i = 0; i < matrix.length; i++)
189 v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
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.
203 public int getMatrixIndex(char c)
205 if (c < symbolIndex.length)
207 return symbolIndex[c];
216 * Returns the pairwise score for substituting c with d, or zero if c or d is
217 * an unscored or unexpected character
220 public float getPairwiseScore(char c, char d)
222 if (c >= symbolIndex.length)
224 System.err.println(String.format(BAD_ASCII_ERROR, c));
227 if (d >= symbolIndex.length)
229 System.err.println(String.format(BAD_ASCII_ERROR, d));
233 int cIndex = symbolIndex[c];
234 int dIndex = symbolIndex[d];
235 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
237 return matrix[cIndex][dIndex];
243 * pretty print the matrix
246 public String toString()
248 return outputMatrix(false);
252 * Print the score matrix, optionally formatted as html, with the alphabet
253 * symbols as column headings and at the start of each row.
255 * The non-html format should give an output which can be parsed as a score
261 public String outputMatrix(boolean html)
263 StringBuilder sb = new StringBuilder(512);
266 * heading row with alphabet
270 sb.append("<table border=\"1\">");
271 sb.append(html ? "<tr><th></th>" : "");
275 sb.append("ScoreMatrix ").append(getName()).append("\n");
276 sb.append(symbols).append("\n");
278 for (char sym : symbols)
282 sb.append("<th> ").append(sym).append(" </th>");
286 sb.append("\t").append(sym);
289 sb.append(html ? "</tr>\n" : "\n");
294 for (char c1 : symbols)
298 sb.append("<tr><td>");
300 sb.append(c1).append(html ? "</td>" : "");
301 for (char c2 : symbols)
303 sb.append(html ? "<td>" : "\t")
304 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
305 .append(html ? "</td>" : "");
307 sb.append(html ? "</tr>\n" : "\n");
311 sb.append("</table>");
313 return sb.toString();
317 * Answers the number of symbols coded for (also equal to the number of rows
318 * and columns of the score matrix)
324 return symbols.length;
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
332 * <li>Sequences:</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
348 public MatrixI findSimilarities(AlignmentView seqstrings)
350 char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X') : ' ';
351 String[] seqs = seqstrings.getSequenceStrings(gapChar);
352 return findSimilarities(seqs);
359 protected MatrixI findSimilarities(String[] seqs)
361 double[][] values = new double[seqs.length][];
362 for (int row = 0; row < seqs.length; row++)
364 values[row] = new double[seqs.length];
365 for (int col = 0; col < seqs.length; col++)
368 int width = Math.min(seqs[row].length(), seqs[col].length());
369 for (int i = 0; i < width; i++)
371 char c1 = seqs[row].charAt(i);
372 char c2 = seqs[col].charAt(i);
373 float score = getPairwiseScore(c1, c2);
376 values[row][col] = total;
379 return new Matrix(values);
383 * Answers a hashcode computed from the symbol alphabet and the matrix score
387 public int hashCode()
389 int hs = Arrays.hashCode(symbols);
390 for (float[] row : matrix)
392 hs = hs * 31 + Arrays.hashCode(row);
398 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
399 * and score values, else false
402 public boolean equals(Object obj)
404 if (!(obj instanceof ScoreMatrix))
408 ScoreMatrix sm = (ScoreMatrix) obj;
409 if (Arrays.equals(symbols, sm.symbols)
410 && Arrays.deepEquals(matrix, sm.matrix))
418 * Returns the alphabet the matrix scores for, as a string of characters
422 public String getSymbols()
424 return new String(symbols);