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.SimilarityParamsI;
25 import jalview.api.analysis.SimilarityScoreModelI;
26 import jalview.datamodel.AlignmentView;
27 import jalview.math.Matrix;
28 import jalview.math.MatrixI;
30 import java.util.Arrays;
32 public class ScoreMatrix implements SimilarityScoreModelI,
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
41 private static boolean scoreGapAsAny = false;
43 public static final short UNMAPPED = (short) -1;
45 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
47 private static final int MAX_ASCII = 127;
50 * the name of the model as shown in menus
55 * the characters that the model provides scores for
57 private char[] symbols;
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]
63 private float[][] matrix;
66 * quick lookup to convert from an ascii character value to the index
67 * of the corresponding symbol in the score matrix
69 private short[] symbolIndex;
72 * true for Protein Score matrix, false for dna score matrix
74 private boolean peptide;
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.
82 * Unique, human readable name for the matrix
84 * the symbols to which scores apply
86 * Pairwise scores indexed according to the symbol alphabet
88 public ScoreMatrix(String name, char[] alphabet, float[][] matrix)
90 if (alphabet.length != matrix.length)
92 throw new IllegalArgumentException(
93 "score matrix size must match alphabet size");
95 for (float[] row : matrix)
97 if (row.length != alphabet.length)
99 throw new IllegalArgumentException(
100 "score matrix size must be square");
104 this.matrix = matrix;
106 this.symbols = alphabet;
108 symbolIndex = buildSymbolIndex(alphabet);
111 * crude heuristic for now...
113 peptide = alphabet.length >= 20;
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.
121 * Unmapped characters (not in the alphabet) get an index of -1.
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).
130 static short[] buildSymbolIndex(char[] alphabet)
132 short[] index = new short[MAX_ASCII + 1];
133 Arrays.fill(index, UNMAPPED);
135 for (char c : alphabet)
143 * also map lower-case character (unless separately mapped)
145 if (c >= 'A' && c <= 'Z')
147 short lowerCase = (short) (c + ('a' - 'A'));
148 if (index[lowerCase] == UNMAPPED)
150 index[lowerCase] = pos;
159 public String getName()
165 public boolean isDNA()
171 public boolean isProtein()
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).
183 * @see #getMatrixIndex(char)
185 public float[][] getMatrix()
187 float[][] v = new float[matrix.length][matrix.length];
188 for (int i = 0; i < matrix.length; i++)
190 v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
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.
204 public int getMatrixIndex(char c)
206 if (c < symbolIndex.length)
208 return symbolIndex[c];
217 * Returns the pairwise score for substituting c with d, or zero if c or d is
218 * an unscored or unexpected character
221 public float getPairwiseScore(char c, char d)
223 if (c >= symbolIndex.length)
225 System.err.println(String.format(BAD_ASCII_ERROR, c));
228 if (d >= symbolIndex.length)
230 System.err.println(String.format(BAD_ASCII_ERROR, d));
234 int cIndex = symbolIndex[c];
235 int dIndex = symbolIndex[d];
236 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
238 return matrix[cIndex][dIndex];
244 * pretty print the matrix
247 public String toString()
249 return outputMatrix(false);
253 * Print the score matrix, optionally formatted as html, with the alphabet
254 * symbols as column headings and at the start of each row.
256 * The non-html format should give an output which can be parsed as a score
262 public String outputMatrix(boolean html)
264 StringBuilder sb = new StringBuilder(512);
267 * heading row with alphabet
271 sb.append("<table border=\"1\">");
272 sb.append(html ? "<tr><th></th>" : "");
276 sb.append("ScoreMatrix ").append(getName()).append("\n");
277 sb.append(symbols).append("\n");
279 for (char sym : symbols)
283 sb.append("<th> ").append(sym).append(" </th>");
287 sb.append("\t").append(sym);
290 sb.append(html ? "</tr>\n" : "\n");
295 for (char c1 : symbols)
299 sb.append("<tr><td>");
301 sb.append(c1).append(html ? "</td>" : "");
302 for (char c2 : symbols)
304 sb.append(html ? "<td>" : "\t")
305 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
306 .append(html ? "</td>" : "");
308 sb.append(html ? "</tr>\n" : "\n");
312 sb.append("</table>");
314 return sb.toString();
318 * Answers the number of symbols coded for (also equal to the number of rows
319 * and columns of the score matrix)
325 return symbols.length;
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
333 * <li>Sequences:</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
349 public MatrixI findSimilarities(AlignmentView seqstrings,
350 SimilarityParamsI options)
352 char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X') : ' ';
353 String[] seqs = seqstrings.getSequenceStrings(gapChar);
354 return findSimilarities(seqs, options);
361 protected MatrixI findSimilarities(String[] seqs,
362 SimilarityParamsI options)
364 // todo use options in calculation
365 double[][] values = new double[seqs.length][];
366 for (int row = 0; row < seqs.length; row++)
368 values[row] = new double[seqs.length];
369 for (int col = 0; col < seqs.length; col++)
372 int width = Math.min(seqs[row].length(), seqs[col].length());
373 for (int i = 0; i < width; i++)
375 char c1 = seqs[row].charAt(i);
376 char c2 = seqs[col].charAt(i);
377 float score = getPairwiseScore(c1, c2);
380 values[row][col] = total;
383 return new Matrix(values);
387 * Answers a hashcode computed from the symbol alphabet and the matrix score
391 public int hashCode()
393 int hs = Arrays.hashCode(symbols);
394 for (float[] row : matrix)
396 hs = hs * 31 + Arrays.hashCode(row);
402 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
403 * and score values, else false
406 public boolean equals(Object obj)
408 if (!(obj instanceof ScoreMatrix))
412 ScoreMatrix sm = (ScoreMatrix) obj;
413 if (Arrays.equals(symbols, sm.symbols)
414 && Arrays.deepEquals(matrix, sm.matrix))
422 * Returns the alphabet the matrix scores for, as a string of characters
426 public String getSymbols()
428 return new String(symbols);