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.math.Matrix;
24 import jalview.math.MatrixI;
26 import java.util.Arrays;
28 public class ScoreMatrix implements PairwiseScoreModelI
30 public static final short UNMAPPED = (short) -1;
32 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
34 private static final int MAX_ASCII = 127;
37 * the name of the model as shown in menus
42 * the characters that the model provides scores for
44 private char[] symbols;
47 * the score matrix; both dimensions must equal the number of symbols
48 * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j]
50 private float[][] matrix;
53 * quick lookup to convert from an ascii character value to the index
54 * of the corresponding symbol in the score matrix
56 private short[] symbolIndex;
59 * true for Protein Score matrix, false for dna score matrix
61 private boolean peptide;
64 * Constructor given a name, symbol alphabet, and matrix of scores for pairs
65 * of symbols. The matrix should be square and of the same size as the
66 * alphabet, for example 20x20 for a 20 symbol alphabet.
69 * Unique, human readable name for the matrix
71 * the symbols to which scores apply
73 * Pairwise scores indexed according to the symbol alphabet
75 public ScoreMatrix(String name, char[] alphabet, float[][] matrix)
77 if (alphabet.length != matrix.length)
79 throw new IllegalArgumentException(
80 "score matrix size must match alphabet size");
82 for (float[] row : matrix)
84 if (row.length != alphabet.length)
86 throw new IllegalArgumentException(
87 "score matrix size must be square");
93 this.symbols = alphabet;
95 symbolIndex = buildSymbolIndex(alphabet);
98 * crude heuristic for now...
100 peptide = alphabet.length >= 20;
104 * Returns an array A where A[i] is the position in the alphabet array of the
105 * character whose value is i. For example if the alphabet is { 'A', 'D', 'X'
106 * } then A['D'] = A[68] = 1.
108 * Unmapped characters (not in the alphabet) get an index of -1.
110 * Mappings are added automatically for lower case symbols (for non case
111 * sensitive scoring), unless they are explicitly present in the alphabet (are
112 * scored separately in the score matrix).
117 static short[] buildSymbolIndex(char[] alphabet)
119 short[] index = new short[MAX_ASCII + 1];
120 Arrays.fill(index, UNMAPPED);
122 for (char c : alphabet)
130 * also map lower-case character (unless separately mapped)
132 if (c >= 'A' && c <= 'Z')
134 short lowerCase = (short) (c + ('a' - 'A'));
135 if (index[lowerCase] == UNMAPPED)
137 index[lowerCase] = pos;
146 public String getName()
152 public boolean isDNA()
158 public boolean isProtein()
164 * Returns the score matrix as used in getPairwiseScore. If using this matrix
165 * directly, callers <em>must</em> also call <code>getMatrixIndex</code> in
166 * order to get the matrix index for each character (symbol).
169 * @see #getMatrixIndex(char)
171 public float[][] getMatrix()
177 * Answers the matrix index for a given character, or -1 if unmapped in the
178 * matrix. Use this method only if using <code>getMatrix</code> in order to
179 * compute scores directly (without symbol lookup) for efficiency.
185 public int getMatrixIndex(char c)
187 if (c < symbolIndex.length)
189 return symbolIndex[c];
198 * Returns the pairwise score for substituting c with d, or zero if c or d is
199 * an unscored or unexpected character
202 public float getPairwiseScore(char c, char d)
204 if (c >= symbolIndex.length)
206 System.err.println(String.format(BAD_ASCII_ERROR, c));
209 if (d >= symbolIndex.length)
211 System.err.println(String.format(BAD_ASCII_ERROR, d));
215 int cIndex = symbolIndex[c];
216 int dIndex = symbolIndex[d];
217 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
219 return matrix[cIndex][dIndex];
225 * pretty print the matrix
228 public String toString()
230 return outputMatrix(false);
234 * Print the score matrix, optionally formatted as html, with the alphabet
235 * symbols as column headings and at the start of each row.
237 * The non-html format should give an output which can be parsed as a score
243 public String outputMatrix(boolean html)
245 StringBuilder sb = new StringBuilder(512);
248 * heading row with alphabet
252 sb.append("<table border=\"1\">");
253 sb.append(html ? "<tr><th></th>" : "");
257 sb.append("ScoreMatrix ").append(getName()).append("\n");
258 sb.append(symbols).append("\n");
260 for (char sym : symbols)
264 sb.append("<th> ").append(sym).append(" </th>");
268 sb.append("\t").append(sym);
271 sb.append(html ? "</tr>\n" : "\n");
276 for (char c1 : symbols)
280 sb.append("<tr><td>");
282 sb.append(c1).append(html ? "</td>" : "");
283 for (char c2 : symbols)
285 sb.append(html ? "<td>" : "\t")
286 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
287 .append(html ? "</td>" : "");
289 sb.append(html ? "</tr>\n" : "\n");
293 sb.append("</table>");
295 return sb.toString();
299 * Answers the number of symbols coded for (also equal to the number of rows
300 * and columns of the score matrix)
306 return symbols.length;
310 * Computes an NxN matrix where N is the number of sequences, and entry [i, j]
311 * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores
312 * computed using the current score matrix. For example
314 * <li>Sequences:</li>
319 * <li>Score matrix is BLOSUM62</li>
320 * <li>Gaps treated same as X (unknown)</li>
321 * <li>product [0, 0] = F.F + K.K + L.L = 6 + 5 + 4 = 15</li>
322 * <li>product [1, 1] = R.R + -.- + D.D = 5 + -1 + 6 = 10</li>
323 * <li>product [2, 2] = Q.Q + I.I + A.A = 5 + 4 + 4 = 13</li>
324 * <li>product [3, 3] = G.G + W.W + C.C = 6 + 11 + 9 = 26</li>
325 * <li>product[0, 1] = F.R + K.- + L.D = -3 + -1 + -3 = -8
329 public MatrixI computePairwiseScores(String[] seqs)
331 double[][] values = new double[seqs.length][];
332 for (int row = 0; row < seqs.length; row++)
334 values[row] = new double[seqs.length];
335 for (int col = 0; col < seqs.length; col++)
338 int width = Math.min(seqs[row].length(), seqs[col].length());
339 for (int i = 0; i < width; i++)
341 char c1 = seqs[row].charAt(i);
342 char c2 = seqs[col].charAt(i);
343 float score = getPairwiseScore(c1, c2);
346 values[row][col] = total;
349 return new Matrix(values);
353 * Answers a hashcode computed from the symbol alphabet and the matrix score
357 public int hashCode()
359 int hs = Arrays.hashCode(symbols);
360 for (float[] row : matrix)
362 hs = hs * 31 + Arrays.hashCode(row);
368 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
369 * and score values, else false
372 public boolean equals(Object obj)
374 if (!(obj instanceof ScoreMatrix))
378 ScoreMatrix sm = (ScoreMatrix) obj;
379 if (Arrays.equals(symbols, sm.symbols)
380 && Arrays.deepEquals(matrix, sm.matrix))