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;
34 * A class that models a substitution score matrix for any given alphabet of
37 public class ScoreMatrix implements SimilarityScoreModelI,
41 * an arbitrary score to assign for identity of an unknown symbol
42 * (this is the value on the diagonal in the * column of the NCBI matrix)
43 * (though a case could be made for using the minimum diagonal value)
45 private static final int UNKNOWN_IDENTITY_SCORE = 1;
48 * this fields records which gap character (if any) is used in the alphabet;
49 * space, dash or dot are recognised as gap symbols
51 private char gapCharacter = '0';
54 * Jalview 2.10.1 treated gaps as X (peptide) or N (nucleotide)
55 * for pairwise scoring; 2.10.2 uses gap score (last column) in
56 * score matrix (JAL-2397)
57 * Set this flag to true (via Groovy) for 2.10.1 behaviour
59 private static boolean scoreGapAsAny = false;
61 public static final short UNMAPPED = (short) -1;
63 private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore";
65 private static final int MAX_ASCII = 127;
68 * the name of the model as shown in menus
69 * each score model in use should have a unique name
74 * a description for the model as shown in tooltips
76 private String description;
79 * the characters that the model provides scores for
81 private char[] symbols;
84 * the score matrix; both dimensions must equal the number of symbols
85 * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j]
87 private float[][] matrix;
90 * quick lookup to convert from an ascii character value to the index
91 * of the corresponding symbol in the score matrix
93 private short[] symbolIndex;
96 * true for Protein Score matrix, false for dna score matrix
98 private boolean peptide;
100 private float minValue;
102 private float maxValue;
105 * Constructor given a name, symbol alphabet, and matrix of scores for pairs
106 * of symbols. The matrix should be square and of the same size as the
107 * alphabet, for example 20x20 for a 20 symbol alphabet.
110 * Unique, human readable name for the matrix
112 * the symbols to which scores apply
114 * Pairwise scores indexed according to the symbol alphabet
116 public ScoreMatrix(String theName, char[] alphabet, float[][] values)
118 if (alphabet.length != values.length)
120 throw new IllegalArgumentException(
121 "score matrix size must match alphabet size");
123 for (float[] row : values)
125 if (row.length != alphabet.length)
127 throw new IllegalArgumentException(
128 "score matrix size must be square");
132 this.matrix = values;
134 this.symbols = alphabet;
136 symbolIndex = buildSymbolIndex(alphabet);
141 * crude heuristic for now...
143 peptide = alphabet.length >= 20;
147 * Record the minimum and maximum score values
149 protected void findMinMax()
151 float min = Float.MAX_VALUE;
152 float max = -Float.MAX_VALUE;
155 for (float[] row : matrix)
161 min = Math.min(min, f);
162 max = Math.max(max, f);
172 * Returns an array A where A[i] is the position in the alphabet array of the
173 * character whose value is i. For example if the alphabet is { 'A', 'D', 'X'
174 * } then A['D'] = A[68] = 1.
176 * Unmapped characters (not in the alphabet) get an index of -1.
178 * Mappings are added automatically for lower case symbols (for non case
179 * sensitive scoring), unless they are explicitly present in the alphabet (are
180 * scored separately in the score matrix).
182 * the gap character (space, dash or dot) included in the alphabet (if any) is
183 * recorded in a field
188 short[] buildSymbolIndex(char[] alphabet)
190 short[] index = new short[MAX_ASCII + 1];
191 Arrays.fill(index, UNMAPPED);
193 for (char c : alphabet)
195 if (Comparison.isGap(c))
206 * also map lower-case character (unless separately mapped)
208 if (c >= 'A' && c <= 'Z')
210 short lowerCase = (short) (c + ('a' - 'A'));
211 if (index[lowerCase] == UNMAPPED)
213 index[lowerCase] = pos;
222 public String getName()
228 public String getDescription()
234 public boolean isDNA()
240 public boolean isProtein()
246 * Returns a copy of the score matrix as used in getPairwiseScore. If using
247 * this matrix directly, callers <em>must</em> also call
248 * <code>getMatrixIndex</code> in order to get the matrix index for each
249 * character (symbol).
252 * @see #getMatrixIndex(char)
254 public float[][] getMatrix()
256 float[][] v = new float[matrix.length][matrix.length];
257 for (int i = 0; i < matrix.length; i++)
259 v[i] = Arrays.copyOf(matrix[i], matrix[i].length);
265 * Answers the matrix index for a given character, or -1 if unmapped in the
266 * matrix. Use this method only if using <code>getMatrix</code> in order to
267 * compute scores directly (without symbol lookup) for efficiency.
273 public int getMatrixIndex(char c)
275 if (c < symbolIndex.length)
277 return symbolIndex[c];
286 * Answers the matrix index for the gap character, or -1 if unmapped in the
287 * matrix. Use this method only if using <code>getMatrix</code> in order to
288 * compute scores directly (without symbol lookup) for efficiency.
293 public int getGapIndex()
295 return getMatrixIndex(gapCharacter);
299 * Returns the pairwise score for substituting c with d. If either c or d is
300 * an unexpected character, returns 1 for identity (c == d), else the minimum
301 * score value in the matrix.
304 public float getPairwiseScore(char c, char d)
306 if (c >= symbolIndex.length)
308 System.err.println(String.format(BAD_ASCII_ERROR, c));
311 if (d >= symbolIndex.length)
313 System.err.println(String.format(BAD_ASCII_ERROR, d));
317 int cIndex = symbolIndex[c];
318 int dIndex = symbolIndex[d];
319 if (cIndex != UNMAPPED && dIndex != UNMAPPED)
321 return matrix[cIndex][dIndex];
325 * one or both symbols not found in the matrix
326 * currently scoring as 1 (for identity) or the minimum
327 * matrix score value (otherwise)
328 * (a case could be made for using minimum row/column value instead)
330 return c == d ? UNKNOWN_IDENTITY_SCORE : getMinimumScore();
334 * pretty print the matrix
337 public String toString()
339 return outputMatrix(false);
343 * Print the score matrix, optionally formatted as html, with the alphabet
344 * symbols as column headings and at the start of each row.
346 * The non-html format should give an output which can be parsed as a score
352 public String outputMatrix(boolean html)
354 StringBuilder sb = new StringBuilder(512);
357 * heading row with alphabet
361 sb.append("<table border=\"1\">");
362 sb.append(html ? "<tr><th></th>" : "");
366 sb.append("ScoreMatrix ").append(getName()).append("\n");
368 for (char sym : symbols)
372 sb.append("<th> ").append(sym).append(" </th>");
376 sb.append("\t").append(sym);
379 sb.append(html ? "</tr>\n" : "\n");
384 for (char c1 : symbols)
388 sb.append("<tr><td>");
390 sb.append(c1).append(html ? "</td>" : "");
391 for (char c2 : symbols)
393 sb.append(html ? "<td>" : "\t")
394 .append(matrix[symbolIndex[c1]][symbolIndex[c2]])
395 .append(html ? "</td>" : "");
397 sb.append(html ? "</tr>\n" : "\n");
401 sb.append("</table>");
403 return sb.toString();
407 * Answers the number of symbols coded for (also equal to the number of rows
408 * and columns of the score matrix)
414 return symbols.length;
418 * Computes an NxN matrix where N is the number of sequences, and entry [i, j]
419 * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores
420 * computed using the current score matrix. For example
422 * <li>Sequences:</li>
427 * <li>Score matrix is BLOSUM62</li>
428 * <li>Gaps treated same as X (unknown)</li>
429 * <li>product [0, 0] = F.F + K.K + L.L = 6 + 5 + 4 = 15</li>
430 * <li>product [1, 1] = R.R + -.- + D.D = 5 + -1 + 6 = 10</li>
431 * <li>product [2, 2] = Q.Q + I.I + A.A = 5 + 4 + 4 = 13</li>
432 * <li>product [3, 3] = G.G + W.W + C.C = 6 + 11 + 9 = 26</li>
433 * <li>product[0, 1] = F.R + K.- + L.D = -3 + -1 + -3 = -8
438 public MatrixI findSimilarities(AlignmentView seqstrings,
439 SimilarityParamsI options)
441 char gapChar = scoreGapAsAny ? (seqstrings.isNa() ? 'N' : 'X')
443 String[] seqs = seqstrings.getSequenceStrings(gapChar);
444 return findSimilarities(seqs, options);
448 * Computes pairwise similarities of a set of sequences using the given
455 protected MatrixI findSimilarities(String[] seqs, SimilarityParamsI params)
457 double[][] values = new double[seqs.length][];
458 for (int row = 0; row < seqs.length; row++)
460 values[row] = new double[seqs.length];
461 for (int col = 0; col < seqs.length; col++)
463 double total = computeSimilarity(seqs[row], seqs[col], params);
464 values[row][col] = total;
467 return new Matrix(values);
471 * Calculates the pairwise similarity of two strings using the given
472 * calculation parameters
479 protected double computeSimilarity(String seq1, String seq2,
480 SimilarityParamsI params)
482 int len1 = seq1.length();
483 int len2 = seq2.length();
486 int width = Math.max(len1, len2);
487 for (int i = 0; i < width; i++)
489 if (i >= len1 || i >= len2)
492 * off the end of one sequence; stop if we are only matching
493 * on the shorter sequence length, else treat as trailing gap
495 if (params.denominateByShortestLength())
501 char c1 = i >= len1 ? gapCharacter : seq1.charAt(i);
502 char c2 = i >= len2 ? gapCharacter : seq2.charAt(i);
503 boolean gap1 = Comparison.isGap(c1);
504 boolean gap2 = Comparison.isGap(c2);
509 * gap-gap: include if options say so, else ignore
511 if (!params.includeGappedColumns())
516 else if (gap1 || gap2)
519 * gap-residue: score if options say so
521 if (!params.includeGaps())
526 float score = getPairwiseScore(c1, c2);
533 * Answers a hashcode computed from the symbol alphabet and the matrix score
537 public int hashCode()
539 int hs = Arrays.hashCode(symbols);
540 for (float[] row : matrix)
542 hs = hs * 31 + Arrays.hashCode(row);
548 * Answers true if the argument is a ScoreMatrix with the same symbol alphabet
549 * and score values, else false
552 public boolean equals(Object obj)
554 if (!(obj instanceof ScoreMatrix))
558 ScoreMatrix sm = (ScoreMatrix) obj;
559 if (Arrays.equals(symbols, sm.symbols)
560 && Arrays.deepEquals(matrix, sm.matrix))
568 * Returns the alphabet the matrix scores for, as a string of characters
574 return new String(symbols);
577 public void setDescription(String desc)
582 public float getMinimumScore()
587 public float getMaximumScore()