View Javadoc
1   /*
2    * Licensed to the Hipparchus project under one or more contributor license agreements. See the
3    * NOTICE file distributed with this work for additional information regarding copyright ownership.
4    * The Hipparchus project licenses this file to You under the Apache License, Version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * copy of the License at
7    *
8    * https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package org.hipparchus.linear;
16  
17  import static org.junit.jupiter.api.Assertions.assertEquals;
18  import static org.junit.jupiter.api.Assertions.assertTrue;
19  import static org.junit.jupiter.api.Assertions.fail;
20  import java.util.Arrays;
21  import org.hipparchus.complex.Complex;
22  import org.hipparchus.complex.ComplexField;
23  import org.hipparchus.exception.LocalizedCoreFormats;
24  import org.hipparchus.exception.MathIllegalArgumentException;
25  import org.hipparchus.exception.MathIllegalStateException;
26  import org.junit.jupiter.api.Assertions;
27  import org.junit.jupiter.api.Test;
28  
29  /**
30   * Test class for ComplexSchurTransformer.
31   */
32  public class ComplexSchurTransformerTest {
33  
34    private final double epsilon = 1.0e-10;
35  
36    /**
37     * Helper method to verify the Schur Decomposition properties.
38     * <p>
39     * <ul>
40     * <li>Check if T is Upper Triangular.</li>
41     * <li>Check if P is Unitary (P * P^H = I).</li>
42     * <li>Check if A = P * T * P^H.</li>
43     * </ul>
44     */
45    private void checkSchurDecomposition(FieldMatrix<Complex> A) {
46      ComplexSchurTransformer transformer = new ComplexSchurTransformer(A);
47      FieldMatrix<Complex> P = transformer.getP();
48      FieldMatrix<Complex> T = transformer.getT();
49      FieldMatrix<Complex> PT = transformer.getPT(); // P^H (Conjugate Transpose)
50  
51      // check cache
52      Assertions.assertSame(P, transformer.getP());
53      Assertions.assertSame(PT, transformer.getPT());
54      Assertions.assertSame(T, transformer.getT());
55  
56      // System.out.println(P);
57      // System.out.println(T);
58  
59      int n = A.getRowDimension();
60      // Check T is Upper Triangular
61      for (int r = 0; r < n; r++) {
62        for (int c = 0; c < r; c++) {
63          assertEquals(0.0, T.getEntry(r, c).norm(), epsilon,
64              "T should be upper triangular. Entry (" + r + "," + c + ") is not zero.");
65        }
66      }
67  
68      // Check P is Unitary: P * P^H = I
69      FieldMatrix<Complex> identity =
70          MatrixUtils.createFieldIdentityMatrix(ComplexField.getInstance(), n);
71      FieldMatrix<Complex> PPt = P.multiply(PT);
72  
73      for (int r = 0; r < n; r++) {
74        for (int c = 0; c < n; c++) {
75          Complex expected = identity.getEntry(r, c);
76          Complex actual = PPt.getEntry(r, c);
77          assertEquals(0.0, expected.subtract(actual).norm(), epsilon,
78              "P should be unitary. P*P^H entry (" + r + "," + c + ") mismatch.");
79        }
80      }
81  
82      // Check A = P * T * P^H
83      FieldMatrix<Complex> reconstructedA = P.multiply(T).multiply(PT);
84      for (int r = 0; r < n; r++) {
85        for (int c = 0; c < n; c++) {
86          Complex expected = A.getEntry(r, c);
87          Complex actual = reconstructedA.getEntry(r, c);
88          assertEquals(0.0, expected.subtract(actual).norm(), epsilon,
89              "Reconstruction A = P*T*P^H failed at (" + r + "," + c + ").");
90        }
91      }
92    }
93  
94    /**
95     * Example 1: Real valued matrix, but treated as Complex. SchurDecomposition[{{-4, -3}, {2, 1}}]
96     * Expected Eigenvalues on diagonal of T: -1, -2
97     */
98    @Test
99    public void testExample1() {
100     // Matrix A = {{-4, -3}, {2, 1}}
101     Complex[][] data =
102         {{new Complex(-4, 0), new Complex(-3, 0)}, {new Complex(2, 0), new Complex(1, 0)}};
103     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
104 
105     checkSchurDecomposition(matrix);
106 
107     // Additional check: The diagonal of T should contain the eigenvalues (-1 and -2).
108     // Note: The order depends on the pivot strategy, so we check if they are present.
109     ComplexSchurTransformer transformer = new ComplexSchurTransformer(matrix);
110     FieldMatrix<Complex> T = transformer.getT();
111 
112     Complex t00 = T.getEntry(0, 0);
113     Complex t11 = T.getEntry(1, 1);
114 
115     // Check if diagonal elements are either -1 or -2
116     boolean hasMinus1 = (t00.subtract(-1).norm() < epsilon) || (t11.subtract(-1).norm() < epsilon);
117     boolean hasMinus2 = (t00.subtract(-2).norm() < epsilon) || (t11.subtract(-2).norm() < epsilon);
118 
119     assertTrue(hasMinus1, "Schur form T should contain eigenvalue -1");
120     assertTrue(hasMinus2, "Schur form T should contain eigenvalue -2");
121   }
122 
123   /**
124    * Example 2: Simple Complex Matrix (Hermitian). m = {{-1, I}, {-I, 1}} Trace = 0, Det = -2.
125    * Eigenvalues should be +/- Sqrt(2).
126    */
127   @Test
128   public void testExample2() {
129     // Matrix A = {{-1, I}, {-I, 1}}
130     Complex I = Complex.I;
131     Complex[][] data = {{new Complex(-1), I}, //
132         {I.negate(), new Complex(1, 0)}};
133     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
134 
135     checkSchurDecomposition(matrix);
136 
137     // Verify eigenvalues +/- Sqrt(2)
138     ComplexSchurTransformer transformer = new ComplexSchurTransformer(matrix);
139     FieldMatrix<Complex> T = transformer.getT();
140 
141     double sqrt2 = Math.sqrt(2.0);
142     Complex t00 = T.getEntry(0, 0);
143     Complex t11 = T.getEntry(1, 1);
144 
145     // Since the matrix is Hermitian, T should be diagonal (Spectral Theorem)
146     assertEquals(0.0, T.getEntry(0, 1).norm(), epsilon,
147         "T should be diagonal for Hermitian matrix");
148 
149     // Check Eigenvalues magnitude
150     assertEquals(sqrt2, t00.norm(), epsilon);
151     assertEquals(sqrt2, t11.norm(), epsilon);
152   }
153 
154   /**
155    * Example 3: 3x3 Matrix with real entries. m = {{5, 7, 6}, {-3, 1, 6}, {-2, 1, 3}} Complex
156    * eigenvalues exist.
157    */
158   @Test
159   public void testExample3() {
160     // Matrix A = {{5, 7, 6}, {-3, 1, 6}, {-2, 1, 3}}
161     Complex[][] data = {{new Complex(5), new Complex(7), new Complex(6)}, //
162         {new Complex(-3), new Complex(1), new Complex(6)}, //
163         {new Complex(-2), new Complex(1), new Complex(3)}};
164     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
165 
166     checkSchurDecomposition(matrix);
167   }
168 
169   @Test
170   public void testExample4() {
171     // Matrix A = {{Pi, .3}, {I, 1.0+1.5}}
172     Complex I = Complex.I;
173     Complex[][] data = {{new Complex(Math.PI), new Complex(0.3)}, //
174         {I, new Complex(1.0, 1.5)}};
175     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
176 
177     checkSchurDecomposition(matrix);
178   }
179 
180   @Test
181   public void testExample5() {
182     // Matrix A = {{-1.2, 2.7, 3.8}, {4.2, 4.4, 5.3}, {3.5, 7.6, 6.8}}
183     Complex[][] data = {{new Complex(-1.2), new Complex(2.7), new Complex(3.8)}, //
184         {new Complex(4.2), new Complex(4.4), new Complex(5.3)}, //
185         {new Complex(3.5), new Complex(7.6), new Complex(6.8)}};
186     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
187 
188     checkSchurDecomposition(matrix);
189   }
190 
191   @Test
192   public void testExample6() {
193     // Matrix A = {{2.7, 4.8, 8.1}, {-.6, 0, 0}, {.1, 0, .3}};
194     Complex[][] data = {{new Complex(2.7), new Complex(4.8), new Complex(8.1)}, //
195         {new Complex(-0.6), new Complex(0.0), new Complex(0.0)}, //
196         {new Complex(0.1), new Complex(0.0), new Complex(0.3)}};
197     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
198 
199     checkSchurDecomposition(matrix);
200   }
201 
202   @Test
203   public void testExample7() {
204     // Matrix A = {{1.81066, 0.31066, 1.5}, {-0.53033, 2.03033, 0.43934}, {-0.96967, -0.53033,
205     // 2.56066}};;
206     Complex[][] data = {{new Complex(1.81066), new Complex(0.31066), new Complex(1.5)}, //
207         {new Complex(-0.53033), new Complex(2.03033), new Complex(0.43934)}, //
208         {new Complex(-0.96967), new Complex(-0.53033), new Complex(2.56066)}};
209     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
210 
211     checkSchurDecomposition(matrix);
212 
213   }
214 
215   /**
216    * Additional Test: Purely Imaginary Diagonal. A = {{3i, 0}, {0, -2i}} Already in Schur form
217    * (Diagonal).
218    */
219   @Test
220   public void testAlreadySchurForm() {
221     Complex I = Complex.I;
222     Complex[][] data = {{I.multiply(3), Complex.ZERO}, {Complex.ZERO, I.multiply(-2)}};
223     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
224 
225     checkSchurDecomposition(matrix);
226 
227     ComplexSchurTransformer transformer = new ComplexSchurTransformer(matrix);
228     FieldMatrix<Complex> T = transformer.getT();
229     Assertions.assertSame(T, transformer.getT());
230 
231     // Should roughly remain the same (order might flip depending on implementation stability)
232     double norm0 = T.getEntry(0, 0).norm();
233     double norm1 = T.getEntry(1, 1).norm();
234 
235     assertTrue((Math.abs(norm0 - 3.0) < epsilon && Math.abs(norm1 - 2.0) < epsilon)
236         || (Math.abs(norm0 - 2.0) < epsilon && Math.abs(norm1 - 3.0) < epsilon));
237   }
238 
239   /**
240    * Additional Test: Defective Matrix (Jordan Block). A = {{1, 1}, {0, 1}} Cannot be diagonalized,
241    * but Schur form exists (itself).
242    */
243   @Test
244   public void testDefectiveMatrix() {
245     Complex[][] data = {{Complex.ONE, Complex.ONE}, {Complex.ZERO, Complex.ONE}};
246     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
247 
248     checkSchurDecomposition(matrix);
249 
250     ComplexSchurTransformer transformer = new ComplexSchurTransformer(matrix);
251     FieldMatrix<Complex> T = transformer.getT();
252     Assertions.assertSame(T, transformer.getT());
253 
254     // T should still be {{1, 1}, {0, 1}} or similar
255     assertEquals(1.0, T.getEntry(0, 0).getReal(), epsilon);
256     assertEquals(1.0, T.getEntry(1, 1).getReal(), epsilon);
257   }
258 
259   @Test
260   public void testNaN() {
261     try {
262       Complex[][] data = {{new Complex(-4, 0), new Complex(-3, Double.NaN)},
263           {new Complex(2, 0), new Complex(1, 0)}};
264       FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
265 
266       checkSchurDecomposition(matrix);
267 
268       fail();
269     } catch (MathIllegalStateException mise) {
270       assertEquals("convergence failed", mise.getMessage());
271     }
272   }
273 
274   /**
275    * Positive definite matrix
276    */
277   @Test
278   public void testGetEigenvalues() {
279     // Matrix A = {{5.42,3.26 + 0.643*I,-0.467-0.193*I},
280     // {3.26-0.643*I,3.82,1.04-2.35*I},
281     // {-0.467+0.193*I,1.04+2.35*I,4.88}}
282     Complex[][] data = {{new Complex(5.42), new Complex(3.26, 0.643), new Complex(-0.467, -0.193)}, //
283         {new Complex(3.26, -0.643), new Complex(3.82), new Complex(1.04, -2.35)}, //
284         {new Complex(-0.467, 0.193), new Complex(1.04, 2.35), new Complex(4.88)}};
285     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
286     checkSchurDecomposition(matrix);
287 
288     Complex[] eigenvalues = ComplexSchurTransformer.getEigenvalues(matrix);
289     // sort descending
290     Arrays.sort(eigenvalues, (a, b) -> {
291       int realComp = Double.compare(b.getReal(), a.getReal());
292       if (realComp != 0) {
293         return realComp;
294       } else {
295         return Double.compare(b.getImaginary(), a.getImaginary());
296       }
297     });
298     FieldVector<Complex> fieldVector = MatrixUtils.createFieldVector(eigenvalues);
299     Assertions.assertEquals(8.768464618713097, fieldVector.getEntry(0).getReal(), 1.0e-15);
300     Assertions.assertEquals(4.61e-16, fieldVector.getEntry(0).getImaginary(), 1.0e-18);
301     Assertions.assertEquals(5.163611813754241, fieldVector.getEntry(1).getReal(), 1.0e-15);
302     Assertions.assertEquals(-0.70e-16, fieldVector.getEntry(1).getImaginary(), 1.0e-18);
303     Assertions.assertEquals(0.18792356753266304, fieldVector.getEntry(2).getReal(), 1.0e-15);
304     Assertions.assertEquals(-1.62e-16, fieldVector.getEntry(2).getImaginary(), 1.0e-18);
305 
306   }
307 
308   @Test
309   void testNonSquare() {
310     Complex[][] data = {{new Complex(5.42), new Complex(3.26, 0.643)}, //
311         {new Complex(3.26, -0.643), new Complex(3.82)}, //
312         {new Complex(-0.467, 0.193), new Complex(1.04, 2.35)}};
313     FieldMatrix<Complex> matrix = MatrixUtils.createFieldMatrix(data);
314     try {
315       new ComplexSchurTransformer(matrix);
316       fail("an exception should have been thrown");
317     } catch (MathIllegalArgumentException ime) {
318       assertEquals(LocalizedCoreFormats.NON_SQUARE_MATRIX, ime.getSpecifier());
319     }
320   }
321 
322 }