View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.linear;
24  
25  import org.hipparchus.exception.LocalizedCoreFormats;
26  import org.hipparchus.exception.MathIllegalArgumentException;
27  import org.hipparchus.fraction.Fraction;
28  import org.junit.jupiter.api.Test;
29  
30  import static org.junit.jupiter.api.Assertions.assertEquals;
31  import static org.junit.jupiter.api.Assertions.assertFalse;
32  import static org.junit.jupiter.api.Assertions.assertNull;
33  import static org.junit.jupiter.api.Assertions.assertSame;
34  import static org.junit.jupiter.api.Assertions.assertTrue;
35  import static org.junit.jupiter.api.Assertions.fail;
36  
37  class LUDecompositionTest {
38      private double[][] testData = {
39              { 1.0, 2.0, 3.0},
40              { 2.0, 5.0, 3.0},
41              { 1.0, 0.0, 8.0}
42      };
43      private double[][] testDataMinus = {
44              { -1.0, -2.0, -3.0},
45              { -2.0, -5.0, -3.0},
46              { -1.0,  0.0, -8.0}
47      };
48      private double[][] luData = {
49              { 2.0, 3.0, 3.0 },
50              { 0.0, 5.0, 7.0 },
51              { 6.0, 9.0, 8.0 }
52      };
53  
54      // singular matrices
55      private double[][] singular = {
56              { 2.0, 3.0 },
57              { 2.0, 3.0 }
58      };
59      private double[][] bigSingular = {
60              { 1.0, 2.0,   3.0,    4.0 },
61              { 2.0, 5.0,   3.0,    4.0 },
62              { 7.0, 3.0, 256.0, 1930.0 },
63              { 3.0, 7.0,   6.0,    8.0 }
64      }; // 4th row = 1st + 2nd
65  
66      private static final double entryTolerance = 10e-16;
67  
68      private static final double normTolerance = 10e-14;
69  
70      /** test dimensions */
71      @Test
72      void testDimensions() {
73          RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
74          LUDecomposition LU = new LUDecomposition(matrix);
75          assertEquals(testData.length, LU.getL().getRowDimension());
76          assertEquals(testData.length, LU.getL().getColumnDimension());
77          assertEquals(testData.length, LU.getU().getRowDimension());
78          assertEquals(testData.length, LU.getU().getColumnDimension());
79          assertEquals(testData.length, LU.getP().getRowDimension());
80          assertEquals(testData.length, LU.getP().getColumnDimension());
81  
82      }
83  
84      /** test non-square matrix */
85      @Test
86      void testNonSquare() {
87          try {
88              new LUDecomposition(MatrixUtils.createRealMatrix(new double[3][2]));
89              fail("Expecting MathIllegalArgumentException");
90          } catch (MathIllegalArgumentException ime) {
91              assertEquals(LocalizedCoreFormats.NON_SQUARE_MATRIX, ime.getSpecifier());
92          }
93      }
94  
95      /** test PA = LU */
96      @Test
97      void testPAEqualLU() {
98          RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
99          LUDecomposition lu = new LUDecomposition(matrix);
100         RealMatrix l = lu.getL();
101         RealMatrix u = lu.getU();
102         RealMatrix p = lu.getP();
103         double norm = l.multiply(u).subtract(p.multiply(matrix)).getNorm1();
104         assertEquals(0, norm, normTolerance);
105 
106         matrix = MatrixUtils.createRealMatrix(testDataMinus);
107         lu = new LUDecomposition(matrix);
108         l = lu.getL();
109         u = lu.getU();
110         p = lu.getP();
111         norm = l.multiply(u).subtract(p.multiply(matrix)).getNorm1();
112         assertEquals(0, norm, normTolerance);
113 
114         matrix = MatrixUtils.createRealIdentityMatrix(17);
115         lu = new LUDecomposition(matrix);
116         l = lu.getL();
117         u = lu.getU();
118         p = lu.getP();
119         norm = l.multiply(u).subtract(p.multiply(matrix)).getNorm1();
120         assertEquals(0, norm, normTolerance);
121 
122         matrix = MatrixUtils.createRealMatrix(singular);
123         lu = new LUDecomposition(matrix);
124         assertFalse(lu.getSolver().isNonSingular());
125         assertNull(lu.getL());
126         assertNull(lu.getU());
127         assertNull(lu.getP());
128 
129         matrix = MatrixUtils.createRealMatrix(bigSingular);
130         lu = new LUDecomposition(matrix);
131         assertFalse(lu.getSolver().isNonSingular());
132         assertNull(lu.getL());
133         assertNull(lu.getU());
134         assertNull(lu.getP());
135 
136     }
137 
138     /** test that L is lower triangular with unit diagonal */
139     @Test
140     void testLLowerTriangular() {
141         RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
142         RealMatrix l = new LUDecomposition(matrix).getL();
143         for (int i = 0; i < l.getRowDimension(); i++) {
144             assertEquals(1, l.getEntry(i, i), entryTolerance);
145             for (int j = i + 1; j < l.getColumnDimension(); j++) {
146                 assertEquals(0, l.getEntry(i, j), entryTolerance);
147             }
148         }
149     }
150 
151     /** test that U is upper triangular */
152     @Test
153     void testUUpperTriangular() {
154         RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
155         RealMatrix u = new LUDecomposition(matrix).getU();
156         for (int i = 0; i < u.getRowDimension(); i++) {
157             for (int j = 0; j < i; j++) {
158                 assertEquals(0, u.getEntry(i, j), entryTolerance);
159             }
160         }
161     }
162 
163     /** test that P is a permutation matrix */
164     @Test
165     void testPPermutation() {
166         RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
167         RealMatrix p   = new LUDecomposition(matrix).getP();
168 
169         RealMatrix ppT = p.multiplyTransposed(p);
170         RealMatrix id  = MatrixUtils.createRealIdentityMatrix(p.getRowDimension());
171         assertEquals(0, ppT.subtract(id).getNorm1(), normTolerance);
172 
173         for (int i = 0; i < p.getRowDimension(); i++) {
174             int zeroCount  = 0;
175             int oneCount   = 0;
176             int otherCount = 0;
177             for (int j = 0; j < p.getColumnDimension(); j++) {
178                 final double e = p.getEntry(i, j);
179                 if (e == 0) {
180                     ++zeroCount;
181                 } else if (e == 1) {
182                     ++oneCount;
183                 } else {
184                     ++otherCount;
185                 }
186             }
187             assertEquals(p.getColumnDimension() - 1, zeroCount);
188             assertEquals(1, oneCount);
189             assertEquals(0, otherCount);
190         }
191 
192         for (int j = 0; j < p.getColumnDimension(); j++) {
193             int zeroCount  = 0;
194             int oneCount   = 0;
195             int otherCount = 0;
196             for (int i = 0; i < p.getRowDimension(); i++) {
197                 final double e = p.getEntry(i, j);
198                 if (e == 0) {
199                     ++zeroCount;
200                 } else if (e == 1) {
201                     ++oneCount;
202                 } else {
203                     ++otherCount;
204                 }
205             }
206             assertEquals(p.getRowDimension() - 1, zeroCount);
207             assertEquals(1, oneCount);
208             assertEquals(0, otherCount);
209         }
210 
211     }
212 
213     /** test singular */
214     @Test
215     void testSingular() {
216         final RealMatrix m = MatrixUtils.createRealMatrix(testData);
217         LUDecomposition lu = new LUDecomposition(m);
218         assertTrue(lu.getSolver().isNonSingular());
219         assertEquals(-1.0, lu.getDeterminant(), 1.0e-15);
220         lu = new LUDecomposition(m.getSubMatrix(0, 1, 0, 1));
221         assertTrue(lu.getSolver().isNonSingular());
222         assertEquals(+1.0, lu.getDeterminant(), 1.0e-15);
223         lu = new LUDecomposition(MatrixUtils.createRealMatrix(singular));
224         assertFalse(lu.getSolver().isNonSingular());
225         assertEquals(0.0, lu.getDeterminant(), 1.0e-15);
226         lu = new LUDecomposition(MatrixUtils.createRealMatrix(bigSingular));
227         assertFalse(lu.getSolver().isNonSingular());
228         assertEquals(0.0, lu.getDeterminant(), 1.0e-15);
229         try {
230             lu.getSolver().solve(new ArrayRealVector(new double[] { 1, 1, 1, 1 }));
231             fail("an exception should have been thrown");
232         } catch (MathIllegalArgumentException miae) {
233             assertEquals(LocalizedCoreFormats.SINGULAR_MATRIX, miae.getSpecifier());
234         }
235     }
236 
237     /** test matrices values */
238     @Test
239     void testMatricesValues1() {
240        LUDecomposition lu =
241             new LUDecomposition(MatrixUtils.createRealMatrix(testData));
242         RealMatrix lRef = MatrixUtils.createRealMatrix(new double[][] {
243                 { 1.0, 0.0, 0.0 },
244                 { 0.5, 1.0, 0.0 },
245                 { 0.5, 0.2, 1.0 }
246         });
247         RealMatrix uRef = MatrixUtils.createRealMatrix(new double[][] {
248                 { 2.0,  5.0, 3.0 },
249                 { 0.0, -2.5, 6.5 },
250                 { 0.0,  0.0, 0.2 }
251         });
252         RealMatrix pRef = MatrixUtils.createRealMatrix(new double[][] {
253                 { 0.0, 1.0, 0.0 },
254                 { 0.0, 0.0, 1.0 },
255                 { 1.0, 0.0, 0.0 }
256         });
257         int[] pivotRef = { 1, 2, 0 };
258 
259         // check values against known references
260         RealMatrix l = lu.getL();
261         assertEquals(0, l.subtract(lRef).getNorm1(), 1.0e-13);
262         RealMatrix u = lu.getU();
263         assertEquals(0, u.subtract(uRef).getNorm1(), 1.0e-13);
264         RealMatrix p = lu.getP();
265         assertEquals(0, p.subtract(pRef).getNorm1(), 1.0e-13);
266         int[] pivot = lu.getPivot();
267         for (int i = 0; i < pivotRef.length; ++i) {
268             assertEquals(pivotRef[i], pivot[i]);
269         }
270 
271         // check the same cached instance is returned the second time
272         assertSame(l, lu.getL());
273         assertSame(u, lu.getU());
274         assertSame(p, lu.getP());
275 
276     }
277 
278     /** test matrices values */
279     @Test
280     void testMatricesValues2() {
281        LUDecomposition lu =
282             new LUDecomposition(MatrixUtils.createRealMatrix(luData));
283         RealMatrix lRef = MatrixUtils.createRealMatrix(new double[][] {
284                 {    1.0,    0.0, 0.0 },
285                 {    0.0,    1.0, 0.0 },
286                 { 1.0 / 3.0, 0.0, 1.0 }
287         });
288         RealMatrix uRef = MatrixUtils.createRealMatrix(new double[][] {
289                 { 6.0, 9.0,    8.0    },
290                 { 0.0, 5.0,    7.0    },
291                 { 0.0, 0.0, 1.0 / 3.0 }
292         });
293         RealMatrix pRef = MatrixUtils.createRealMatrix(new double[][] {
294                 { 0.0, 0.0, 1.0 },
295                 { 0.0, 1.0, 0.0 },
296                 { 1.0, 0.0, 0.0 }
297         });
298         int[] pivotRef = { 2, 1, 0 };
299 
300         // check values against known references
301         RealMatrix l = lu.getL();
302         assertEquals(0, l.subtract(lRef).getNorm1(), 1.0e-13);
303         RealMatrix u = lu.getU();
304         assertEquals(0, u.subtract(uRef).getNorm1(), 1.0e-13);
305         RealMatrix p = lu.getP();
306         assertEquals(0, p.subtract(pRef).getNorm1(), 1.0e-13);
307         int[] pivot = lu.getPivot();
308         for (int i = 0; i < pivotRef.length; ++i) {
309             assertEquals(pivotRef[i], pivot[i]);
310         }
311 
312         // check the same cached instance is returned the second time
313         assertSame(l, lu.getL());
314         assertSame(u, lu.getU());
315         assertSame(p, lu.getP());
316     }
317 
318     @Test
319     void testSolve() {
320         LUDecomposition lu =
321                         new LUDecomposition(new Array2DRowRealMatrix(testData));
322         DecompositionSolver solver = lu.getSolver();
323         RealVector solution = solver.solve(new ArrayRealVector(new double[] {
324             new Fraction(1, 2).doubleValue(), new Fraction(2, 3).doubleValue(), new Fraction(3,4).doubleValue()
325         }));
326         assertEquals(testData.length, solution.getDimension());
327         assertEquals(new Fraction(-31, 12).doubleValue(), solution.getEntry(0), 1.0e-14);
328         assertEquals(new Fraction( 11, 12).doubleValue(), solution.getEntry(1), 1.0e-14);
329         assertEquals(new Fraction(  5, 12).doubleValue(), solution.getEntry(2), 1.0e-14);
330         assertEquals(testData.length,    solver.getRowDimension());
331         assertEquals(testData[0].length, solver.getColumnDimension());
332         try {
333             solver.solve(new ArrayRealVector(new double[] { 1, 1 }));
334             fail("an exception should have been thrown");
335         } catch (MathIllegalArgumentException miae) {
336             assertEquals(LocalizedCoreFormats.DIMENSIONS_MISMATCH, miae.getSpecifier());
337         }
338     }
339 
340 }