JAL-1767 unit test for save and restore PCA
[jalview.git] / test / jalview / math / MatrixTest.java
1 package jalview.math;
2
3 import static org.testng.Assert.assertEquals;
4 import static org.testng.Assert.assertNotSame;
5 import static org.testng.Assert.assertNull;
6 import static org.testng.Assert.assertTrue;
7 import static org.testng.Assert.fail;
8
9 import java.util.Arrays;
10 import java.util.Random;
11
12 import org.testng.annotations.Test;
13 import org.testng.internal.junit.ArrayAsserts;
14
15 public class MatrixTest
16 {
17   final static double DELTA = 0.000001d;
18
19   @Test(groups = "Timing")
20   public void testPreMultiply_timing()
21   {
22     int rows = 50; // increase to stress test timing
23     int cols = 100;
24     double[][] d1 = new double[rows][cols];
25     double[][] d2 = new double[cols][rows];
26     Matrix m1 = new Matrix(d1);
27     Matrix m2 = new Matrix(d2);
28     long start = System.currentTimeMillis();
29     m1.preMultiply(m2);
30     long elapsed = System.currentTimeMillis() - start;
31     System.out.println(rows + "x" + cols
32             + " multiplications of double took " + elapsed + "ms");
33   }
34
35   @Test(groups = "Functional")
36   public void testPreMultiply()
37   {
38     Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 } }); // 1x3
39     Matrix m2 = new Matrix(new double[][] { { 5 }, { 6 }, { 7 } }); // 3x1
40
41     /*
42      * 1x3 times 3x1 is 1x1
43      * 2x5 + 3x6 + 4*7 =  56
44      */
45     MatrixI m3 = m2.preMultiply(m1);
46     assertEquals(m3.height(), 1);
47     assertEquals(m3.width(), 1);
48     assertEquals(m3.getValue(0, 0), 56d);
49
50     /*
51      * 3x1 times 1x3 is 3x3
52      */
53     m3 = m1.preMultiply(m2);
54     assertEquals(m3.height(), 3);
55     assertEquals(m3.width(), 3);
56     assertEquals(Arrays.toString(m3.getRow(0)), "[10.0, 15.0, 20.0]");
57     assertEquals(Arrays.toString(m3.getRow(1)), "[12.0, 18.0, 24.0]");
58     assertEquals(Arrays.toString(m3.getRow(2)), "[14.0, 21.0, 28.0]");
59   }
60
61   @Test(
62     groups = "Functional",
63     expectedExceptions = { IllegalArgumentException.class })
64   public void testPreMultiply_tooManyColumns()
65   {
66     Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 }, { 3, 4, 5 } }); // 2x3
67
68     /*
69      * 2x3 times 2x3 invalid operation - 
70      * multiplier has more columns than multiplicand has rows
71      */
72     m1.preMultiply(m1);
73     fail("Expected exception");
74   }
75
76   @Test(
77     groups = "Functional",
78     expectedExceptions = { IllegalArgumentException.class })
79   public void testPreMultiply_tooFewColumns()
80   {
81     Matrix m1 = new Matrix(new double[][] { { 2, 3, 4 }, { 3, 4, 5 } }); // 2x3
82
83     /*
84      * 3x2 times 3x2 invalid operation - 
85      * multiplier has more columns than multiplicand has row
86      */
87     m1.preMultiply(m1);
88     fail("Expected exception");
89   }
90   
91   
92   private boolean matrixEquals(Matrix m1, Matrix m2) {
93     if (m1.width() != m2.width() || m1.height() != m2.height())
94     {
95       return false;
96     }
97     for (int i = 0; i < m1.height(); i++)
98     {
99       if (!Arrays.equals(m1.getRow(i), m2.getRow(i)))
100       {
101         return false;
102       }
103     }
104     return true;
105   }
106
107   @Test(groups = "Functional")
108   public void testPostMultiply()
109   {
110     /*
111      * Square matrices
112      * (2 3) . (10   100)
113      * (4 5)   (1000 10000)
114      * =
115      * (3020 30200)
116      * (5040 50400)
117      */
118     MatrixI m1 = new Matrix(new double[][] { { 2, 3 }, { 4, 5 } });
119     MatrixI m2 = new Matrix(new double[][] { { 10, 100 }, { 1000, 10000 } });
120     MatrixI m3 = m1.postMultiply(m2);
121     assertEquals(Arrays.toString(m3.getRow(0)), "[3020.0, 30200.0]");
122     assertEquals(Arrays.toString(m3.getRow(1)), "[5040.0, 50400.0]");
123
124     /*
125      * also check m2.preMultiply(m1) - should be same as m1.postMultiply(m2) 
126      */
127     m3 = m2.preMultiply(m1);
128     assertEquals(Arrays.toString(m3.getRow(0)), "[3020.0, 30200.0]");
129     assertEquals(Arrays.toString(m3.getRow(1)), "[5040.0, 50400.0]");
130
131     /*
132      * m1 has more rows than columns
133      * (2).(10 100 1000) = (20 200 2000)
134      * (3)                 (30 300 3000)
135      */
136     m1 = new Matrix(new double[][] { { 2 }, { 3 } });
137     m2 = new Matrix(new double[][] { { 10, 100, 1000 } });
138     m3 = m1.postMultiply(m2);
139     assertEquals(m3.height(), 2);
140     assertEquals(m3.width(), 3);
141     assertEquals(Arrays.toString(m3.getRow(0)), "[20.0, 200.0, 2000.0]");
142     assertEquals(Arrays.toString(m3.getRow(1)), "[30.0, 300.0, 3000.0]");
143     m3 = m2.preMultiply(m1);
144     assertEquals(m3.height(), 2);
145     assertEquals(m3.width(), 3);
146     assertEquals(Arrays.toString(m3.getRow(0)), "[20.0, 200.0, 2000.0]");
147     assertEquals(Arrays.toString(m3.getRow(1)), "[30.0, 300.0, 3000.0]");
148
149     /*
150      * m1 has more columns than rows
151      * (2 3 4) . (5 4) = (56 25)
152      *           (6 3) 
153      *           (7 2)
154      * [0, 0] = 2*5 + 3*6 + 4*7 = 56
155      * [0, 1] = 2*4 + 3*3 + 4*2 = 25  
156      */
157     m1 = new Matrix(new double[][] { { 2, 3, 4 } });
158     m2 = new Matrix(new double[][] { { 5, 4 }, { 6, 3 }, { 7, 2 } });
159     m3 = m1.postMultiply(m2);
160     assertEquals(m3.height(), 1);
161     assertEquals(m3.width(), 2);
162     assertEquals(m3.getRow(0)[0], 56d);
163     assertEquals(m3.getRow(0)[1], 25d);
164
165     /*
166      * and check premultiply equivalent
167      */
168     m3 = m2.preMultiply(m1);
169     assertEquals(m3.height(), 1);
170     assertEquals(m3.width(), 2);
171     assertEquals(m3.getRow(0)[0], 56d);
172     assertEquals(m3.getRow(0)[1], 25d);
173   }
174
175   @Test(groups = "Functional")
176   public void testCopy()
177   {
178     Random r = new Random();
179     int rows = 5;
180     int cols = 11;
181     double[][] in = new double[rows][cols];
182
183     for (int i = 0; i < rows; i++)
184     {
185       for (int j = 0; j < cols; j++)
186       {
187         in[i][j] = r.nextDouble();
188       }
189     }
190     Matrix m1 = new Matrix(in);
191
192     Matrix m2 = (Matrix) m1.copy();
193     assertNotSame(m1, m2);
194     assertTrue(matrixEquals(m1, m2));
195     assertNull(m2.d);
196     assertNull(m2.e);
197
198     /*
199      * now add d and e vectors and recopy
200      */
201     m1.d = Arrays.copyOf(in[2], in[2].length);
202     m1.e = Arrays.copyOf(in[4], in[4].length);
203     m2 = (Matrix) m1.copy();
204     assertNotSame(m2.d, m1.d);
205     assertNotSame(m2.e, m1.e);
206     assertEquals(m2.d, m1.d);
207     assertEquals(m2.e, m1.e);
208   }
209
210   /**
211    * main method extracted from Matrix
212    * 
213    * @param args
214    */
215   public static void main(String[] args) throws Exception
216   {
217     int n = Integer.parseInt(args[0]);
218     double[][] in = new double[n][n];
219   
220     for (int i = 0; i < n; i++)
221     {
222       for (int j = 0; j < n; j++)
223       {
224         in[i][j] = Math.random();
225       }
226     }
227   
228     Matrix origmat = new Matrix(in);
229   
230     // System.out.println(" --- Original matrix ---- ");
231     // / origmat.print(System.out);
232     // System.out.println();
233     // System.out.println(" --- transpose matrix ---- ");
234     MatrixI trans = origmat.transpose();
235   
236     // trans.print(System.out);
237     // System.out.println();
238     // System.out.println(" --- OrigT * Orig ---- ");
239     MatrixI symm = trans.postMultiply(origmat);
240   
241     // symm.print(System.out);
242     // System.out.println();
243     // Copy the symmetric matrix for later
244     // Matrix origsymm = symm.copy();
245   
246     // This produces the tridiagonal transformation matrix
247     // long tstart = System.currentTimeMillis();
248     symm.tred();
249   
250     // long tend = System.currentTimeMillis();
251   
252     // System.out.println("Time take for tred = " + (tend-tstart) + "ms");
253     // System.out.println(" ---Tridiag transform matrix ---");
254     // symm.print(System.out);
255     // System.out.println();
256     // System.out.println(" --- D vector ---");
257     // symm.printD(System.out);
258     // System.out.println();
259     // System.out.println(" --- E vector ---");
260     // symm.printE(System.out);
261     // System.out.println();
262     // Now produce the diagonalization matrix
263     // tstart = System.currentTimeMillis();
264     symm.tqli();
265     // tend = System.currentTimeMillis();
266   
267     // System.out.println("Time take for tqli = " + (tend-tstart) + " ms");
268     // System.out.println(" --- New diagonalization matrix ---");
269     // symm.print(System.out);
270     // System.out.println();
271     // System.out.println(" --- D vector ---");
272     // symm.printD(System.out);
273     // System.out.println();
274     // System.out.println(" --- E vector ---");
275     // symm.printE(System.out);
276     // System.out.println();
277     // System.out.println(" --- First eigenvector --- ");
278     // double[] eigenv = symm.getColumn(0);
279     // for (int i=0; i < eigenv.length;i++) {
280     // Format.print(System.out,"%15.4f",eigenv[i]);
281     // }
282     // System.out.println();
283     // double[] neigenv = origsymm.vectorPostMultiply(eigenv);
284     // for (int i=0; i < neigenv.length;i++) {
285     // Format.print(System.out,"%15.4f",neigenv[i]/symm.d[0]);
286     // }
287     // System.out.println();
288   }
289
290   @Test(groups = "Timing")
291   public void testSign()
292   {
293     assertEquals(Matrix.sign(-1, -2), -1d);
294     assertEquals(Matrix.sign(-1, 2), 1d);
295     assertEquals(Matrix.sign(-1, 0), 1d);
296     assertEquals(Matrix.sign(1, -2), -1d);
297     assertEquals(Matrix.sign(1, 2), 1d);
298     assertEquals(Matrix.sign(1, 0), 1d);
299   }
300
301   /**
302    * Helper method to make values for a sparse, pseudo-random symmetric matrix
303    * 
304    * @param rows
305    * @param cols
306    * @param occupancy
307    *          one in 'occupancy' entries will be non-zero
308    * @return
309    */
310   public double[][] getSparseValues(int rows, int cols, int occupancy)
311   {
312     Random r = new Random(1729);
313
314     /*
315      * generate whole number values between -12 and +12
316      * (to mimic score matrices used in Jalview)
317      */
318     double[][] d = new double[rows][cols];
319     int m = 0;
320     for (int i = 0; i < rows; i++)
321     {
322       if (++m % occupancy == 0)
323       {
324         d[i][i] = r.nextInt() % 13; // diagonal
325       }
326       for (int j = 0; j < i; j++)
327       {
328         if (++m % occupancy == 0)
329         {
330           d[i][j] = r.nextInt() % 13;
331           d[j][i] = d[i][j];
332         }
333       }
334     }
335     return d;
336   
337   }
338
339   /**
340    * Verify that the results of method tred() are the same if the calculation is
341    * redone
342    */
343   @Test(groups = "Functional")
344   public void testTred_reproducible()
345   {
346     /*
347      * make a pseudo-random symmetric matrix as required for tred/tqli
348      */
349     int rows = 10;
350     int cols = rows;
351     double[][] d = getSparseValues(rows, cols, 3);
352   
353     /*
354      * make a copy of the values so m1, m2 are not
355      * sharing arrays!
356      */
357     double[][] d1 = new double[rows][cols];
358     for (int row = 0; row < rows; row++)
359     {
360       for (int col = 0; col < cols; col++)
361       {
362         d1[row][col] = d[row][col];
363       }
364     }
365     Matrix m1 = new Matrix(d);
366     Matrix m2 = new Matrix(d1);
367     assertMatricesMatch(m1, m2); // sanity check
368     m1.tred();
369     m2.tred();
370     assertMatricesMatch(m1, m2);
371   }
372
373   public static void assertMatricesMatch(MatrixI m1, MatrixI m2)
374   {
375     if (m1.height() != m2.height())
376     {
377       fail("height mismatch");
378     }
379     if (m1.width() != m2.width())
380     {
381       fail("width mismatch");
382     }
383     for (int row = 0; row < m1.height(); row++)
384     {
385       for (int col = 0; col < m1.width(); col++)
386       {
387         double v2 = m2.getValue(row, col);
388         double v1 = m1.getValue(row, col);
389         if (Math.abs(v1 - v2) > DELTA)
390         {
391           fail(String.format("At [%d, %d] %f != %f", row, col, v1, v2));
392         }
393       }
394     }
395     ArrayAsserts.assertArrayEquals("D vector", m1.getD(), m2.getD(),
396             0.00001d);
397     ArrayAsserts.assertArrayEquals("E vector", m1.getE(), m2.getE(),
398             0.00001d);
399   }
400
401   @Test(groups = "Functional")
402   public void testFindMinMax()
403   {
404     /*
405      * empty matrix case
406      */
407     Matrix m = new Matrix(new double[][] { {} });
408     assertNull(m.findMinMax());
409
410     /*
411      * normal case
412      */
413     double[][] vals = new double[2][];
414     vals[0] = new double[] {7d, 1d, -2.3d};
415     vals[1] = new double[] {-12d, 94.3d, -102.34d};
416     m = new Matrix(vals);
417     double[] minMax = m.findMinMax();
418     assertEquals(minMax[0], -102.34d);
419     assertEquals(minMax[1], 94.3d);
420   }
421
422   @Test(groups = { "Functional", "Timing" })
423   public void testFindMinMax_timing()
424   {
425     Random r = new Random();
426     int size = 1000; // increase to stress test timing
427     double[][] vals = new double[size][size];
428     double max = -Double.MAX_VALUE;
429     double min = Double.MAX_VALUE;
430     for (int i = 0; i < size; i++)
431     {
432       vals[i] = new double[size];
433       for (int j = 0; j < size; j++)
434       {
435         // use nextLong rather than nextDouble to include negative values
436         double d = r.nextLong();
437         if (d > max)
438         {
439           max = d;
440         }
441         if (d < min)
442         {
443           min = d;
444         }
445         vals[i][j] = d;
446       }
447     }
448     Matrix m = new Matrix(vals);
449     long now = System.currentTimeMillis();
450     double[] minMax = m.findMinMax();
451     System.out.println(String.format("findMinMax for %d x %d took %dms",
452             size, size, (System.currentTimeMillis() - now)));
453     assertEquals(minMax[0], min);
454     assertEquals(minMax[1], max);
455   }
456
457   /**
458    * Test range reversal with maximum value becoming zero
459    */
460   @Test(groups = "Functional")
461   public void testReverseRange_maxToZero()
462   {
463     Matrix m1 = new Matrix(
464             new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
465
466     /*
467      * subtract all from max: range -3.4 to 15 becomes 18.4 to 0
468      */
469     m1.reverseRange(true);
470     assertEquals(m1.getValue(0, 0), 13d, DELTA);
471     assertEquals(m1.getValue(0, 1), 11.5d, DELTA);
472     assertEquals(m1.getValue(0, 2), 11d, DELTA);
473     assertEquals(m1.getValue(1, 0), 18.4d, DELTA);
474     assertEquals(m1.getValue(1, 1), 11d, DELTA);
475     assertEquals(m1.getValue(1, 2), 0d, DELTA);
476
477     /*
478      * repeat operation - range is now 0 to 18.4
479      */
480     m1.reverseRange(true);
481     assertEquals(m1.getValue(0, 0), 5.4d, DELTA);
482     assertEquals(m1.getValue(0, 1), 6.9d, DELTA);
483     assertEquals(m1.getValue(0, 2), 7.4d, DELTA);
484     assertEquals(m1.getValue(1, 0), 0d, DELTA);
485     assertEquals(m1.getValue(1, 1), 7.4d, DELTA);
486     assertEquals(m1.getValue(1, 2), 18.4d, DELTA);
487   }
488
489   /**
490    * Test range reversal with minimum and maximum values swapped
491    */
492   @Test(groups = "Functional")
493   public void testReverseRange_swapMinMax()
494   {
495     Matrix m1 = new Matrix(
496             new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
497   
498     /*
499      * swap all values in min-max range
500      * = subtract from (min + max = 11.6) 
501      * range -3.4 to 15 becomes 18.4 to -3.4
502      */
503     m1.reverseRange(false);
504     assertEquals(m1.getValue(0, 0), 9.6d, DELTA);
505     assertEquals(m1.getValue(0, 1), 8.1d, DELTA);
506     assertEquals(m1.getValue(0, 2), 7.6d, DELTA);
507     assertEquals(m1.getValue(1, 0), 15d, DELTA);
508     assertEquals(m1.getValue(1, 1), 7.6d, DELTA);
509     assertEquals(m1.getValue(1, 2), -3.4d, DELTA);
510   
511     /*
512      * repeat operation - original values restored
513      */
514     m1.reverseRange(false);
515     assertEquals(m1.getValue(0, 0), 2d, DELTA);
516     assertEquals(m1.getValue(0, 1), 3.5d, DELTA);
517     assertEquals(m1.getValue(0, 2), 4d, DELTA);
518     assertEquals(m1.getValue(1, 0), -3.4d, DELTA);
519     assertEquals(m1.getValue(1, 1), 4d, DELTA);
520     assertEquals(m1.getValue(1, 2), 15d, DELTA);
521   }
522
523   @Test(groups = "Functional")
524   public void testMultiply()
525   {
526     Matrix m = new Matrix(new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
527     m.multiply(2d);
528     assertEquals(m.getValue(0, 0), 4d, DELTA);
529     assertEquals(m.getValue(0, 1), 7d, DELTA);
530     assertEquals(m.getValue(0, 2), 8d, DELTA);
531     assertEquals(m.getValue(1, 0), -6.8d, DELTA);
532     assertEquals(m.getValue(1, 1), 8d, DELTA);
533     assertEquals(m.getValue(1, 2), 30d, DELTA);
534   }
535
536   @Test(groups = "Functional")
537   public void testConstructor()
538   {
539     double[][] values = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
540     Matrix m = new Matrix(values);
541     assertEquals(m.getValue(0, 0), 1d, DELTA);
542
543     /*
544      * verify the matrix has a copy of the original array
545      */
546     assertNotSame(values[0], m.getRow(0));
547     values[0][0] = -1d;
548     assertEquals(m.getValue(0, 0), 1d, DELTA); // unchanged
549   }
550 }