Debian Codegraph @

src/dr/math/matrixAlgebra/Matrix.java

raw symbols SCIP
1 /*
2 * Matrix.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math.matrixAlgebra;
27
28 /**
29 * Class representing matrix
30 *
31 * @author Didier H. Besset
32 */
33 public class Matrix {
34 protected double[][] components;
35 protected LUPDecomposition lupDecomposition = null;
36
37 /**
38 * Creates a matrix with given components.
39 * NOTE: the components must not be altered after the definition.
40 *
41 * @param a double[][]
42 */
43 public Matrix(double[][] a) {
44 components = a;
45 }
46
47 /**
48 * Creates a matrix with given components.
49 * NOTE: the components must not be altered after the definition.
50 *
51 * @param a double[]
52 */
53 public Matrix(double[] a, int n, int m) {
54 if (n <= 0 || m <= 0)
55 throw new NegativeArraySizeException(
56 "Requested matrix size: " + n + " by " + m);
57 if (n * m != a.length) {
58 throw new IllegalArgumentException(
59 "Requested matrix size: " + n + " by " + m + " doesn't match array size: " + a.length);
60 }
61 components = new double[n][m];
62 int k = 0;
63 for (int i = 0; i < n; i++) {
64 for (int j = 0; j < m; j++) {
65 components[i][j] = a[k];
66 k++;
67 }
68
69 }
70 }
71
72 /**
73 * Creates a null matrix of given dimensions.
74 *
75 * @param n int number of rows
76 * @param m int number of columns
77 * @throws NegativeArraySizeException
78 */
79 public Matrix(int n, int m) throws NegativeArraySizeException {
80 if (n <= 0 || m <= 0)
81 throw new NegativeArraySizeException(
82 "Requested matrix size: " + n + " by " + m);
83 components = new double[n][m];
84 // clear(); // Java automatically zeros new vectors
85 }
86
87 /**
88 * @param a MatrixAlgebra.Matrix
89 * @throws dr.math.matrixAlgebra.IllegalDimension
90 * if the supplied matrix
91 * does not have the same dimensions.
92 */
93 public void accumulate(Matrix a) throws IllegalDimension {
94 if (a.rows() != rows() || a.columns() != columns())
95 throw new IllegalDimension("Operation error: cannot add a"
96 + a.rows() + " by " + a.columns()
97 + " matrix to a " + rows() + " by "
98 + columns() + " matrix");
99 int m = components[0].length;
100 for (int i = 0; i < components.length; i++) {
101 for (int j = 0; j < m; j++)
102 components[i][j] += a.component(i, j);
103 }
104 }
105
106 public void decumulate(Matrix a) throws IllegalDimension {
107 if (a.rows() != rows() || a.columns() != columns())
108 throw new IllegalDimension("Operation error: cannot add a"
109 + a.rows() + " by " + a.columns()
110 + " matrix to a " + rows() + " by "
111 + columns() + " matrix");
112 int m = components[0].length;
113 for (int i = 0; i < components.length; i++) {
114 for (int j = 0; j < m; j++)
115 components[i][j] -= a.component(i, j);
116 }
117 }
118
119 /**
120 * @param a MatrixAlgebra.Matrix
121 * @return MatrixAlgebra.Matrix sum of the receiver with the
122 * supplied matrix.
123 * @throws dr.math.matrixAlgebra.IllegalDimension
124 * if the supplied matrix
125 * does not have the same dimensions.
126 */
127 public Matrix add(Matrix a) throws IllegalDimension {
128 if (a.rows() != rows() || a.columns() != columns())
129 throw new IllegalDimension("Operation error: cannot add a "
130 + a.rows() + " by " + a.columns()
131 + " matrix to a " + rows() + " by "
132 + columns() + " matrix");
133 return new Matrix(addComponents(a));
134 }
135
136 /**
137 * Computes the components of the sum of the receiver and
138 * a supplied matrix.
139 *
140 * @param a MatrixAlgebra.Matrix
141 * @return double[][]
142 */
143 protected double[][] addComponents(Matrix a) {
144 int n = this.rows();
145 int m = this.columns();
146 double[][] newComponents = new double[n][m];
147 for (int i = 0; i < n; i++) {
148 for (int j = 0; j < n; j++)
149 newComponents[i][j] = components[i][j] + a.components[i][j];
150 }
151 return newComponents;
152 }
153
154 public void clear() {
155 int m = components[0].length;
156 for (int i = 0; i < components.length; i++) {
157 for (int j = 0; j < m; j++) components[i][j] = 0;
158 }
159 }
160
161 /**
162 * @return int the number of columns of the matrix
163 */
164 public int columns() {
165 return components[0].length;
166 }
167
168 /**
169 * @param n int
170 * @param m int
171 * @return double
172 */
173 public double component(int n, int m) {
174 return components[n][m];
175 }
176
177 public void set(int n, int m, double value) {
178 components[n][m] = value;
179 }
180
181 /**
182 * @return double
183 * @throws dr.math.matrixAlgebra.IllegalDimension
184 * if the supplied
185 * matrix is not square.
186 */
187 public double determinant() throws IllegalDimension {
188 return lupDecomposition().determinant();
189 }
190
191 public double logDeterminant() throws IllegalDimension {
192 return lupDecomposition().logDeterminant();
193 }
194
195 public boolean isPD() throws IllegalDimension {
196 return lupDecomposition().isPD();
197 }
198
199
200 /**
201 * @param a MatrixAlgebra.Matrix
202 * @return true if the supplied matrix is equal to the receiver.
203 */
204 public boolean equals(Matrix a) {
205 int n = this.rows();
206 if (a.rows() != n)
207 return false;
208 int m = this.columns();
209 if (a.columns() != m)
210 return false;
211 for (int i = 0; i < n; i++) {
212 for (int j = 0; j < n; j++) {
213 if (a.components[i][j] != components[i][j])
214 return false;
215 }
216 }
217 return true;
218 }
219
220 /**
221 * @return MatrixAlgebra.Matrix inverse of the receiver
222 * or pseudoinverse if the receiver is not a square matrix.
223 * @throws java.lang.ArithmeticException if the receiver is
224 * a singular matrix.
225 */
226 public Matrix inverse() throws ArithmeticException {
227 try {
228 return new Matrix(
229 lupDecomposition().inverseMatrixComponents());
230 } catch (IllegalDimension e) {
231 return new Matrix(
232 transposedProduct().inverse()
233 .productWithTransposedComponents(this));
234 }
235 }
236
237 /**
238 * @return boolean
239 */
240 public boolean isSquare() {
241 return rows() == columns();
242 }
243
244 /**
245 * @return LUPDecomposition the LUP decomposition of the receiver.
246 * @throws IllegalDimension if the receiver is not
247 * a square matrix.
248 */
249 protected LUPDecomposition lupDecomposition()
250 throws IllegalDimension {
251 if (lupDecomposition == null)
252 lupDecomposition = new LUPDecomposition(this);
253 return lupDecomposition;
254 }
255
256 /**
257 * @param a double multiplicand.
258 * @return MatrixAlgebra.Matrix product of the matrix with
259 * a supplied number
260 */
261 public Matrix product(double a) {
262 return new Matrix(productComponents(a));
263 }
264
265 /**
266 * Computes the product of the matrix with a vector.
267 *
268 * @param v matrixAlgebra.Vector
269 * @return matrixAlgebra.Vector
270 */
271 public Vector product(Vector v) throws IllegalDimension {
272 int n = this.rows();
273 int m = this.columns();
274 if (v.dimension() != m)
275 throw new IllegalDimension("Product error: " + n + " by " + m
276 + " matrix cannot by multiplied with vector of dimension "
277 + v.dimension());
278 return secureProduct(v);
279 }
280
281 /**
282 * @param a MatrixAlgebra.Matrix
283 * @return MatrixAlgebra.Matrix product of the receiver with the
284 * supplied matrix
285 * @throws dr.math.matrixAlgebra.IllegalDimension
286 * If the number of
287 * columns of the receiver are not equal to the
288 * number of rows of the supplied matrix.
289 */
290 public Matrix product(Matrix a) throws IllegalDimension {
291 if (a.rows() != columns())
292 throw new IllegalDimension(
293 "Operation error: cannot multiply a "
294 + rows() + " by " + columns()
295 + " matrix with a " + a.rows()
296 + " by " + a.columns()
297 + " matrix");
298 return new Matrix(productComponents(a));
299 }
300
301 /**
302 * @param a double
303 * @return double[][]
304 */
305 protected double[][] productComponents(double a) {
306 int n = this.rows();
307 int m = this.columns();
308 double[][] newComponents = new double[n][m];
309 for (int i = 0; i < n; i++) {
310 for (int j = 0; j < m; j++)
311 newComponents[i][j] = a * components[i][j];
312 }
313 return newComponents;
314 }
315
316 /**
317 * @param a MatrixAlgebra.Matrix
318 * @return double[][] the components of the product of the receiver
319 * with the supplied matrix
320 */
321 protected double[][] productComponents(Matrix a) {
322 int p = this.columns();
323 int n = this.rows();
324 int m = a.columns();
325 double[][] newComponents = new double[n][m];
326 for (int i = 0; i < n; i++) {
327 for (int j = 0; j < m; j++) {
328 double sum = 0;
329 for (int k = 0; k < p; k++)
330 sum += components[i][k] * a.components[k][j];
331 newComponents[i][j] = sum;
332 }
333 }
334 return newComponents;
335 }
336
337 /**
338 * @param a MatrixAlgebra.Matrix
339 * @return MatrixAlgebra.Matrix product of the receiver with the
340 * tranpose of the supplied matrix
341 * @throws dr.math.matrixAlgebra.IllegalDimension
342 * If the number of
343 * columns of the receiver are not equal to
344 * the number of columns of the supplied matrix.
345 */
346 public Matrix productWithTransposed(Matrix a)
347 throws IllegalDimension {
348 if (a.columns() != columns())
349 throw new IllegalDimension(
350 "Operation error: cannot multiply a " + rows()
351 + " by " + columns()
352 + " matrix with the transpose of a "
353 + a.rows() + " by " + a.columns()
354 + " matrix");
355 return new Matrix(productWithTransposedComponents(a));
356 }
357
358 public static Matrix buildIdentityTimesElementMatrix(int dim, double element){
359 double[][] idTemp=new double[dim][dim];
360 for (int i = 0; i < dim; i++) {
361 idTemp[i][i]=element;
362 }
363 return new Matrix(idTemp);
364 }
365
366 /**
367 * @param a MatrixAlgebra.Matrix
368 * @return double[][] the components of the product of the receiver
369 * with the transpose of the supplied matrix
370 */
371 protected double[][] productWithTransposedComponents(Matrix a) {
372 int p = this.columns();
373 int n = this.rows();
374 int m = a.rows();
375 double[][] newComponents = new double[n][m];
376 for (int i = 0; i < n; i++) {
377 for (int j = 0; j < m; j++) {
378 double sum = 0;
379 for (int k = 0; k < p; k++)
380 sum += components[i][k] * a.components[j][k];
381 newComponents[i][j] = sum;
382 }
383 }
384 return newComponents;
385 }
386
387 /**
388 * @return int the number of rows of the matrix
389 */
390 public int rows() {
391 return components.length;
392 }
393
394 /**
395 * Computes the product of the matrix with a vector.
396 *
397 * @param v matrixAlgebra.Vector
398 * @return matrixAlgebra.Vector
399 */
400 protected Vector secureProduct(Vector v) {
401 int n = this.rows();
402 int m = this.columns();
403 double[] vectorComponents = new double[n];
404 for (int i = 0; i < n; i++) {
405 vectorComponents[i] = 0;
406 for (int j = 0; j < m; j++)
407 vectorComponents[i] += components[i][j] * v.components[j];
408 }
409 return new Vector(vectorComponents);
410 }
411
412 /**
413 * Same as product(Matrix a), but without dimension checking.
414 *
415 * @param a MatrixAlgebra.Matrix
416 * @return MatrixAlgebra.Matrix product of the receiver with the
417 * supplied matrix
418 */
419 protected Matrix secureProduct(Matrix a) {
420 return new Matrix(productComponents(a));
421 }
422
423 /**
424 * Same as subtract ( Marix a), but without dimension checking.
425 *
426 * @param a MatrixAlgebra.Matrix
427 * @return MatrixAlgebra.Matrix
428 */
429 protected Matrix secureSubtract(Matrix a) {
430 return new Matrix(subtractComponents(a));
431 }
432
433 /**
434 * @param a MatrixAlgebra.Matrix
435 * @return MatrixAlgebra.Matrix subtract the supplied matrix to
436 * the receiver.
437 * @throws dr.math.matrixAlgebra.IllegalDimension
438 * if the supplied matrix
439 * does not have the same dimensions.
440 */
441 public Matrix subtract(Matrix a) throws IllegalDimension {
442 if (a.rows() != rows() || a.columns() != columns())
443 throw new IllegalDimension(
444 "Product error: cannot subtract a" + a.rows()
445 + " by " + a.columns() + " matrix to a "
446 + rows() + " by " + columns() + " matrix");
447 return new Matrix(subtractComponents(a));
448 }
449
450 /**
451 * @param a MatrixAlgebra.Matrix
452 * @return double[][]
453 */
454 protected double[][] subtractComponents(Matrix a) {
455 int n = this.rows();
456 int m = this.columns();
457 double[][] newComponents = new double[n][m];
458 for (int i = 0; i < n; i++) {
459 for (int j = 0; j < m; j++)
460 newComponents[i][j] = components[i][j] - a.components[i][j];
461 }
462 return newComponents;
463 }
464
465 /**
466 * @return double[][] a copy of the components of the receiver.
467 */
468 public double[][] toComponents() {
469 int n = rows();
470 int m = columns();
471 double[][] answer = new double[n][m];
472 for (int i = 0; i < n; i++) {
473 for (int j = 0; j < m; j++)
474 answer[i][j] = components[i][j];
475 }
476 return answer;
477 }
478
479 public double[] toVectorizedComponents() {
480 int n = rows();
481 int m = columns();
482 double[] answer = new double[n * m];
483 for (int i = 0; i < n; i++) {
484 for (int j = 0; j < m; j++)
485 answer[i * m + j] = components[i][j];
486 }
487 return answer;
488 }
489
490 /**
491 * Returns a string representation of the system.
492 *
493 * @return java.lang.String
494 */
495 public String toString() {
496 StringBuffer sb = new StringBuffer();
497 char[] separator = {'[', ' '};
498 int n = rows();
499 int m = columns();
500 for (int i = 0; i < n; i++) {
501 separator[0] = '{';
502 for (int j = 0; j < m; j++) {
503 sb.append(separator);
504 sb.append(components[i][j]);
505 separator[0] = ' ';
506 }
507 sb.append('}');
508 sb.append('\n');
509 }
510 return sb.toString();
511 }
512
513 public String toStringOctave() {
514 StringBuffer sb = new StringBuffer();
515 int n = rows();
516 int m = columns();
517 sb.append("[ ");
518 for (int i = 0; i < n; i++) {
519 for (int j = 0; j < m; j++) {
520 sb.append(components[i][j]);
521 if (j == m - 1) {
522 if (i == n - 1)
523 sb.append(" ");
524 else
525 sb.append("; ");
526 } else
527 sb.append(", ");
528 }
529 }
530 sb.append("]");
531 return sb.toString();
532 }
533
534 /**
535 * @return MatrixAlgebra.Matrix transpose of the receiver
536 */
537 public Matrix transpose() {
538 int n = rows();
539 int m = columns();
540 double[][] newComponents = new double[m][n];
541 for (int i = 0; i < n; i++) {
542 for (int j = 0; j < m; j++)
543 newComponents[j][i] = components[i][j];
544 }
545 return new Matrix(newComponents);
546 }
547
548 public Matrix extractRowsAndColumns(final int[] rowIndices, final int[] colIndices) {
549 return new Matrix(gatherRowsAndColumns(components, rowIndices, colIndices));
550 }
551
552 /**
553 * @return MatrixAlgebra.SymmetricMatrix the transposed product
554 * of the receiver with itself.
555 */
556 public SymmetricMatrix transposedProduct() {
557 return new SymmetricMatrix(transposedProductComponents(this));
558 }
559
560 /**
561 * @param a MatrixAlgebra.Matrix
562 * @return MatrixAlgebra.Matrix product of the tranpose of the
563 * receiver with the supplied matrix
564 * @throws dr.math.matrixAlgebra.IllegalDimension
565 * If the number of rows
566 * of the receiver are not equal to
567 * the number of rows of the supplied matrix.
568 */
569 public Matrix transposedProduct(Matrix a) throws IllegalDimension {
570 if (a.rows() != rows())
571 throw new IllegalDimension(
572 "Operation error: cannot multiply a tranposed "
573 + rows() + " by " + columns()
574 + " matrix with a " + a.rows() + " by "
575 + a.columns() + " matrix");
576 return new Matrix(transposedProductComponents(a));
577 }
578
579 /**
580 * @param a MatrixAlgebra.Matrix
581 * @return double[][] the components of the product of the
582 * transpose of the receiver
583 * with the supplied matrix.
584 */
585 protected double[][] transposedProductComponents(Matrix a) {
586 int p = this.rows();
587 int n = this.columns();
588 int m = a.columns();
589 double[][] newComponents = new double[n][m];
590 for (int i = 0; i < n; i++) {
591 for (int j = 0; j < m; j++) {
592 double sum = 0;
593 for (int k = 0; k < p; k++)
594 sum += components[k][i] * a.components[k][j];
595 newComponents[i][j] = sum;
596 }
597 }
598 return newComponents;
599 }
600
601 public static double[][] gatherRowsAndColumns(final double[][] source, final int[] rowIndices, final int[] colIndices) {
602 final int rowLength = rowIndices.length;
603 final int colLength = colIndices.length;
604 double[][] destination = new double[rowLength][colLength];
605
606 for (int i = 0; i < rowLength; ++i) {
607
608 final double[] in = source[rowIndices[i]];
609 final double[] out = destination[i];
610
611 for (int j = 0; j < colLength; ++j) {
612 out[j] = in[colIndices[j]];
613 }
614 }
615 return destination;
616 }
617
618 public static double[] gatherEntries(final double[] in, final int[] indices) {
619 final int indicesLength = indices.length;
620 final double[] out = new double[indicesLength];
621
622 for (int i = 0; i < indicesLength; ++i) {
623 out[i] = in[indices[i]];
624 }
625
626 return out;
627 }
628 }