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