JAL-2446 merged to spike branch
[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     Matrix m2 = (Matrix) m1.copy();
192     assertNotSame(m1, m2);
193     assertTrue(matrixEquals(m1, m2));
194   }
195
196   /**
197    * main method extracted from Matrix
198    * 
199    * @param args
200    */
201   public static void main(String[] args) throws Exception
202   {
203     int n = Integer.parseInt(args[0]);
204     double[][] in = new double[n][n];
205   
206     for (int i = 0; i < n; i++)
207     {
208       for (int j = 0; j < n; j++)
209       {
210         in[i][j] = Math.random();
211       }
212     }
213   
214     Matrix origmat = new Matrix(in);
215   
216     // System.out.println(" --- Original matrix ---- ");
217     // / origmat.print(System.out);
218     // System.out.println();
219     // System.out.println(" --- transpose matrix ---- ");
220     MatrixI trans = origmat.transpose();
221   
222     // trans.print(System.out);
223     // System.out.println();
224     // System.out.println(" --- OrigT * Orig ---- ");
225     MatrixI symm = trans.postMultiply(origmat);
226   
227     // symm.print(System.out);
228     // System.out.println();
229     // Copy the symmetric matrix for later
230     // Matrix origsymm = symm.copy();
231   
232     // This produces the tridiagonal transformation matrix
233     // long tstart = System.currentTimeMillis();
234     symm.tred();
235   
236     // long tend = System.currentTimeMillis();
237   
238     // System.out.println("Time take for tred = " + (tend-tstart) + "ms");
239     // System.out.println(" ---Tridiag transform matrix ---");
240     // symm.print(System.out);
241     // System.out.println();
242     // System.out.println(" --- D vector ---");
243     // symm.printD(System.out);
244     // System.out.println();
245     // System.out.println(" --- E vector ---");
246     // symm.printE(System.out);
247     // System.out.println();
248     // Now produce the diagonalization matrix
249     // tstart = System.currentTimeMillis();
250     symm.tqli();
251     // tend = System.currentTimeMillis();
252   
253     // System.out.println("Time take for tqli = " + (tend-tstart) + " ms");
254     // System.out.println(" --- New diagonalization 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     // System.out.println(" --- First eigenvector --- ");
264     // double[] eigenv = symm.getColumn(0);
265     // for (int i=0; i < eigenv.length;i++) {
266     // Format.print(System.out,"%15.4f",eigenv[i]);
267     // }
268     // System.out.println();
269     // double[] neigenv = origsymm.vectorPostMultiply(eigenv);
270     // for (int i=0; i < neigenv.length;i++) {
271     // Format.print(System.out,"%15.4f",neigenv[i]/symm.d[0]);
272     // }
273     // System.out.println();
274   }
275
276   @Test(groups = "Timing")
277   public void testSign()
278   {
279     assertEquals(Matrix.sign(-1, -2), -1d);
280     assertEquals(Matrix.sign(-1, 2), 1d);
281     assertEquals(Matrix.sign(-1, 0), 1d);
282     assertEquals(Matrix.sign(1, -2), -1d);
283     assertEquals(Matrix.sign(1, 2), 1d);
284     assertEquals(Matrix.sign(1, 0), 1d);
285   }
286
287   /**
288    * Helper method to make values for a sparse, pseudo-random symmetric matrix
289    * 
290    * @param rows
291    * @param cols
292    * @param occupancy
293    *          one in 'occupancy' entries will be non-zero
294    * @return
295    */
296   public double[][] getSparseValues(int rows, int cols, int occupancy)
297   {
298     Random r = new Random(1729);
299
300     /*
301      * generate whole number values between -12 and +12
302      * (to mimic score matrices used in Jalview)
303      */
304     double[][] d = new double[rows][cols];
305     int m = 0;
306     for (int i = 0; i < rows; i++)
307     {
308       if (++m % occupancy == 0)
309       {
310         d[i][i] = r.nextInt() % 13; // diagonal
311       }
312       for (int j = 0; j < i; j++)
313       {
314         if (++m % occupancy == 0)
315         {
316           d[i][j] = r.nextInt() % 13;
317           d[j][i] = d[i][j];
318         }
319       }
320     }
321     return d;
322   
323   }
324
325   /**
326    * Verify that the results of method tred() are the same if the calculation is
327    * redone
328    */
329   @Test(groups = "Functional")
330   public void testTred_reproducible()
331   {
332     /*
333      * make a pseudo-random symmetric matrix as required for tred/tqli
334      */
335     int rows = 10;
336     int cols = rows;
337     double[][] d = getSparseValues(rows, cols, 3);
338   
339     /*
340      * make a copy of the values so m1, m2 are not
341      * sharing arrays!
342      */
343     double[][] d1 = new double[rows][cols];
344     for (int row = 0; row < rows; row++)
345     {
346       for (int col = 0; col < cols; col++)
347       {
348         d1[row][col] = d[row][col];
349       }
350     }
351     Matrix m1 = new Matrix(d);
352     Matrix m2 = new Matrix(d1);
353     assertMatricesMatch(m1, m2); // sanity check
354     m1.tred();
355     m2.tred();
356     assertMatricesMatch(m1, m2);
357   }
358
359   private void assertMatricesMatch(MatrixI m1, MatrixI m2)
360   {
361     if (m1.height() != m2.height())
362     {
363       fail("height mismatch");
364     }
365     if (m1.width() != m2.width())
366     {
367       fail("width mismatch");
368     }
369     for (int row = 0; row < m1.height(); row++)
370     {
371       for (int col = 0; col < m1.width(); col++)
372       {
373         double v2 = m2.getValue(row, col);
374         double v1 = m1.getValue(row, col);
375         if (Math.abs(v1 - v2) > DELTA)
376         {
377           fail(String.format("At [%d, %d] %f != %f", row, col, v1, v2));
378         }
379       }
380     }
381     ArrayAsserts.assertArrayEquals(m1.getD(), m2.getD(), 0.00001d);
382     ArrayAsserts.assertArrayEquals(m1.getE(), m2.getE(), 0.00001d);
383   }
384
385   @Test(groups = "Functional")
386   public void testFindMinMax()
387   {
388     /*
389      * empty matrix case
390      */
391     Matrix m = new Matrix(new double[][] { {} });
392     assertNull(m.findMinMax());
393
394     /*
395      * normal case
396      */
397     double[][] vals = new double[2][];
398     vals[0] = new double[] {7d, 1d, -2.3d};
399     vals[1] = new double[] {-12d, 94.3d, -102.34d};
400     m = new Matrix(vals);
401     double[] minMax = m.findMinMax();
402     assertEquals(minMax[0], -102.34d);
403     assertEquals(minMax[1], 94.3d);
404   }
405
406   @Test(groups = { "Functional", "Timing" })
407   public void testFindMinMax_timing()
408   {
409     Random r = new Random();
410     int size = 1000; // increase to stress test timing
411     double[][] vals = new double[size][size];
412     double max = -Double.MAX_VALUE;
413     double min = Double.MAX_VALUE;
414     for (int i = 0; i < size; i++)
415     {
416       vals[i] = new double[size];
417       for (int j = 0; j < size; j++)
418       {
419         // use nextLong rather than nextDouble to include negative values
420         double d = r.nextLong();
421         if (d > max)
422         {
423           max = d;
424         }
425         if (d < min)
426         {
427           min = d;
428         }
429         vals[i][j] = d;
430       }
431     }
432     Matrix m = new Matrix(vals);
433     long now = System.currentTimeMillis();
434     double[] minMax = m.findMinMax();
435     System.out.println(String.format("findMinMax for %d x %d took %dms",
436             size, size, (System.currentTimeMillis() - now)));
437     assertEquals(minMax[0], min);
438     assertEquals(minMax[1], max);
439   }
440
441   /**
442    * Test range reversal with maximum value becoming zero
443    */
444   @Test(groups = "Functional")
445   public void testReverseRange_maxToZero()
446   {
447     Matrix m1 = new Matrix(
448             new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
449
450     /*
451      * subtract all from max: range -3.4 to 15 becomes 18.4 to 0
452      */
453     m1.reverseRange(true);
454     assertEquals(m1.getValue(0, 0), 13d, DELTA);
455     assertEquals(m1.getValue(0, 1), 11.5d, DELTA);
456     assertEquals(m1.getValue(0, 2), 11d, DELTA);
457     assertEquals(m1.getValue(1, 0), 18.4d, DELTA);
458     assertEquals(m1.getValue(1, 1), 11d, DELTA);
459     assertEquals(m1.getValue(1, 2), 0d, DELTA);
460
461     /*
462      * repeat operation - range is now 0 to 18.4
463      */
464     m1.reverseRange(true);
465     assertEquals(m1.getValue(0, 0), 5.4d, DELTA);
466     assertEquals(m1.getValue(0, 1), 6.9d, DELTA);
467     assertEquals(m1.getValue(0, 2), 7.4d, DELTA);
468     assertEquals(m1.getValue(1, 0), 0d, DELTA);
469     assertEquals(m1.getValue(1, 1), 7.4d, DELTA);
470     assertEquals(m1.getValue(1, 2), 18.4d, DELTA);
471   }
472
473   /**
474    * Test range reversal with minimum and maximum values swapped
475    */
476   @Test(groups = "Functional")
477   public void testReverseRange_swapMinMax()
478   {
479     Matrix m1 = new Matrix(
480             new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
481   
482     /*
483      * swap all values in min-max range
484      * = subtract from (min + max = 11.6) 
485      * range -3.4 to 15 becomes 18.4 to -3.4
486      */
487     m1.reverseRange(false);
488     assertEquals(m1.getValue(0, 0), 9.6d, DELTA);
489     assertEquals(m1.getValue(0, 1), 8.1d, DELTA);
490     assertEquals(m1.getValue(0, 2), 7.6d, DELTA);
491     assertEquals(m1.getValue(1, 0), 15d, DELTA);
492     assertEquals(m1.getValue(1, 1), 7.6d, DELTA);
493     assertEquals(m1.getValue(1, 2), -3.4d, DELTA);
494   
495     /*
496      * repeat operation - original values restored
497      */
498     m1.reverseRange(false);
499     assertEquals(m1.getValue(0, 0), 2d, DELTA);
500     assertEquals(m1.getValue(0, 1), 3.5d, DELTA);
501     assertEquals(m1.getValue(0, 2), 4d, DELTA);
502     assertEquals(m1.getValue(1, 0), -3.4d, DELTA);
503     assertEquals(m1.getValue(1, 1), 4d, DELTA);
504     assertEquals(m1.getValue(1, 2), 15d, DELTA);
505   }
506
507   @Test(groups = "Functional")
508   public void testMultiply()
509   {
510     Matrix m = new Matrix(new double[][] { { 2, 3.5, 4 }, { -3.4, 4, 15 } });
511     m.multiply(2d);
512     assertEquals(m.getValue(0, 0), 4d, DELTA);
513     assertEquals(m.getValue(0, 1), 7d, DELTA);
514     assertEquals(m.getValue(0, 2), 8d, DELTA);
515     assertEquals(m.getValue(1, 0), -6.8d, DELTA);
516     assertEquals(m.getValue(1, 1), 8d, DELTA);
517     assertEquals(m.getValue(1, 2), 30d, DELTA);
518   }
519
520   @Test(groups = "Functional")
521   public void testConstructor()
522   {
523     double[][] values = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } };
524     Matrix m = new Matrix(values);
525     assertEquals(m.getValue(0, 0), 1d, DELTA);
526
527     /*
528      * verify the matrix has a copy of the original array
529      */
530     assertNotSame(values[0], m.getRow(0));
531     values[0][0] = -1d;
532     assertEquals(m.getValue(0, 0), 1d, DELTA); // unchanged
533   }
534 }