3 import static org.testng.Assert.assertEquals;
4 import static org.testng.Assert.assertFalse;
5 import static org.testng.Assert.assertNotSame;
6 import static org.testng.Assert.assertNull;
7 import static org.testng.Assert.assertTrue;
8 import static org.testng.Assert.fail;
10 import java.util.Arrays;
11 import java.util.Random;
13 import org.testng.annotations.Test;
14 import org.testng.internal.junit.ArrayAsserts;
16 public class MatrixTest
18 final static double DELTA = 0.000001d;
20 @Test(groups = "Timing")
21 public void testPreMultiply_timing()
23 int rows = 50; // increase to stress test timing
25 double[][] d1 = new double[rows][cols];
26 double[][] d2 = new double[cols][rows];
27 Matrix m1 = new Matrix(d1);
28 Matrix m2 = new Matrix(d2);
29 long start = System.currentTimeMillis();
31 long elapsed = System.currentTimeMillis() - start;
32 System.out.println(rows + "x" + cols
33 + " multiplications of double took " + elapsed + "ms");
36 @Test(groups = "Functional")
37 public void testPreMultiply()
39 Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 } }); // 1x3
40 Matrix m2 = new Matrix(new double[][] { { 5 }, { 6 }, { 7 } }); // 3x1
43 * 1x3 times 3x1 is 1x1
44 * 2x5 + 3x6 + 4*7 = 56
46 MatrixI m3 = m2.preMultiply(m1);
47 assertEquals(m3.height(), 1);
48 assertEquals(m3.width(), 1);
49 assertEquals(m3.getValue(0, 0), 56d);
52 * 3x1 times 1x3 is 3x3
54 m3 = m1.preMultiply(m2);
55 assertEquals(m3.height(), 3);
56 assertEquals(m3.width(), 3);
57 assertEquals(Arrays.toString(m3.getRow(0)), "[10.0, 15.0, 20.0]");
58 assertEquals(Arrays.toString(m3.getRow(1)), "[12.0, 18.0, 24.0]");
59 assertEquals(Arrays.toString(m3.getRow(2)), "[14.0, 21.0, 28.0]");
63 groups = "Functional",
64 expectedExceptions = { IllegalArgumentException.class })
65 public void testPreMultiply_tooManyColumns()
67 Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 }, { 3, 4, 5 } }); // 2x3
70 * 2x3 times 2x3 invalid operation -
71 * multiplier has more columns than multiplicand has rows
74 fail("Expected exception");
78 groups = "Functional",
79 expectedExceptions = { IllegalArgumentException.class })
80 public void testPreMultiply_tooFewColumns()
82 Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 }, { 3, 4, 5 } }); // 2x3
85 * 3x2 times 3x2 invalid operation -
86 * multiplier has more columns than multiplicand has row
89 fail("Expected exception");
93 private boolean matrixEquals(Matrix m1, Matrix m2) {
94 if (m1.width() != m2.width() || m1.height() != m2.height())
98 for (int i = 0; i < m1.height(); i++)
100 if (!Arrays.equals(m1.getRow(i), m2.getRow(i)))
108 @Test(groups = "Functional")
109 public void testPostMultiply()
119 MatrixI m1 = new Matrix(new double[][] { { 2, 3 }, { 4, 5 } });
120 MatrixI m2 = new Matrix(new double[][] { { 10, 100 }, { 1000, 10000 } });
121 MatrixI m3 = m1.postMultiply(m2);
122 assertEquals(Arrays.toString(m3.getRow(0)), "[3020.0, 30200.0]");
123 assertEquals(Arrays.toString(m3.getRow(1)), "[5040.0, 50400.0]");
126 * also check m2.preMultiply(m1) - should be same as m1.postMultiply(m2)
128 m3 = m2.preMultiply(m1);
129 assertEquals(Arrays.toString(m3.getRow(0)), "[3020.0, 30200.0]");
130 assertEquals(Arrays.toString(m3.getRow(1)), "[5040.0, 50400.0]");
133 * m1 has more rows than columns
134 * (2).(10 100 1000) = (20 200 2000)
137 m1 = new Matrix(new double[][] { { 2 }, { 3 } });
138 m2 = new Matrix(new double[][] { { 10, 100, 1000 } });
139 m3 = m1.postMultiply(m2);
140 assertEquals(m3.height(), 2);
141 assertEquals(m3.width(), 3);
142 assertEquals(Arrays.toString(m3.getRow(0)), "[20.0, 200.0, 2000.0]");
143 assertEquals(Arrays.toString(m3.getRow(1)), "[30.0, 300.0, 3000.0]");
144 m3 = m2.preMultiply(m1);
145 assertEquals(m3.height(), 2);
146 assertEquals(m3.width(), 3);
147 assertEquals(Arrays.toString(m3.getRow(0)), "[20.0, 200.0, 2000.0]");
148 assertEquals(Arrays.toString(m3.getRow(1)), "[30.0, 300.0, 3000.0]");
151 * m1 has more columns than rows
152 * (2 3 4) . (5 4) = (56 25)
155 * [0, 0] = 2*5 + 3*6 + 4*7 = 56
156 * [0, 1] = 2*4 + 3*3 + 4*2 = 25
158 m1 = new Matrix(new double[][] { { 2, 3, 4 } });
159 m2 = new Matrix(new double[][] { { 5, 4 }, { 6, 3 }, { 7, 2 } });
160 m3 = m1.postMultiply(m2);
161 assertEquals(m3.height(), 1);
162 assertEquals(m3.width(), 2);
163 assertEquals(m3.getRow(0)[0], 56d);
164 assertEquals(m3.getRow(0)[1], 25d);
167 * and check premultiply equivalent
169 m3 = m2.preMultiply(m1);
170 assertEquals(m3.height(), 1);
171 assertEquals(m3.width(), 2);
172 assertEquals(m3.getRow(0)[0], 56d);
173 assertEquals(m3.getRow(0)[1], 25d);
176 @Test(groups = "Functional")
177 public void testCopy()
179 Random r = new Random();
182 double[][] in = new double[rows][cols];
184 for (int i = 0; i < rows; i++)
186 for (int j = 0; j < cols; j++)
188 in[i][j] = r.nextDouble();
191 Matrix m1 = new Matrix(in);
193 Matrix m2 = (Matrix) m1.copy();
194 assertNotSame(m1, m2);
195 assertTrue(matrixEquals(m1, m2));
200 * now add d and e vectors and recopy
202 m1.d = Arrays.copyOf(in[2], in[2].length);
203 m1.e = Arrays.copyOf(in[4], in[4].length);
204 m2 = (Matrix) m1.copy();
205 assertNotSame(m2.d, m1.d);
206 assertNotSame(m2.e, m1.e);
207 assertEquals(m2.d, m1.d);
208 assertEquals(m2.e, m1.e);
212 * main method extracted from Matrix
216 public static void main(String[] args) throws Exception
218 int n = Integer.parseInt(args[0]);
219 double[][] in = new double[n][n];
221 for (int i = 0; i < n; i++)
223 for (int j = 0; j < n; j++)
225 in[i][j] = Math.random();
229 Matrix origmat = new Matrix(in);
231 // System.out.println(" --- Original matrix ---- ");
232 // / origmat.print(System.out);
233 // System.out.println();
234 // System.out.println(" --- transpose matrix ---- ");
235 MatrixI trans = origmat.transpose();
237 // trans.print(System.out);
238 // System.out.println();
239 // System.out.println(" --- OrigT * Orig ---- ");
240 MatrixI symm = trans.postMultiply(origmat);
242 // symm.print(System.out);
243 // System.out.println();
244 // Copy the symmetric matrix for later
245 // Matrix origsymm = symm.copy();
247 // This produces the tridiagonal transformation matrix
248 // long tstart = System.currentTimeMillis();
251 // long tend = System.currentTimeMillis();
253 // System.out.println("Time take for tred = " + (tend-tstart) + "ms");
254 // System.out.println(" ---Tridiag transform matrix ---");
255 // symm.print(System.out);
256 // System.out.println();
257 // System.out.println(" --- D vector ---");
258 // symm.printD(System.out);
259 // System.out.println();
260 // System.out.println(" --- E vector ---");
261 // symm.printE(System.out);
262 // System.out.println();
263 // Now produce the diagonalization matrix
264 // tstart = System.currentTimeMillis();
266 // tend = System.currentTimeMillis();
268 // System.out.println("Time take for tqli = " + (tend-tstart) + " ms");
269 // System.out.println(" --- New diagonalization matrix ---");
270 // symm.print(System.out);
271 // System.out.println();
272 // System.out.println(" --- D vector ---");
273 // symm.printD(System.out);
274 // System.out.println();
275 // System.out.println(" --- E vector ---");
276 // symm.printE(System.out);
277 // System.out.println();
278 // System.out.println(" --- First eigenvector --- ");
279 // double[] eigenv = symm.getColumn(0);
280 // for (int i=0; i < eigenv.length;i++) {
281 // Format.print(System.out,"%15.4f",eigenv[i]);
283 // System.out.println();
284 // double[] neigenv = origsymm.vectorPostMultiply(eigenv);
285 // for (int i=0; i < neigenv.length;i++) {
286 // Format.print(System.out,"%15.4f",neigenv[i]/symm.d[0]);
288 // System.out.println();
291 @Test(groups = "Timing")
292 public void testSign()
294 assertEquals(Matrix.sign(-1, -2), -1d);
295 assertEquals(Matrix.sign(-1, 2), 1d);
296 assertEquals(Matrix.sign(-1, 0), 1d);
297 assertEquals(Matrix.sign(1, -2), -1d);
298 assertEquals(Matrix.sign(1, 2), 1d);
299 assertEquals(Matrix.sign(1, 0), 1d);
303 * Helper method to make values for a sparse, pseudo-random symmetric matrix
308 * one in 'occupancy' entries will be non-zero
311 public double[][] getSparseValues(int rows, int cols, int occupancy)
313 Random r = new Random(1729);
316 * generate whole number values between -12 and +12
317 * (to mimic score matrices used in Jalview)
319 double[][] d = new double[rows][cols];
321 for (int i = 0; i < rows; i++)
323 if (++m % occupancy == 0)
325 d[i][i] = r.nextInt() % 13; // diagonal
327 for (int j = 0; j < i; j++)
329 if (++m % occupancy == 0)
331 d[i][j] = r.nextInt() % 13;
341 * Verify that the results of method tred() are the same if the calculation is
344 @Test(groups = "Functional")
345 public void testTred_reproducible()
348 * make a pseudo-random symmetric matrix as required for tred/tqli
352 double[][] d = getSparseValues(rows, cols, 3);
355 * make a copy of the values so m1, m2 are not
358 double[][] d1 = new double[rows][cols];
359 for (int row = 0; row < rows; row++)
361 for (int col = 0; col < cols; col++)
363 d1[row][col] = d[row][col];
366 Matrix m1 = new Matrix(d);
367 Matrix m2 = new Matrix(d1);
368 assertMatricesMatch(m1, m2); // sanity check
371 assertMatricesMatch(m1, m2);
374 public static void assertMatricesMatch(MatrixI m1, MatrixI m2)
376 if (m1.height() != m2.height())
378 fail("height mismatch");
380 if (m1.width() != m2.width())
382 fail("width mismatch");
384 for (int row = 0; row < m1.height(); row++)
386 for (int col = 0; col < m1.width(); col++)
388 double v2 = m2.getValue(row, col);
389 double v1 = m1.getValue(row, col);
390 if (Math.abs(v1 - v2) > DELTA)
392 fail(String.format("At [%d, %d] %f != %f", row, col, v1, v2));
396 ArrayAsserts.assertArrayEquals("D vector", m1.getD(), m2.getD(),
398 ArrayAsserts.assertArrayEquals("E vector", m1.getE(), m2.getE(),
402 @Test(groups = "Functional")
403 public void testFindMinMax()
408 Matrix m = new Matrix(new double[][] { {} });
409 assertNull(m.findMinMax());
414 double[][] vals = new double[2][];
415 vals[0] = new double[] {7d, 1d, -2.3d};
416 vals[1] = new double[] {-12d, 94.3d, -102.34d};
417 m = new Matrix(vals);
418 double[] minMax = m.findMinMax();
419 assertEquals(minMax[0], -102.34d);
420 assertEquals(minMax[1], 94.3d);
423 @Test(groups = { "Functional", "Timing" })
424 public void testFindMinMax_timing()
426 Random r = new Random();
427 int size = 1000; // increase to stress test timing
428 double[][] vals = new double[size][size];
429 double max = -Double.MAX_VALUE;
430 double min = Double.MAX_VALUE;
431 for (int i = 0; i < size; i++)
433 vals[i] = new double[size];
434 for (int j = 0; j < size; j++)
436 // use nextLong rather than nextDouble to include negative values
437 double d = r.nextLong();
449 Matrix m = new Matrix(vals);
450 long now = System.currentTimeMillis();
451 double[] minMax = m.findMinMax();
452 System.out.println(String.format("findMinMax for %d x %d took %dms",
453 size, size, (System.currentTimeMillis() - now)));
454 assertEquals(minMax[0], min);
455 assertEquals(minMax[1], max);
459 * Test range reversal with maximum value becoming zero
461 @Test(groups = "Functional")
462 public void testReverseRange_maxToZero()
464 Matrix m1 = new Matrix(
465 new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
468 * subtract all from max: range -3.4 to 15 becomes 18.4 to 0
470 m1.reverseRange(true);
471 assertEquals(m1.getValue(0, 0), 13d, DELTA);
472 assertEquals(m1.getValue(0, 1), 11.5d, DELTA);
473 assertEquals(m1.getValue(0, 2), 11d, DELTA);
474 assertEquals(m1.getValue(1, 0), 18.4d, DELTA);
475 assertEquals(m1.getValue(1, 1), 11d, DELTA);
476 assertEquals(m1.getValue(1, 2), 0d, DELTA);
479 * repeat operation - range is now 0 to 18.4
481 m1.reverseRange(true);
482 assertEquals(m1.getValue(0, 0), 5.4d, DELTA);
483 assertEquals(m1.getValue(0, 1), 6.9d, DELTA);
484 assertEquals(m1.getValue(0, 2), 7.4d, DELTA);
485 assertEquals(m1.getValue(1, 0), 0d, DELTA);
486 assertEquals(m1.getValue(1, 1), 7.4d, DELTA);
487 assertEquals(m1.getValue(1, 2), 18.4d, DELTA);
491 * Test range reversal with minimum and maximum values swapped
493 @Test(groups = "Functional")
494 public void testReverseRange_swapMinMax()
496 Matrix m1 = new Matrix(
497 new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
500 * swap all values in min-max range
501 * = subtract from (min + max = 11.6)
502 * range -3.4 to 15 becomes 18.4 to -3.4
504 m1.reverseRange(false);
505 assertEquals(m1.getValue(0, 0), 9.6d, DELTA);
506 assertEquals(m1.getValue(0, 1), 8.1d, DELTA);
507 assertEquals(m1.getValue(0, 2), 7.6d, DELTA);
508 assertEquals(m1.getValue(1, 0), 15d, DELTA);
509 assertEquals(m1.getValue(1, 1), 7.6d, DELTA);
510 assertEquals(m1.getValue(1, 2), -3.4d, DELTA);
513 * repeat operation - original values restored
515 m1.reverseRange(false);
516 assertEquals(m1.getValue(0, 0), 2d, DELTA);
517 assertEquals(m1.getValue(0, 1), 3.5d, DELTA);
518 assertEquals(m1.getValue(0, 2), 4d, DELTA);
519 assertEquals(m1.getValue(1, 0), -3.4d, DELTA);
520 assertEquals(m1.getValue(1, 1), 4d, DELTA);
521 assertEquals(m1.getValue(1, 2), 15d, DELTA);
524 @Test(groups = "Functional")
525 public void testMultiply()
527 Matrix m = new Matrix(new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
529 assertEquals(m.getValue(0, 0), 4d, DELTA);
530 assertEquals(m.getValue(0, 1), 7d, DELTA);
531 assertEquals(m.getValue(0, 2), 8d, DELTA);
532 assertEquals(m.getValue(1, 0), -6.8d, DELTA);
533 assertEquals(m.getValue(1, 1), 8d, DELTA);
534 assertEquals(m.getValue(1, 2), 30d, DELTA);
537 @Test(groups = "Functional")
538 public void testConstructor()
540 double[][] values = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
541 Matrix m = new Matrix(values);
542 assertEquals(m.getValue(0, 0), 1d, DELTA);
545 * verify the matrix has a copy of the original array
547 assertNotSame(values[0], m.getRow(0));
549 assertEquals(m.getValue(0, 0), 1d, DELTA); // unchanged
552 @Test(groups = "Functional")
553 public void testEquals()
555 double[][] values = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
556 Matrix m1 = new Matrix(values);
557 double[][] values2 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
558 Matrix m2 = new Matrix(values2);
560 double delta = 0.0001d;
561 assertTrue(m1.equals(m1, delta));
562 assertTrue(m1.equals(m2, delta));
563 assertTrue(m2.equals(m1, delta));
565 double[][] values3 = new double[][] { { 1, 2, 3 }, { 4, 5, 7 } };
566 m2 = new Matrix(values3);
567 assertFalse(m1.equals(m2, delta));
568 assertFalse(m2.equals(m1, delta));
570 // must be same shape
571 values2 = new double[][] { { 1, 2, 3 } };
572 m2 = new Matrix(values2);
573 assertFalse(m2.equals(m1, delta));
575 assertFalse(m1.equals(null, delta));