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;
29 import jalview.util.Comparison;
31 import java.util.Arrays;
33 public class ScoreMatrix implements SimilarityScoreModelI,
37 * Jalview 2.10.1 treated gaps as X (peptide) or N (nucleotide)
38 * for pairwise scoring; 2.10.2 uses gap score (last column) in
39 * score matrix (JAL-2397)
40 * Set this flag to true (via Groovy) for 2.10.1 behaviour
42 private static boolean scoreGapAsAny = false;
44 public static final short UNMAPPED = (short) -1;
46 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
48 private static final int MAX_ASCII = 127;
51 * the name of the model as shown in menus
56 * the characters that the model provides scores for
58 private char[] symbols;
61 * the score matrix; both dimensions must equal the number of symbols
62 * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j]
64 private float[][] matrix;
67 * quick lookup to convert from an ascii character value to the index
68 * of the corresponding symbol in the score matrix
70 private short[] symbolIndex;
73 * true for Protein Score matrix, false for dna score matrix
75 private boolean peptide;
78 * Constructor given a name, symbol alphabet, and matrix of scores for pairs
79 * of symbols. The matrix should be square and of the same size as the
80 * alphabet, for example 20x20 for a 20 symbol alphabet.
83 * Unique, human readable name for the matrix
85 * the symbols to which scores apply
87 * Pairwise scores indexed according to the symbol alphabet
89 public ScoreMatrix(String theName, char[] alphabet, float[][] values)
91 if (alphabet.length != values.length)
93 throw new IllegalArgumentException(
94 "score matrix size must match alphabet size");
96 for (float[] row : values)
98 if (row.length != alphabet.length)
100 throw new IllegalArgumentException(
101 "score matrix size must be square");
105 this.matrix = values;
107 this.symbols = alphabet;
109 symbolIndex = buildSymbolIndex(alphabet);
112 * crude heuristic for now...
114 peptide = alphabet.length >= 20;
118 * Returns an array A where A[i] is the position in the alphabet array of the
119 * character whose value is i. For example if the alphabet is { 'A', 'D', 'X'
120 * } then A['D'] = A[68] = 1.
122 * Unmapped characters (not in the alphabet) get an index of -1.
124 * Mappings are added automatically for lower case symbols (for non case
125 * sensitive scoring), unless they are explicitly present in the alphabet (are
126 * scored separately in the score matrix).
131 static short[] buildSymbolIndex(char[] alphabet)
133 short[] index = new short[MAX_ASCII + 1];
134 Arrays.fill(index, UNMAPPED);
136 for (char c : alphabet)
144 * also map lower-case character (unless separately mapped)
146 if (c >= 'A' && c <= 'Z')
148 short lowerCase = (short) (c + ('a' - 'A'));
149 if (index[lowerCase] == UNMAPPED)
151 index[lowerCase] = pos;
160 public String getName()
166 public boolean isDNA()
172 public boolean isProtein()
178 * Returns a copy of the score matrix as used in getPairwiseScore. If using
179 * this matrix directly, callers <em>must</em> also call
180 * <code>getMatrixIndex</code> in order to get the matrix index for each
181 * character (symbol).
184 * @see #getMatrixIndex(char)
186 public float[][] getMatrix()
188 float[][] v = new float[matrix.length][matrix.length];
189 for (int i = 0; i < matrix.length; i++)
191 v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
197 * Answers the matrix index for a given character, or -1 if unmapped in the
198 * matrix. Use this method only if using <code>getMatrix</code> in order to
199 * compute scores directly (without symbol lookup) for efficiency.
205 public int getMatrixIndex(char c)
207 if (c < symbolIndex.length)
209 return symbolIndex[c];
218 * Returns the pairwise score for substituting c with d, or zero if c or d is
219 * an unscored or unexpected character
222 public float getPairwiseScore(char c, char d)
224 if (c >= symbolIndex.length)
226 System.err.println(String.format(BAD_ASCII_ERROR, c));
229 if (d >= symbolIndex.length)
231 System.err.println(String.format(BAD_ASCII_ERROR, d));
235 int cIndex = symbolIndex[c];
236 int dIndex = symbolIndex[d];
237 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
239 return matrix[cIndex][dIndex];
245 * pretty print the matrix
248 public String toString()
250 return outputMatrix(false);
254 * Print the score matrix, optionally formatted as html, with the alphabet
255 * symbols as column headings and at the start of each row.
257 * The non-html format should give an output which can be parsed as a score
263 public String outputMatrix(boolean html)
265 StringBuilder sb = new StringBuilder(512);
268 * heading row with alphabet
272 sb.append("<table border=\"1\">");
273 sb.append(html ? "<tr><th></th>" : "");
277 sb.append("ScoreMatrix ").append(getName()).append("\n");
278 sb.append(symbols).append("\n");
280 for (char sym : symbols)
284 sb.append("<th> ").append(sym).append(" </th>");
288 sb.append("\t").append(sym);
291 sb.append(html ? "</tr>\n" : "\n");
296 for (char c1 : symbols)
300 sb.append("<tr><td>");
302 sb.append(c1).append(html ? "</td>" : "");
303 for (char c2 : symbols)
305 sb.append(html ? "<td>" : "\t")
306 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
307 .append(html ? "</td>" : "");
309 sb.append(html ? "</tr>\n" : "\n");
313 sb.append("</table>");
315 return sb.toString();
319 * Answers the number of symbols coded for (also equal to the number of rows
320 * and columns of the score matrix)
326 return symbols.length;
330 * Computes an NxN matrix where N is the number of sequences, and entry [i, j]
331 * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores
332 * computed using the current score matrix. For example
334 * <li>Sequences:</li>
339 * <li>Score matrix is BLOSUM62</li>
340 * <li>Gaps treated same as X (unknown)</li>
341 * <li>product [0, 0] = F.F + K.K + L.L = 6 + 5 + 4 = 15</li>
342 * <li>product [1, 1] = R.R + -.- + D.D = 5 + -1 + 6 = 10</li>
343 * <li>product [2, 2] = Q.Q + I.I + A.A = 5 + 4 + 4 = 13</li>
344 * <li>product [3, 3] = G.G + W.W + C.C = 6 + 11 + 9 = 26</li>
345 * <li>product[0, 1] = F.R + K.- + L.D = -3 + -1 + -3 = -8
350 public MatrixI findSimilarities(AlignmentView seqstrings,
351 SimilarityParamsI options)
353 char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X') : ' ';
354 String[] seqs = seqstrings.getSequenceStrings(gapChar);
355 return findSimilarities(seqs, options);
359 * Computes pairwise similarities of a set of sequences using the given
366 protected MatrixI findSimilarities(String[] seqs, SimilarityParamsI params)
368 double[][] values = new double[seqs.length][];
369 for (int row = 0; row < seqs.length; row++)
371 values[row] = new double[seqs.length];
372 for (int col = 0; col < seqs.length; col++)
374 double total = computeSimilarity(seqs[row], seqs[col], params);
375 values[row][col] = total;
378 return new Matrix(values);
382 * Calculates the pairwise similarity of two strings using the given
383 * calculation parameters
390 protected double computeSimilarity(String seq1, String seq2,
391 SimilarityParamsI params)
393 int len1 = seq1.length();
394 int len2 = seq2.length();
397 int width = Math.max(len1, len2);
398 for (int i = 0; i < width; i++)
400 if (i >= len1 || i >= len2)
403 * off the end of one sequence; stop if we are only matching
404 * on the shorter sequence length, else treat as trailing gap
406 if (params.denominateByShortestLength())
411 // Change GAP_SPACE to GAP_DASH if we adopt - for gap in matrices
412 char c1 = i >= len1 ? Comparison.GAP_SPACE : seq1.charAt(i);
413 char c2 = i >= len2 ? Comparison.GAP_SPACE : seq2.charAt(i);
414 boolean gap1 = Comparison.isGap(c1);
415 boolean gap2 = Comparison.isGap(c2);
420 * gap-gap: include if options say so, else ignore
422 if (!params.includeGappedColumns())
427 else if (gap1 || gap2)
430 * gap-residue: score if options say so
432 if (!params.includeGaps())
437 float score = getPairwiseScore(c1, c2);
444 * Answers a hashcode computed from the symbol alphabet and the matrix score
448 public int hashCode()
450 int hs = Arrays.hashCode(symbols);
451 for (float[] row : matrix)
453 hs = hs * 31 + Arrays.hashCode(row);
459 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
460 * and score values, else false
463 public boolean equals(Object obj)
465 if (!(obj instanceof ScoreMatrix))
469 ScoreMatrix sm = (ScoreMatrix) obj;
470 if (Arrays.equals(symbols, sm.symbols)
471 && Arrays.deepEquals(matrix, sm.matrix))
479 * Returns the alphabet the matrix scores for, as a string of characters
483 public String getSymbols()
485 return new String(symbols);