enc_linalg_test.cc (2217B)
1 // Copyright (c) the JPEG XL Project Authors. All rights reserved. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 #include "lib/jxl/enc_linalg.h" 7 8 #include "lib/jxl/base/random.h" 9 #include "lib/jxl/testing.h" 10 11 namespace jxl { 12 namespace { 13 14 Matrix2x2 Diagonal(const Vector2& d) { return {{{d[0], 0.0}, {0.0, d[1]}}}; } 15 16 Matrix2x2 Identity() { return Diagonal({1.0, 1.0}); } 17 18 Matrix2x2 MatMul(const Matrix2x2& A, const Matrix2x2& B) { 19 Matrix2x2 out; 20 for (size_t y = 0; y < 2; ++y) { 21 for (size_t x = 0; x < 2; ++x) { 22 out[y][x] = A[0][x] * B[y][0] + A[1][x] * B[y][1]; 23 } 24 } 25 return out; 26 } 27 28 Matrix2x2 Transpose(const Matrix2x2& A) { 29 return {{{A[0][0], A[1][0]}, {A[0][1], A[1][1]}}}; 30 } 31 32 Matrix2x2 RandomSymmetricMatrix(Rng& rng, const double vmin, 33 const double vmax) { 34 Matrix2x2 A; 35 A[0][0] = rng.UniformF(vmin, vmax); 36 A[0][1] = A[1][0] = rng.UniformF(vmin, vmax); 37 A[1][1] = rng.UniformF(vmin, vmax); 38 return A; 39 } 40 41 void VerifyMatrixEqual(const Matrix2x2& A, const Matrix2x2& B, 42 const double eps) { 43 for (size_t y = 0; y < 2; ++y) { 44 for (size_t x = 0; x < 2; ++x) { 45 ASSERT_NEAR(A[y][x], B[y][x], eps); 46 } 47 } 48 } 49 50 void VerifyOrthogonal(const Matrix2x2& A, const double eps) { 51 VerifyMatrixEqual(Identity(), MatMul(Transpose(A), A), eps); 52 } 53 54 TEST(LinAlgTest, ConvertToDiagonal) { 55 { 56 Matrix2x2 I = Identity(); 57 Matrix2x2 U; 58 Vector2 d; 59 ConvertToDiagonal(I, d, U); 60 VerifyMatrixEqual(I, U, 1e-15); 61 for (size_t k = 0; k < 2; ++k) { 62 ASSERT_NEAR(d[k], 1.0, 1e-15); 63 } 64 } 65 { 66 Matrix2x2 A = Identity(); 67 A[0][1] = A[1][0] = 2.0; 68 Matrix2x2 U; 69 Vector2 d; 70 ConvertToDiagonal(A, d, U); 71 VerifyOrthogonal(U, 1e-12); 72 VerifyMatrixEqual(A, MatMul(U, MatMul(Diagonal(d), Transpose(U))), 1e-12); 73 } 74 Rng rng(0); 75 for (size_t i = 0; i < 100; ++i) { 76 Matrix2x2 A = RandomSymmetricMatrix(rng, -1.0, 1.0); 77 Matrix2x2 U; 78 Vector2 d; 79 ConvertToDiagonal(A, d, U); 80 VerifyOrthogonal(U, 1e-12); 81 VerifyMatrixEqual(A, MatMul(U, MatMul(Diagonal(d), Transpose(U))), 1e-12); 82 } 83 } 84 85 } // namespace 86 } // namespace jxl