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.datamodel.AlignmentView;
26 import jalview.math.Matrix;
27 import jalview.math.MatrixI;
28 import jalview.util.Comparison;
30 import java.util.Arrays;
33 * A class that models a substitution score matrix for any given alphabet of
34 * symbols. Instances of this class are immutable and thread-safe.
36 public class ScoreMatrix extends SimilarityScoreModel implements
39 private static final char GAP_CHARACTER = Comparison.GAP_DASH;
42 * an arbitrary score to assign for identity of an unknown symbol
43 * (this is the value on the diagonal in the * column of the NCBI matrix)
44 * (though a case could be made for using the minimum diagonal value)
46 private static final int UNKNOWN_IDENTITY_SCORE = 1;
49 * Jalview 2.10.1 treated gaps as X (peptide) or N (nucleotide)
50 * for pairwise scoring; 2.10.2 uses gap score (last column) in
51 * score matrix (JAL-2397)
52 * Set this flag to true (via Groovy) for 2.10.1 behaviour
54 private static boolean scoreGapAsAny = false;
56 public static final short UNMAPPED = (short) -1;
58 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
60 private static final int MAX_ASCII = 127;
63 * the name of the model as shown in menus
64 * each score model in use should have a unique name
69 * a description for the model as shown in tooltips
71 private String description;
74 * the characters that the model provides scores for
76 private char[] symbols;
79 * the score matrix; both dimensions must equal the number of symbols
80 * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j]
82 private float[][] matrix;
85 * quick lookup to convert from an ascii character value to the index
86 * of the corresponding symbol in the score matrix
88 private short[] symbolIndex;
91 * true for Protein Score matrix, false for dna score matrix
93 private boolean peptide;
95 private float minValue;
97 private float maxValue;
100 * Constructor given a name, symbol alphabet, and matrix of scores for pairs
101 * of symbols. The matrix should be square and of the same size as the
102 * alphabet, for example 20x20 for a 20 symbol alphabet.
105 * Unique, human readable name for the matrix
107 * the symbols to which scores apply
109 * Pairwise scores indexed according to the symbol alphabet
111 public ScoreMatrix(String theName, char[] alphabet, float[][] values)
113 this(theName, null, alphabet, values);
117 * Constructor given a name, description, symbol alphabet, and matrix of
118 * scores for pairs of symbols. The matrix should be square and of the same
119 * size as the alphabet, for example 20x20 for a 20 symbol alphabet.
122 * Unique, human readable name for the matrix
123 * @param theDescription
124 * descriptive display name suitable for use in menus
126 * the symbols to which scores apply
128 * Pairwise scores indexed according to the symbol alphabet
130 public ScoreMatrix(String theName, String theDescription,
131 char[] alphabet, float[][] values)
133 if (alphabet.length != values.length)
135 throw new IllegalArgumentException(
136 "score matrix size must match alphabet size");
138 for (float[] row : values)
140 if (row.length != alphabet.length)
142 throw new IllegalArgumentException(
143 "score matrix size must be square");
147 this.matrix = values;
149 this.description = theDescription;
150 this.symbols = alphabet;
152 symbolIndex = buildSymbolIndex(alphabet);
157 * crude heuristic for now...
159 peptide = alphabet.length >= 20;
163 * Record the minimum and maximum score values
165 protected void findMinMax()
167 float min = Float.MAX_VALUE;
168 float max = -Float.MAX_VALUE;
171 for (float[] row : matrix)
177 min = Math.min(min, f);
178 max = Math.max(max, f);
188 * Returns an array A where A[i] is the position in the alphabet array of the
189 * character whose value is i. For example if the alphabet is { 'A', 'D', 'X'
190 * } then A['D'] = A[68] = 1.
192 * Unmapped characters (not in the alphabet) get an index of -1.
194 * Mappings are added automatically for lower case symbols (for non case
195 * sensitive scoring), unless they are explicitly present in the alphabet (are
196 * scored separately in the score matrix).
198 * the gap character (space, dash or dot) included in the alphabet (if any) is
199 * recorded in a field
204 short[] buildSymbolIndex(char[] alphabet)
206 short[] index = new short[MAX_ASCII + 1];
207 Arrays.fill(index, UNMAPPED);
209 for (char c : alphabet)
217 * also map lower-case character (unless separately mapped)
219 if (c >= 'A' && c <= 'Z')
221 short lowerCase = (short) (c + ('a' - 'A'));
222 if (index[lowerCase] == UNMAPPED)
224 index[lowerCase] = pos;
233 public String getName()
239 public String getDescription()
245 public boolean isDNA()
251 public boolean isProtein()
257 * Returns a copy of the score matrix as used in getPairwiseScore. If using
258 * this matrix directly, callers <em>must</em> also call
259 * <code>getMatrixIndex</code> in order to get the matrix index for each
260 * character (symbol).
263 * @see #getMatrixIndex(char)
265 public float[][] getMatrix()
267 float[][] v = new float[matrix.length][matrix.length];
268 for (int i = 0; i < matrix.length; i++)
270 v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
276 * Answers the matrix index for a given character, or -1 if unmapped in the
277 * matrix. Use this method only if using <code>getMatrix</code> in order to
278 * compute scores directly (without symbol lookup) for efficiency.
284 public int getMatrixIndex(char c)
286 if (c < symbolIndex.length)
288 return symbolIndex[c];
297 * Returns the pairwise score for substituting c with d. If either c or d is
298 * an unexpected character, returns 1 for identity (c == d), else the minimum
299 * score value in the matrix.
302 public float getPairwiseScore(char c, char d)
304 if (c >= symbolIndex.length)
306 System.err.println(String.format(BAD_ASCII_ERROR, c));
309 if (d >= symbolIndex.length)
311 System.err.println(String.format(BAD_ASCII_ERROR, d));
315 int cIndex = symbolIndex[c];
316 int dIndex = symbolIndex[d];
317 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
319 return matrix[cIndex][dIndex];
323 * one or both symbols not found in the matrix
324 * currently scoring as 1 (for identity) or the minimum
325 * matrix score value (otherwise)
326 * (a case could be made for using minimum row/column value instead)
328 return c == d ? UNKNOWN_IDENTITY_SCORE : getMinimumScore();
332 * pretty print the matrix
335 public String toString()
337 return outputMatrix(false);
341 * Print the score matrix, optionally formatted as html, with the alphabet
342 * symbols as column headings and at the start of each row.
344 * The non-html format should give an output which can be parsed as a score
350 public String outputMatrix(boolean html)
352 StringBuilder sb = new StringBuilder(512);
355 * heading row with alphabet
359 sb.append("<table border=\"1\">");
360 sb.append(html ? "<tr><th></th>" : "");
364 sb.append("ScoreMatrix ").append(getName()).append("\n");
366 for (char sym : symbols)
370 sb.append("<th> ").append(sym).append(" </th>");
374 sb.append("\t").append(sym);
377 sb.append(html ? "</tr>\n" : "\n");
382 for (char c1 : symbols)
386 sb.append("<tr><td>");
388 sb.append(c1).append(html ? "</td>" : "");
389 for (char c2 : symbols)
391 sb.append(html ? "<td>" : "\t")
392 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
393 .append(html ? "</td>" : "");
395 sb.append(html ? "</tr>\n" : "\n");
399 sb.append("</table>");
401 return sb.toString();
405 * Answers the number of symbols coded for (also equal to the number of rows
406 * and columns of the score matrix)
412 return symbols.length;
416 * Computes an NxN matrix where N is the number of sequences, and entry [i, j]
417 * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores
418 * computed using the current score matrix. For example
420 * <li>Sequences:</li>
425 * <li>Score matrix is BLOSUM62</li>
426 * <li>Gaps treated same as X (unknown)</li>
427 * <li>product [0, 0] = F.F + K.K + L.L = 6 + 5 + 4 = 15</li>
428 * <li>product [1, 1] = R.R + -.- + D.D = 5 + -1 + 6 = 10</li>
429 * <li>product [2, 2] = Q.Q + I.I + A.A = 5 + 4 + 4 = 13</li>
430 * <li>product [3, 3] = G.G + W.W + C.C = 6 + 11 + 9 = 26</li>
431 * <li>product[0, 1] = F.R + K.- + L.D = -3 + -1 + -3 = -8
434 * This method is thread-safe.
437 public MatrixI findSimilarities(AlignmentView seqstrings,
438 SimilarityParamsI options)
440 char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X')
442 String[] seqs = seqstrings.getSequenceStrings(gapChar);
443 return findSimilarities(seqs, options);
447 * Computes pairwise similarities of a set of sequences using the given
454 protected MatrixI findSimilarities(String[] seqs, SimilarityParamsI params)
456 double[][] values = new double[seqs.length][];
457 for (int row = 0; row < seqs.length; row++)
459 values[row] = new double[seqs.length];
460 for (int col = 0; col < seqs.length; col++)
462 double total = computeSimilarity(seqs[row], seqs[col], params);
463 values[row][col] = total;
466 return new Matrix(values);
470 * Calculates the pairwise similarity of two strings using the given
471 * calculation parameters
478 protected double computeSimilarity(String seq1, String seq2,
479 SimilarityParamsI params)
481 int len1 = seq1.length();
482 int len2 = seq2.length();
485 int width = Math.max(len1, len2);
486 for (int i = 0; i < width; i++)
488 if (i >= len1 || i >= len2)
491 * off the end of one sequence; stop if we are only matching
492 * on the shorter sequence length, else treat as trailing gap
494 if (params.denominateByShortestLength())
500 char c1 = i >= len1 ? GAP_CHARACTER : seq1.charAt(i);
501 char c2 = i >= len2 ? GAP_CHARACTER : seq2.charAt(i);
502 boolean gap1 = Comparison.isGap(c1);
503 boolean gap2 = Comparison.isGap(c2);
508 * gap-gap: include if options say so, else ignore
510 if (!params.includeGappedColumns())
515 else if (gap1 || gap2)
518 * gap-residue: score if options say so
520 if (!params.includeGaps())
525 float score = getPairwiseScore(c1, c2);
532 * Answers a hashcode computed from the symbol alphabet and the matrix score
536 public int hashCode()
538 int hs = Arrays.hashCode(symbols);
539 for (float[] row : matrix)
541 hs = hs * 31 + Arrays.hashCode(row);
547 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
548 * and score values, else false
551 public boolean equals(Object obj)
553 if (!(obj instanceof ScoreMatrix))
557 ScoreMatrix sm = (ScoreMatrix) obj;
558 if (Arrays.equals(symbols, sm.symbols)
559 && Arrays.deepEquals(matrix, sm.matrix))
567 * Returns the alphabet the matrix scores for, as a string of characters
573 return new String(symbols);
576 public float getMinimumScore()
581 public float getMaximumScore()