/* * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) * Copyright (C) $$Year-Rel$$ The Jalview Authors * * This file is part of Jalview. * * Jalview is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * Jalview is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jalview. If not, see . * The Jalview Authors are detailed in the 'AUTHORS' file. */ package jalview.analysis.scoremodels; import jalview.math.Matrix; import jalview.math.MatrixI; import java.util.Arrays; public class ScoreMatrix implements PairwiseScoreModelI { public static final short UNMAPPED = (short) -1; private static final String BAD_ASCII_ERROR = "Unexpected character %s in getPairwiseScore"; private static final int MAX_ASCII = 127; /* * the name of the model as shown in menus */ private String name; /* * the characters that the model provides scores for */ private char[] symbols; /* * the score matrix; both dimensions must equal the number of symbols * matrix[i][j] is the substitution score for replacing symbols[i] with symbols[j] */ private float[][] matrix; /* * quick lookup to convert from an ascii character value to the index * of the corresponding symbol in the score matrix */ private short[] symbolIndex; /* * true for Protein Score matrix, false for dna score matrix */ private boolean peptide; /** * Constructor given a name, symbol alphabet, and matrix of scores for pairs * of symbols. The matrix should be square and of the same size as the * alphabet, for example 20x20 for a 20 symbol alphabet. * * @param name * Unique, human readable name for the matrix * @param alphabet * the symbols to which scores apply * @param matrix * Pairwise scores indexed according to the symbol alphabet */ public ScoreMatrix(String name, char[] alphabet, float[][] matrix) { if (alphabet.length != matrix.length) { throw new IllegalArgumentException( "score matrix size must match alphabet size"); } for (float[] row : matrix) { if (row.length != alphabet.length) { throw new IllegalArgumentException( "score matrix size must be square"); } } this.matrix = matrix; this.name = name; this.symbols = alphabet; symbolIndex = buildSymbolIndex(alphabet); /* * crude heuristic for now... */ peptide = alphabet.length >= 20; } /** * Returns an array A where A[i] is the position in the alphabet array of the * character whose value is i. For example if the alphabet is { 'A', 'D', 'X' * } then A['D'] = A[68] = 1. *

* Unmapped characters (not in the alphabet) get an index of -1. *

* Mappings are added automatically for lower case symbols (for non case * sensitive scoring), unless they are explicitly present in the alphabet (are * scored separately in the score matrix). * * @param alphabet * @return */ static short[] buildSymbolIndex(char[] alphabet) { short[] index = new short[MAX_ASCII + 1]; Arrays.fill(index, UNMAPPED); short pos = 0; for (char c : alphabet) { if (c <= MAX_ASCII) { index[c] = pos; } /* * also map lower-case character (unless separately mapped) */ if (c >= 'A' && c <= 'Z') { short lowerCase = (short) (c + ('a' - 'A')); if (index[lowerCase] == UNMAPPED) { index[lowerCase] = pos; } } pos++; } return index; } @Override public String getName() { return name; } @Override public boolean isDNA() { return !peptide; } @Override public boolean isProtein() { return peptide; } /** * Returns the score matrix as used in getPairwiseScore. If using this matrix * directly, callers must also call getMatrixIndex in * order to get the matrix index for each character (symbol). * * @return * @see #getMatrixIndex(char) */ public float[][] getMatrix() { return matrix; } /** * Answers the matrix index for a given character, or -1 if unmapped in the * matrix. Use this method only if using getMatrix in order to * compute scores directly (without symbol lookup) for efficiency. * * @param c * @return * @see #getMatrix() */ public int getMatrixIndex(char c) { if (c < symbolIndex.length) { return symbolIndex[c]; } else { return UNMAPPED; } } /** * Returns the pairwise score for substituting c with d, or zero if c or d is * an unscored or unexpected character */ @Override public float getPairwiseScore(char c, char d) { if (c >= symbolIndex.length) { System.err.println(String.format(BAD_ASCII_ERROR, c)); return 0; } if (d >= symbolIndex.length) { System.err.println(String.format(BAD_ASCII_ERROR, d)); return 0; } int cIndex = symbolIndex[c]; int dIndex = symbolIndex[d]; if (cIndex != UNMAPPED && dIndex != UNMAPPED) { return matrix[cIndex][dIndex]; } return 0; } /** * pretty print the matrix */ @Override public String toString() { return outputMatrix(false); } /** * Print the score matrix, optionally formatted as html, with the alphabet symbols as column headings and at the start of each row * @param html * @return */ public String outputMatrix(boolean html) { StringBuilder sb = new StringBuilder(512); /* * heading row with alphabet */ if (html) { sb.append(""); sb.append(html ? "" : ""); } for (char sym : symbols) { if (html) { sb.append(""); } else { sb.append("\t").append(sym); } } sb.append(html ? "\n" : "\n"); /* * table of scores */ for (char c1 : symbols) { if (html) { sb.append("" : ""); for (char c2 : symbols) { sb.append(html ? "" : ""); } sb.append(html ? "\n" : "\n"); } if (html) { sb.append("
 ").append(sym).append(" 
"); } sb.append(c1).append(html ? "" : "\t") .append(matrix[symbolIndex[c1]][symbolIndex[c2]]) .append(html ? "
"); } return sb.toString(); } /** * Answers the number of symbols coded for (also equal to the number of rows * and columns of the score matrix) * * @return */ public int getSize() { return symbols.length; } /** * Computes an NxN matrix where N is the number of sequences, and entry [i, j] * is sequence[i] pairwise multiplied with sequence[j], as a sum of scores * computed using the current score matrix. For example *

*/ public MatrixI computePairwiseScores(String[] seqs) { double[][] values = new double[seqs.length][]; for (int row = 0; row < seqs.length; row++) { values[row] = new double[seqs.length]; for (int col = 0; col < seqs.length; col++) { int total = 0; int width = Math.min(seqs[row].length(), seqs[col].length()); for (int i = 0; i < width; i++) { char c1 = seqs[row].charAt(i); char c2 = seqs[col].charAt(i); float score = getPairwiseScore(c1, c2); total += score; } values[row][col] = total; } } return new Matrix(values); } }