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.
23 import jalview.util.Format;
24 import jalview.util.MessageManager;
26 import java.io.PrintStream;
27 import java.lang.Math;
28 import java.util.Arrays;
31 * A class to model rectangular matrices of double values and operations on them
33 public class Matrix implements MatrixI
36 * maximum number of iterations for tqli
38 private static final int MAX_ITER = 45;
39 // fudge - add 15 iterations, just in case
44 final protected int rows;
47 * the number of columns
49 final protected int cols;
52 * the cell values in row-major order
54 private double[][] value;
56 protected double[] d; // Diagonal
58 protected double[] e; // off diagonal
61 * Constructor given number of rows and columns
66 protected Matrix(int rowCount, int colCount)
73 * Creates a new Matrix object containing a copy of the supplied array values.
77 * new Matrix(new double[][] {{2, 3, 4}, {5, 6, 7})
83 * Note that ragged arrays (with not all rows, or columns, of the same
84 * length), are not supported by this class. They can be constructed, but
85 * results of operations on them are undefined and may throw exceptions.
88 * the matrix values in row-major order
90 public Matrix(double[][] values)
92 this.rows = values.length;
93 this.cols = this.rows == 0 ? 0 : values[0].length;
96 * make a copy of the values array, for immutability
98 this.value = new double[rows][];
100 for (double[] row : values)
104 value[i] = new double[row.length];
105 System.arraycopy(row, 0, value[i], 0, row.length);
111 public Matrix(float[][] values)
113 this.rows = values.length;
114 this.cols = this.rows == 0 ? 0 : values[0].length;
117 * make a copy of the values array, for immutability
119 this.value = new double[rows][];
121 for (float[] row : values)
125 value[i] = new double[row.length];
127 for (float oldValue : row)
129 value[i][j] = oldValue;
138 public MatrixI transpose()
140 double[][] out = new double[cols][rows];
142 for (int i = 0; i < cols; i++)
144 for (int j = 0; j < rows; j++)
146 out[i][j] = value[j][i];
150 return new Matrix(out);
161 public void print(PrintStream ps, String format)
163 for (int i = 0; i < rows; i++)
165 for (int j = 0; j < cols; j++)
167 Format.print(ps, format, getValue(i, j));
175 public MatrixI preMultiply(MatrixI in)
177 if (in.width() != rows)
179 throw new IllegalArgumentException("Can't pre-multiply " + this.rows
180 + " rows by " + in.width() + " columns");
182 double[][] tmp = new double[in.height()][this.cols];
184 for (int i = 0; i < in.height(); i++)
186 for (int j = 0; j < this.cols; j++)
189 * result[i][j] is the vector product of
190 * in.row[i] and this.column[j]
192 for (int k = 0; k < in.width(); k++)
194 if (!Double.isNaN(in.getValue(i,k)) && !Double.isNaN(this.value[k][j]))
196 tmp[i][j] += (in.getValue(i, k) * this.value[k][j]);
202 return new Matrix(tmp);
211 public double[] vectorPostMultiply(double[] in)
213 double[] out = new double[in.length];
215 for (int i = 0; i < in.length; i++)
219 for (int k = 0; k < in.length; k++)
221 out[i] += (value[i][k] * in[k]);
229 public MatrixI postMultiply(MatrixI in)
231 if (in.height() != this.cols)
233 throw new IllegalArgumentException("Can't post-multiply " + this.cols
234 + " columns by " + in.height() + " rows");
236 return in.preMultiply(this);
240 public MatrixI copy()
242 double[][] newmat = new double[rows][cols];
244 for (int i = 0; i < rows; i++)
246 System.arraycopy(value[i], 0, newmat[i], 0, value[i].length);
249 Matrix m = new Matrix(newmat);
252 m.d = Arrays.copyOf(this.d, this.d.length);
256 m.e = Arrays.copyOf(this.e, this.e.length);
279 this.d = new double[rows];
280 this.e = new double[rows];
282 for (i = n; i >= 2; i--)
290 for (k = 1; k <= l; k++)
292 double v = Math.abs(getValue(i - 1, k - 1));
298 e[i - 1] = getValue(i - 1, l - 1);
302 for (k = 1; k <= l; k++)
304 double v = divideValue(i - 1, k - 1, scale);
308 f = getValue(i - 1, l - 1);
312 g = -1.0 * Math.sqrt(h);
319 e[i - 1] = scale * g;
321 setValue(i - 1, l - 1, f - g);
324 for (j = 1; j <= l; j++)
326 double val = getValue(i - 1, j - 1) / h;
327 setValue(j - 1, i - 1, val);
330 for (k = 1; k <= j; k++)
332 g += (getValue(j - 1, k - 1) * getValue(i - 1, k - 1));
335 for (k = j + 1; k <= l; k++)
337 g += (getValue(k - 1, j - 1) * getValue(i - 1, k - 1));
341 f += (e[j - 1] * getValue(i - 1, j - 1));
346 for (j = 1; j <= l; j++)
348 f = getValue(i - 1, j - 1);
349 g = e[j - 1] - (hh * f);
352 for (k = 1; k <= j; k++)
354 double val = (f * e[k - 1]) + (g * getValue(i - 1, k - 1));
355 addValue(j - 1, k - 1, -val);
362 e[i - 1] = getValue(i - 1, l - 1);
371 for (i = 1; i <= n; i++)
377 for (j = 1; j <= l; j++)
381 for (k = 1; k <= l; k++)
383 g += (getValue(i - 1, k - 1) * getValue(k - 1, j - 1));
386 for (k = 1; k <= l; k++)
388 addValue(k - 1, j - 1, -(g * getValue(k - 1, i - 1)));
393 d[i - 1] = getValue(i - 1, i - 1);
394 setValue(i - 1, i - 1, 1.0);
396 for (j = 1; j <= l; j++)
398 setValue(j - 1, i - 1, 0.0);
399 setValue(i - 1, j - 1, 0.0);
405 * Adds f to the value at [i, j] and returns the new value
411 protected double addValue(int i, int j, double f)
413 double v = value[i][j] + f;
419 * Divides the value at [i, j] by divisor and returns the new value. If d is
420 * zero, returns the unchanged value.
427 protected double divideValue(int i, int j, double divisor)
431 return getValue(i, j);
433 double v = value[i][j];
443 public void tqli() throws Exception
462 for (i = 2; i <= n; i++)
469 for (l = 1; l <= n; l++)
475 for (m = l; m <= (n - 1); m++)
477 dd = Math.abs(d[m - 1]) + Math.abs(d[m]);
479 if ((Math.abs(e[m - 1]) + dd) == dd)
489 if (iter == MAX_ITER)
491 throw new Exception(MessageManager.formatMessage(
492 "exception.matrix_too_many_iteration", new String[]
493 { "tqli", Integer.valueOf(MAX_ITER).toString() }));
497 // System.out.println("Iteration " + iter);
500 g = (d[l] - d[l - 1]) / (2.0 * e[l - 1]);
501 r = Math.sqrt((g * g) + 1.0);
502 g = d[m - 1] - d[l - 1] + (e[l - 1] / (g + sign(r, g)));
507 for (i = m - 1; i >= l; i--)
512 if (Math.abs(f) >= Math.abs(g))
515 r = Math.sqrt((c * c) + 1.0);
523 r = Math.sqrt((s * s) + 1.0);
530 r = ((d[i - 1] - g) * s) + (2.0 * c * b);
535 for (k = 1; k <= n; k++)
537 f = getValue(k - 1, i);
538 setValue(k - 1, i, (s * getValue(k - 1, i - 1)) + (c * f));
539 setValue(k - 1, i - 1,
540 (c * getValue(k - 1, i - 1)) - (s * f));
544 d[l - 1] = d[l - 1] - p;
553 public double getValue(int i, int j)
559 public void setValue(int i, int j, double val)
581 this.d = new double[rows];
582 this.e = new double[rows];
584 for (i = n - 1; i >= 1; i--)
592 for (k = 0; k < l; k++)
594 scale += Math.abs(value[i][k]);
603 for (k = 0; k < l; k++)
605 value[i][k] /= scale;
606 h += (value[i][k] * value[i][k]);
613 g = -1.0 * Math.sqrt(h);
625 for (j = 0; j < l; j++)
627 value[j][i] = value[i][j] / h;
630 for (k = 0; k < j; k++)
632 g += (value[j][k] * value[i][k]);
635 for (k = j; k < l; k++)
637 g += (value[k][j] * value[i][k]);
641 f += (e[j] * value[i][j]);
646 for (j = 0; j < l; j++)
652 for (k = 0; k < j; k++)
654 value[j][k] -= ((f * e[k]) + (g * value[i][k]));
670 for (i = 0; i < n; i++)
676 for (j = 0; j < l; j++)
680 for (k = 0; k < l; k++)
682 g += (value[i][k] * value[k][j]);
685 for (k = 0; k < l; k++)
687 value[k][j] -= (g * value[k][i]);
695 for (j = 0; j < l; j++)
706 public void tqli2() throws Exception
726 for (i = 2; i <= n; i++)
733 for (l = 1; l <= n; l++)
739 for (m = l; m <= (n - 1); m++)
741 dd = Math.abs(d[m - 1]) + Math.abs(d[m]);
743 if ((Math.abs(e[m - 1]) + dd) == dd)
753 if (iter == MAX_ITER)
755 throw new Exception(MessageManager.formatMessage(
756 "exception.matrix_too_many_iteration", new String[]
757 { "tqli2", Integer.valueOf(MAX_ITER).toString() }));
761 // System.out.println("Iteration " + iter);
764 g = (d[l] - d[l - 1]) / (2.0 * e[l - 1]);
765 r = Math.sqrt((g * g) + 1.0);
766 g = d[m - 1] - d[l - 1] + (e[l - 1] / (g + sign(r, g)));
771 for (i = m - 1; i >= l; i--)
776 if (Math.abs(f) >= Math.abs(g))
779 r = Math.sqrt((c * c) + 1.0);
787 r = Math.sqrt((s * s) + 1.0);
794 r = ((d[i - 1] - g) * s) + (2.0 * c * b);
799 for (k = 1; k <= n; k++)
802 value[k - 1][i] = (s * value[k - 1][i - 1]) + (c * f);
803 value[k - 1][i - 1] = (c * value[k - 1][i - 1]) - (s * f);
807 d[l - 1] = d[l - 1] - p;
816 * Answers the first argument with the sign of the second argument
823 static double sign(double a, double b)
836 * returns the matrix as a double[][] array
841 public double[][] asArray()
847 * Returns an array containing the values in the specified column
854 public double[] getColumn(int col)
856 double[] out = new double[rows];
858 for (int i = 0; i < rows; i++)
860 out[i] = value[i][col];
874 public void printD(PrintStream ps, String format)
876 for (int j = 0; j < d.length; j++)
878 Format.print(ps, format, d[j]);
891 public void printE(PrintStream ps, String format)
893 for (int j = 0; j < rows; j++)
895 Format.print(ps, format, e[j]);
900 public double[] getD()
906 public double[] getE()
924 public double[] getRow(int i)
926 double[] row = new double[cols];
927 System.arraycopy(value[i], 0, row, 0, cols);
932 * Returns a length 2 array of {minValue, maxValue} of all values in the
933 * matrix. Returns null if the matrix is null or empty.
937 double[] findMinMax()
943 double min = Double.MAX_VALUE;
944 double max = -Double.MAX_VALUE;
945 boolean empty = true;
946 for (double[] row : value)
964 return empty ? null : new double[] { min, max };
971 public void reverseRange(boolean maxToZero)
977 double[] minMax = findMinMax();
980 return; // empty matrix
982 double subtractFrom = maxToZero ? minMax[1] : minMax[0] + minMax[1];
984 for (double[] row : value)
991 row[j] = subtractFrom - x;
999 * Multiplies every entry in the matrix by the given value.
1004 public void multiply(double by)
1006 for (double[] row : value)
1010 for (int i = 0; i < row.length; i++)
1019 * Add d to all entries of this matrix
1021 * @param d ~ value to add
1024 public void add(double d)
1026 for (double[] row : value)
1030 for (int i = 0; i < row.length; i++)
1039 public void setD(double[] v)
1045 public void setE(double[] v)
1050 public double getTotal()
1053 for (int i = 0; i < this.height(); i++)
1055 for (int j = 0; j < this.width(); j++)
1067 public boolean equals(MatrixI m2, double delta)
1069 if (m2 == null || this.height() != m2.height()
1070 || this.width() != m2.width())
1074 for (int i = 0; i < this.height(); i++)
1076 for (int j = 0; j < this.width(); j++)
1078 double diff = this.getValue(i, j) - m2.getValue(i, j);
1079 if (Math.abs(diff) > delta)
1089 * Returns a copy in which every value in the matrix is its absolute
1094 public MatrixI absolute()
1096 MatrixI copy = this.copy();
1097 for (int i = 0; i < copy.width(); i++)
1099 double[] row = copy.getRow(i);
1102 for (int j = 0; j < row.length; j++)
1104 row[j] = Math.abs(row[j]);
1112 * Returns the mean of each row
1117 public double[] meanRow()
1119 double[] mean = new double[rows];
1121 for (double[] row : value)
1125 mean[i++] = MiscMath.mean(row);
1132 * Returns the mean of each column
1137 public double[] meanCol()
1139 double[] mean = new double[cols];
1140 for (int j = 0; j < cols; j++)
1142 double[] column = getColumn(j);
1145 mean[j] = MiscMath.mean(column);
1152 * return a flattened matrix containing the sum of each column
1157 public double[] sumCol()
1159 double[] sum = new double[cols];
1160 for (int j = 0; j < cols; j++)
1162 double[] column = getColumn(j);
1165 sum[j] = MiscMath.sum(column);
1172 * returns the mean value of the complete matrix
1177 public double mean()
1181 for (double[] row : value)
1183 for (double col : row)
1185 if (!Double.isNaN(col))
1193 return sum / (double) (this.rows * this.cols - nanCount);
1197 * fills up a diagonal matrix with its transposed copy
1198 * !other side should be filled with 0
1199 * !keeps Double.NaN found in either side
1201 * TODO check on which side it was diagonal and only do calculations for the other side
1204 public void fillDiagonal()
1208 MatrixI copy = this.transpose(); // goes through each element in the matrix and
1209 for (int i = 0; i < n; i++) // adds the value in the transposed copy to the original value
1211 for (int j = 0; j < m; j++)
1215 this.addValue(i, j, copy.getValue(i,j));
1222 * counts the number of Double.NaN in the matrix
1227 public int countNaN()
1230 for (int i = 0; i < this.rows; i++)
1232 for (int j = 0; j < this.cols; j++)
1234 if (Double.isNaN(this.getValue(i,j)))
1244 * performs an element-wise addition of this matrix by another matrix ~ this - m
1245 * @param m ~ other matrix
1250 public MatrixI add(MatrixI m)
1252 if (m.width() != cols || m.height() != rows)
1254 throw new IllegalArgumentException("Can't add a " + m.height() + "x" + m.width() + " to a " + this.rows + "x" + this.cols + " matrix");
1256 double[][] tmp = new double[this.rows][this.cols];
1257 for (int i = 0; i < this.rows; i++)
1259 for (int j = 0; j < this.cols; j++)
1261 tmp[i][j] = this.getValue(i,j) + m.getValue(i,j);
1264 return new Matrix(tmp);
1268 * performs an element-wise subtraction of this matrix by another matrix ~ this - m
1269 * @param m ~ other matrix
1274 public MatrixI subtract(MatrixI m)
1276 if (m.width() != cols || m.height() != rows)
1278 throw new IllegalArgumentException("Can't subtract a " + m.height() + "x" + m.width() + " from a " + this.rows + "x" + this.cols + " matrix");
1280 double[][] tmp = new double[this.rows][this.cols];
1281 for (int i = 0; i < this.rows; i++)
1283 for (int j = 0; j < this.cols; j++)
1285 tmp[i][j] = this.getValue(i,j) - m.getValue(i,j);
1288 return new Matrix(tmp);
1292 * performs an element-wise multiplication of this matrix by another matrix ~ this * m
1293 * @param m ~ other matrix
1298 public MatrixI elementwiseMultiply(MatrixI m)
1300 if (m.width() != cols || m.height() != rows)
1302 throw new IllegalArgumentException("Can't multiply a " + this.rows + "x" + this.cols + " by a " + m.height() + "x" + m.width() + " matrix");
1304 double[][] tmp = new double[this.rows][this.cols];
1305 for (int i = 0; i < this.rows; i++)
1307 for (int j = 0; j < this.cols; j++)
1309 tmp[i][j] = this.getValue(i, j) * m.getValue(i,j);
1312 return new Matrix(tmp);
1316 * performs an element-wise division of this matrix by another matrix ~ this / m
1317 * @param m ~ other matrix
1322 public MatrixI elementwiseDivide(MatrixI m)
1324 if (m.width() != cols || m.height() != rows)
1326 throw new IllegalArgumentException("Can't divide a " + this.rows + "x" + this.cols + " by a " + m.height() + "x" + m.width() + " matrix");
1328 double[][] tmp = new double[this.rows][this.cols];
1329 for (int i = 0; i < this.rows; i++)
1331 for (int j = 0; j < this.cols; j++)
1333 tmp[i][j] = this.getValue(i, j) / m.getValue(i,j);
1336 return new Matrix(tmp);
1340 * calculate the root-mean-square for tow matrices
1341 * @param m ~ other matrix
1346 public double rmsd(MatrixI m)
1348 MatrixI squaredDeviates = this.subtract(m);
1349 squaredDeviates = squaredDeviates.preMultiply(squaredDeviates);
1350 return Math.sqrt(squaredDeviates.mean());
1354 * calculates the Frobenius norm of this matrix
1359 public double norm()
1362 for (double[] row : value)
1364 for (double val : row)
1366 result += Math.pow(val, 2);
1369 return Math.sqrt(result);
1373 * returns the sum of all values in this matrix
1381 for (double[] row : value)
1383 for (double val : row)
1385 sum += (Double.isNaN(val)) ? 0.0 : val;
1392 * returns the sum-product of this matrix with vector v
1398 public double[] sumProduct(double[] v)
1400 if (v.length != cols)
1402 throw new IllegalArgumentException("Vector and matrix do not have the same dimension! (" + v.length + " != " + cols + ")");
1404 double[] result = new double[rows];
1405 for (int i = 0; i < rows; i++)
1407 double[] row = value[i];
1409 for (int j = 0; j < row.length; j++)
1411 sum += row[j] * v[j];
1419 * mirrors columns of the matrix
1424 public MatrixI mirrorCol()
1426 double[][] result = new double[rows][cols];
1427 for (int i = 0; i < rows; i++)
1429 int k = cols - 1; // reverse col
1430 for (int j = 0; j < cols; j++)
1432 result[i][k--] = this.getValue(i,j);
1435 return new Matrix(result);