Debian Codegraph @

src/dr/matrix/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.matrix;
27
28 /**
29 * An inteface for an immutable matrix.
30 *
31 * @version $Id: Matrix.java,v 1.8 2006/06/18 16:20:58 alexei Exp $
32 *
33 * @author Andrew Rambaut
34 */
35 public interface Matrix {
36
37 //***************************************************
38 // Getter methods
39 //***************************************************
40
41 /**
42 * @return the number of rows
43 */
44 int getRowCount();
45
46 /**
47 * @return the number of columns
48 */
49 int getColumnCount();
50
51 /**
52 * @return the number of elements
53 */
54 int getElementCount();
55
56 /**
57 * @return the number of elements in 1 triangle. Square matrices only.
58 */
59 int getTriangleCount() throws Matrix.NotSquareException;
60
61 /**
62 * @return the number of elements in the diagonal. Square matrices only.
63 */
64 int getDiagonalCount() throws Matrix.NotSquareException;
65
66 /**
67 * @return the matrix elements as a 1D array
68 */
69 double[] getElements();
70
71 /**
72 * @return the matrix elements as a 2D array
73 */
74 double[][] getElements2D();
75
76 /**
77 * @return the upper triangle elements as a 1D array
78 */
79 double[] getUpperTriangle() throws Matrix.NotSquareException;
80
81 /**
82 * @return the upper triangle elements as a 1D array
83 */
84 double[] getLowerTriangle() throws Matrix.NotSquareException;
85
86 /**
87 * @return the diagonal elements as a 1D array
88 */
89 double[] getDiagonal() throws Matrix.NotSquareException;
90
91 /**
92 * @return an element
93 */
94 double getElement(int row, int column);
95
96 /**
97 * @return the ith element
98 */
99 double getElement(int index);
100
101 /**
102 * @return a single row
103 */
104 double[] getRow(int row);
105
106 /**
107 * @return a single column
108 */
109 double[] getColumn(int column);
110
111 /**
112 * @return the minimum value in the matrix
113 */
114 double getMinValue();
115
116 /**
117 * @return the minimum value in the matrix
118 */
119 double getMaxValue();
120
121 /**
122 * @return whether matrix is square
123 */
124 boolean getIsSquare();
125
126 /**
127 * @return whether matrix is symmetric
128 */
129 boolean getIsSymmetric() throws Matrix.NotSquareException;
130
131 /**
132 * @return an id for row
133 */
134 String getRowId(int row);
135
136 /**
137 * @return an id for row
138 */
139 String getColumnId(int column);
140
141
142 //***************************************************
143 // Exception classes
144 //***************************************************
145
146 /**
147 * The base matrix exception
148 */
149 public class MatrixException extends Exception {
150 /**
151 *
152 */
153 private static final long serialVersionUID = -5904166681730282246L;
154 MatrixException() { super(); }
155 MatrixException(String message) { super(message); }
156 }
157
158 /**
159 * Thrown when the matrix should be square but it's not
160 */
161 public class NotSquareException extends MatrixException {
162
163 /**
164 *
165 */
166 private static final long serialVersionUID = 5121968928197320497L; }
167
168 /**
169 * Thrown when the dimensions of a matrix are wrong
170 */
171 public class WrongDimensionException extends MatrixException {
172 /**
173 *
174 */
175 private static final long serialVersionUID = -1799942797975356399L;
176 WrongDimensionException() { super(); }
177 WrongDimensionException(String message) { super(message); }
178 }
179
180 //***************************************************
181 // Util class
182 //***************************************************
183
184 /**
185 * Static class providing maths and utility functions
186 */
187 public static class Util {
188
189 /**
190 * @return the dot product of a & b
191 */
192 public static double dotProduct(Matrix a, Matrix b) {
193 throw new RuntimeException("not implemented yet");
194 }
195
196 /**
197 * the cross product of a & b storing in result
198 */
199 public static void product(Matrix a, Matrix b, MutableMatrix result) throws Matrix.WrongDimensionException {
200 int rca = a.getRowCount();
201 int cca = a.getColumnCount();
202
203 int rcb = b.getRowCount();
204 int ccb = b.getColumnCount();
205
206 if (cca != rcb)
207 throw new Matrix.WrongDimensionException("column count of matrix a = " + cca + ", row count of matrix b = " + rcb);
208
209 result.setDimension(rca, ccb);
210
211 for (int r = 0; r < rca; r++) {
212 for (int c = 0; c < ccb; c++) {
213 double sum = 0;
214 for (int i = 0; i < cca; i++) {
215 sum += a.getElement(r, i) * b.getElement(i, c);
216 }
217 result.setElement(r, c, sum);
218 }
219 }
220 }
221
222 /**
223 * the kronecker product of a & b storing in result
224 */
225 public static void kroneckerProduct(Matrix a, Matrix b, MutableMatrix result) {
226 int ra, ca, rb, cb;
227 int rca = a.getRowCount();
228 int cca = a.getColumnCount();
229 int rcb = b.getRowCount();
230 int ccb = b.getColumnCount();
231
232 for (rb = 0; rb < rcb; rb++) {
233 for (cb = 0; cb < ccb; cb++) {
234 for (ra = 0; ra < rca; ra++) {
235 for (ca = 0; ca < cca; ca++) {
236 result.setElement(rb*rca + ra, cb * cca + ca,
237 a.getElement(ra, ca) * b.getElement(rb, cb));
238 }
239 }
240
241 }
242 }
243 }
244
245 /**
246 * the adds a to b storing in result
247 */
248 public static void add(Matrix a, Matrix b, MutableMatrix result) throws Matrix.WrongDimensionException {
249 int rca = a.getRowCount();
250 int cca = a.getColumnCount();
251
252 if (rca != b.getRowCount() || cca != b.getColumnCount())
253 throw new Matrix.WrongDimensionException();
254
255 result.setDimension(rca, cca);
256
257 for (int r = 0; r < rca; r++) {
258 for (int c = 0; c < cca; c++) {
259 result.setElement(r, c, a.getElement(r, c) + b.getElement(r, c));
260 }
261 }
262 }
263
264 /**
265 * the subtracts b from a storing in result
266 */
267 public static void subtract(Matrix a, Matrix b, MutableMatrix result) throws Matrix.WrongDimensionException {
268 int rca = a.getRowCount();
269 int cca = a.getColumnCount();
270
271 if (rca != b.getRowCount() || cca != b.getColumnCount())
272 throw new Matrix.WrongDimensionException();
273
274 result.setDimension(rca, cca);
275
276 for (int r = 0; r < rca; r++) {
277 for (int c = 0; c < cca; c++) {
278 result.setElement(r, c, a.getElement(r, c) - b.getElement(r, c));
279 }
280 }
281 }
282
283 /**
284 * @return the determinant of matrix
285 */
286 public static double det(Matrix matrix) throws Matrix.NotSquareException {
287
288 int n = matrix.getRowCount();
289 int col = matrix.getColumnCount();
290 if (n != col) throw new Matrix.NotSquareException();
291
292 double[][] D = new double[n][n];
293
294 for (int i =0; i < n; i++) {
295 for (int j=0; j < n; j++) {
296 D[i][j] = matrix.getElement(i, j);
297 }
298 }
299
300 org.apache.commons.math.linear.RealMatrixImpl RM = new org.apache.commons.math.linear.RealMatrixImpl(D);
301 return RM.getDeterminant();
302 }
303
304 /**
305 * @return the log of the determinant of matrix
306 */
307 public static double logDet(Matrix matrix) throws Matrix.NotSquareException {
308 throw new RuntimeException("not implemented yet");
309 }
310
311 /**
312 * invert the matrix
313 * code modified from: http://www.nauticom.net/www/jdtaft/JavaMatrix.htm
314 *
315 * This is the Java source code for a matrix inversion routine which uses
316 * Gaussian reduction. The matrix to be inverted is assumed square and
317 * nonsingular. The matrix order is n. NOTE: row 0 and column 0 of the
318 * array D are NOT used. Matrix D is sized as D[n+1][2*n+2], with the
319 * left half (excluding row 0 and column 0) initialized to the matrix to
320 * be inverted. Upon completion the left half is reduced to an identity
321 * matrix and the right half is reduced to the inverse of the original matrix.
322 * The inversion routine initializes the right half of D to an identity matrix.
323 * @fixme Shouldn't this throw an exception if matrix is singular?
324 */
325 public static void invert(MutableMatrix matrix) throws Matrix.NotSquareException {
326
327 int n = matrix.getRowCount();
328 int col = matrix.getColumnCount();
329 if (n != col) throw new Matrix.NotSquareException();
330
331 double[][] D = new double[n+1][n*2+2];
332
333 for (int i =0; i < n; i++) {
334 for (int j=0; j < n; j++) {
335 D[i+1][j+1] = matrix.getElement(i, j);
336 }
337 }
338
339 double alpha;
340 double beta;
341 int i;
342 int j;
343 int k;
344 // int error;
345
346 // error = 0;
347 int n2 = 2*n;
348
349 /* init the reduction matrix */
350 for( i = 1; i <= n; i++ )
351 {
352 for( j = 1; j <= n; j++ )
353 {
354 D[i][j+n] = 0.;
355 }
356 D[i][i+n] = 1.0;
357 }
358
359 /* perform the reductions */
360 for( i = 1; i <= n; i++ )
361 {
362 alpha = D[i][i];
363 if( alpha == 0.0 ) /* error - singular matrix */
364 {
365 // error = 1;
366 break;
367 }
368 else
369 {
370 for( j = 1; j <= n2; j++ )
371 {
372 D[i][j] = D[i][j]/alpha;
373 }
374 for( k = 1; k <= n; k++ )
375 {
376 if( (k-i) != 0 )
377 {
378 beta = D[k][i];
379 for( j = 1; j <= n2; j++ )
380 {
381 D[k][j] = D[k][j] - beta*D[i][j];
382 }
383 }
384 }
385 }
386 }
387
388 for (i =0; i < n; i++) {
389 for (j=0; j < n; j++) {
390 matrix.setElement(i, j, D[i+1][j+n+1]);
391 }
392 }
393 }
394
395 /**
396 * invert the product of a and b storing int result
397 */
398 public static void invert(Matrix a, Matrix b, MutableMatrix result)
399 throws Matrix.NotSquareException, Matrix.WrongDimensionException
400 {
401 throw new RuntimeException("not implemented yet");
402 }
403
404 /**
405 * raise the matrix to scalar d
406 */
407 public static void raise(Matrix matrix, double d, MutableMatrix result) throws Matrix.NotSquareException {
408 throw new RuntimeException("not implemented yet");
409 }
410
411 public static Matrix createColumnVector(double[] v) { return new ColumnVector(v); }
412
413 public static Matrix createRowVector(double[] v) { return new RowVector(v); }
414
415 public static MutableMatrix createMutableMatrix(double[][] values) { return new ConcreteMatrix(values); }
416
417 }
418
419 //***************************************************
420 // AbstractMatrix class
421 //***************************************************
422
423 /**
424 * Abstract class providing a base for immutable matrix implementations. At the
425 * very least, classes derived from this need only implement
426 * getRowCount(), getColumnCount(), and getElement(int, int).
427 *
428 * By using these access methods, it will not be very efficient.
429 */
430 public abstract class AbstractMatrix implements Matrix {
431
432 //***************************************************
433 // Getter methods
434 //***************************************************
435
436 /**
437 * @return the number of elements
438 */
439 public int getElementCount() {
440 return getRowCount() * getColumnCount();
441 }
442
443 /**
444 * @return the number of elements in 1 triangle. Square matrices only.
445 */
446 public int getTriangleCount() throws Matrix.NotSquareException {
447 if (!getIsSquare())
448 throw new Matrix.NotSquareException();
449
450 int dim = getRowCount();
451 return ((dim - 1) * dim) / 2;
452 }
453
454 /**
455 * @return the number of elements in the diagonal. Square matrices only.
456 */
457 public int getDiagonalCount() throws Matrix.NotSquareException {
458 if (!getIsSquare())
459 throw new Matrix.NotSquareException();
460
461 return getRowCount();
462 }
463
464 /**
465 * @return the matrix elements as a 1D array
466 */
467 public double[] getElements() {
468 double[] values = new double[getElementCount()];
469 int k = 0;
470 int rc = getRowCount();
471 int cc = getColumnCount();
472 for (int r = 0; r < rc; r++) {
473 for (int c = 0; c < cc; c++) {
474 values[k] = getElement(r, c);
475 k++;
476 }
477 }
478 return values;
479 }
480
481 /**
482 * @return the matrix elements as a 2D array
483 */
484 public double[][] getElements2D() {
485
486 double[][] values = new double[getRowCount()][getColumnCount()];
487 int rc = getRowCount();
488 int cc = getColumnCount();
489 for (int r = 0; r < rc; r++) {
490 for (int c = 0; c < cc; c++) {
491 values[r][c] = getElement(r, c);
492 }
493 }
494
495 return values;
496 }
497
498 /**
499 * @return the ith element
500 */
501 public double getElement(int index) {
502 int r = index / getColumnCount();
503 int c = index % getColumnCount();
504 return getElement(r, c);
505 }
506
507 /**
508 * @return the upper triangle elements as a 1D array
509 */
510 public double[] getUpperTriangle() throws Matrix.NotSquareException {
511 if (!getIsSquare())
512 throw new Matrix.NotSquareException();
513
514 double[] values = new double[getTriangleCount()];
515 int k = 0;
516 int dim = getRowCount();
517 for (int r = 0; r < dim; r++) {
518 for (int c = r + 1; c < dim; c++) {
519 values[k] = getElement(r, c);
520 k++;
521 }
522 }
523
524 return values;
525 }
526
527 /**
528 * @return the upper triangle elements as a 1D array
529 */
530 public double[] getLowerTriangle() throws Matrix.NotSquareException {
531 if (!getIsSquare())
532 throw new Matrix.NotSquareException();
533
534 double[] values = new double[getTriangleCount()];
535 int k = 0;
536 int dim = getRowCount();
537 for (int r = 0; r < dim; r++) {
538 for (int c = 0; c < r; c++) {
539 values[k] = getElement(r, c);
540 k++;
541 }
542 }
543
544 return values;
545 }
546
547
548 /**
549 * @return the diagonal elements as a 1D array
550 */
551 public double[] getDiagonal() throws Matrix.NotSquareException {
552 if (!getIsSquare())
553 throw new Matrix.NotSquareException();
554
555 int dim = getRowCount();
556 double[] values = new double[dim];
557 for (int r = 0; r < dim; r++) {
558 values[r] = getElement(r, r);
559 }
560
561 return values;
562 }
563
564 /**
565 * @return a single row
566 */
567 public double[] getRow(int row) {
568 int dim = getColumnCount();
569 double[] values = new double[dim];
570 for (int c = 0; c < dim; c++) {
571 values[c] = getElement(row, c);
572 }
573
574 return values;
575 }
576
577 /**
578 * @return a single column
579 */
580 public double[] getColumn(int column) {
581 int dim = getRowCount();
582 double[] values = new double[dim];
583 for (int r = 0; r < dim; r++) {
584 values[r] = getElement(r, column);
585 }
586
587 return values;
588 }
589
590 /**
591 * @return the minimum value in the matrix
592 */
593 public double getMinValue() {
594 double value, minValue = getElement(0);
595 int n = getElementCount();
596
597 for (int i = 1; i < n; i++) {
598 value = getElement(i);
599 if (value < minValue)
600 minValue = value;
601 }
602
603 return minValue;
604 }
605
606 /**
607 * @return the minimum value in the matrix
608 */
609 public double getMaxValue() {
610 double value, maxValue = getElement(0);
611 int n = getElementCount();
612
613 for (int i = 1; i < n; i++) {
614 value = getElement(i);
615 if (value > maxValue)
616 maxValue = value;
617 }
618
619 return maxValue;
620 }
621
622 /**
623 * @return whether matrix is square
624 */
625 public boolean getIsSquare() {
626 return getRowCount() == getColumnCount();
627 }
628
629 /**
630 * @return whether matrix is symmetric
631 */
632 public boolean getIsSymmetric() throws Matrix.NotSquareException {
633 if (!getIsSquare())
634 throw new Matrix.NotSquareException();
635
636 int dim = getRowCount();
637 for (int r = 0; r < dim; r++) {
638 for (int c = r + 1; r < dim; r++) {
639 if (getElement(r, c) != getElement(c, r))
640 return false;
641 }
642 }
643
644 return true;
645 }
646
647 /**
648 * @return an id for row
649 */
650 public String getRowId(int row) { return null; }
651
652 /**
653 * @return an id for row
654 */
655 public String getColumnId(int column) { return null; }
656
657
658 }
659
660 }
661
662 class ColumnVector extends Matrix.AbstractMatrix {
663
664 public ColumnVector(double[] v) {
665
666 this.values = new double[v.length];
667 for (int i = 0; i < values.length; i++) {
668 values[i] = v[i];
669 }
670 }
671
672 public final int getColumnCount() { return 1; }
673 public final int getRowCount() { return values.length; }
674 public final double getElement(int i, int j) { return values[i]; }
675
676 double[] values = null;
677 }
678
679 class RowVector extends Matrix.AbstractMatrix {
680
681 public RowVector(double[] v) {
682
683 this.values = new double[v.length];
684 for (int i = 0; i < values.length; i++) {
685 values[i] = v[i];
686 }
687 }
688
689 public final int getRowCount() { return 1; }
690 public final int getColumnCount() { return values.length; }
691 public final double getElement(int i, int j) { return values[j]; }
692
693 double[] values = null;
694 }