1 // Copyright (c) 2017-2024, Lawrence Livermore National Security, LLC and other CEED contributors. 2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details. 3 // 4 // SPDX-License-Identifier: BSD-2-Clause 5 // 6 // This file is part of CEED: http://github.com/ceed 7 8 /// @file 9 /// Eigen system solver for symmetric NxN matrices. Modified from the CC0 code provided at https://github.com/jewettaij/jacobi_pd 10 #pragma once 11 12 #include <ceed.h> 13 #include <math.h> 14 15 #include "utils.h" 16 17 // @typedef choose the criteria for sorting eigenvalues and eigenvectors 18 typedef enum eSortCriteria { 19 SORT_NONE, 20 SORT_DECREASING_EVALS, 21 SORT_INCREASING_EVALS, 22 SORT_DECREASING_ABS_EVALS, 23 SORT_INCREASING_ABS_EVALS 24 } SortCriteria; 25 26 ///@brief Find the off-diagonal index in row i whose absolute value is largest 27 /// 28 /// @param[in] *A matrix 29 /// @param[in] i row index 30 /// @returns Index of absolute largest off-diagonal element in row i 31 CEED_QFUNCTION_HELPER CeedInt MaxEntryRow(const CeedScalar *A, CeedInt N, CeedInt i) { 32 CeedInt j_max = i + 1; 33 for (CeedInt j = i + 2; j < N; j++) 34 if (fabs(A[i * N + j]) > fabs(A[i * N + j_max])) j_max = j; 35 return j_max; 36 } 37 38 /// @brief Find the indices (i_max, j_max) marking the location of the 39 /// entry in the matrix with the largest absolute value. This 40 /// uses the max_idx_row[] array to find the answer in O(n) time. 41 /// 42 /// @param[in] *A matrix 43 /// @param[inout] i_max row index 44 /// @param[inout] j_max column index 45 CEED_QFUNCTION_HELPER void MaxEntry(const CeedScalar *A, CeedInt N, CeedInt *max_idx_row, CeedInt *i_max, CeedInt *j_max) { 46 *i_max = 0; 47 *j_max = max_idx_row[*i_max]; 48 CeedScalar max_entry = fabs(A[*i_max * N + *j_max]); 49 for (CeedInt i = 1; i < N - 1; i++) { 50 CeedInt j = max_idx_row[i]; 51 if (fabs(A[i * N + j]) > max_entry) { 52 max_entry = fabs(A[i * N + j]); 53 *i_max = i; 54 *j_max = j; 55 } 56 } 57 } 58 59 /// @brief Calculate the components of a rotation matrix which performs a 60 /// rotation in the i,j plane by an angle (θ) that (when multiplied on 61 /// both sides) will zero the ij'th element of A, so that afterwards 62 /// A[i][j] = 0. The results will be stored in c, s, and t 63 /// (which store cos(θ), sin(θ), and tan(θ), respectively). 64 /// 65 /// @param[in] *A matrix 66 /// @param[in] i row index 67 /// @param[in] j column index 68 CEED_QFUNCTION_HELPER void CalcRot(const CeedScalar *A, CeedInt N, CeedInt i, CeedInt j, CeedScalar *rotmat_cst) { 69 rotmat_cst[2] = 1.0; // = tan(θ) 70 CeedScalar A_jj_ii = (A[j * N + j] - A[i * N + i]); 71 if (A_jj_ii != 0.0) { 72 // kappa = (A[j][j] - A[i][i]) / (2*A[i][j]) 73 CeedScalar kappa = A_jj_ii; 74 rotmat_cst[2] = 0.0; 75 CeedScalar A_ij = A[i * N + j]; 76 if (A_ij != 0.0) { 77 kappa /= (2.0 * A_ij); 78 // t satisfies: t^2 + 2*t*kappa - 1 = 0 79 // (choose the root which has the smaller absolute value) 80 rotmat_cst[2] = 1.0 / (sqrt(1 + kappa * kappa) + fabs(kappa)); 81 if (kappa < 0.0) rotmat_cst[2] = -rotmat_cst[2]; 82 } 83 } 84 rotmat_cst[0] = 1.0 / sqrt(1 + rotmat_cst[2] * rotmat_cst[2]); 85 rotmat_cst[1] = rotmat_cst[0] * rotmat_cst[2]; 86 } 87 88 /// @brief Perform a similarity transformation by multiplying matrix A on both 89 /// sides by a rotation matrix (and its transpose) to eliminate A[i][j]. 90 /// @details This rotation matrix performs a rotation in the i,j plane by 91 /// angle θ. This function assumes that c=cos(θ). s=sin(θ), t=tan(θ) 92 /// have been calculated in advance (using the CalcRot() function). 93 /// It also assumes that i<j. The max_idx_row[] array is also updated. 94 /// To save time, since the matrix is symmetric, the elements 95 /// below the diagonal (ie. A[u][v] where u>v) are not computed. 96 /// @verbatim 97 /// A' = R^T * A * R 98 /// where R the rotation in the i,j plane and ^T denotes the transpose. 99 /// i j 100 /// _ _ 101 /// | 1 | 102 /// | . | 103 /// | . | 104 /// | 1 | 105 /// | c ... s | 106 /// | . . . | 107 /// R = | . 1 . | 108 /// | . . . | 109 /// | -s ... c | 110 /// | 1 | 111 /// | . | 112 /// | . | 113 /// |_ 1 _| 114 /// @endverbatim 115 /// 116 /// Let A' denote the matrix A after multiplication by R^T and R. 117 /// The components of A' are: 118 /// 119 /// @verbatim 120 /// A'_uv = Σ_w Σ_z R_wu * A_wz * R_zv 121 /// @endverbatim 122 /// 123 /// Note that a the rotation at location i,j will modify all of the matrix 124 /// elements containing at least one index which is either i or j 125 /// such as: A[w][i], A[i][w], A[w][j], A[j][w]. 126 /// Check and see whether these modified matrix elements exceed the 127 /// corresponding values in max_idx_row[] array for that row. 128 /// If so, then update max_idx_row for that row. 129 /// This is somewhat complicated by the fact that we must only consider 130 /// matrix elements in the upper-right triangle strictly above the diagonal. 131 /// (ie. matrix elements whose second index is > the first index). 132 /// The modified elements we must consider are marked with an "X" below: 133 /// 134 /// @verbatim 135 /// i j 136 /// _ _ 137 /// | . X X | 138 /// | . X X | 139 /// | . X X | 140 /// | . X X | 141 /// | X X X X X 0 X X X X | i 142 /// | . X | 143 /// | . X | 144 /// A = | . X | 145 /// | . X | 146 /// | X X X X X | j 147 /// | . | 148 /// | . | 149 /// | . | 150 /// |_ . _| 151 /// @endverbatim 152 /// 153 /// @param[in] *A matrix 154 /// @param[in] i row index 155 /// @param[in] j column index 156 CEED_QFUNCTION_HELPER void ApplyRot(CeedScalar *A, CeedInt N, CeedInt i, CeedInt j, CeedInt *max_idx_row, CeedScalar *rotmat_cst) { 157 // Compute the diagonal elements of A which have changed: 158 A[i * N + i] -= rotmat_cst[2] * A[i * N + j]; 159 A[j * N + j] += rotmat_cst[2] * A[i * N + j]; 160 // Note: This is algebraically equivalent to: 161 // A[i][i] = c*c*A[i][i] + s*s*A[j][j] - 2*s*c*A[i][j] 162 // A[j][j] = s*s*A[i][i] + c*c*A[j][j] + 2*s*c*A[i][j] 163 164 // Update the off-diagonal elements of A which will change (above the diagonal) 165 166 A[i * N + j] = 0.0; 167 168 // compute A[w][i] and A[i][w] for all w!=i,considering above-diagonal elements 169 for (CeedInt w = 0; w < i; w++) { // 0 <= w < i < j < N 170 A[i * N + w] = A[w * N + i]; // backup the previous value. store below diagonal (i>w) 171 A[w * N + i] = rotmat_cst[0] * A[w * N + i] - rotmat_cst[1] * A[w * N + j]; // A[w][i], A[w][j] from previous iteration 172 if (i == max_idx_row[w]) max_idx_row[w] = MaxEntryRow(A, N, w); 173 else if (fabs(A[w * N + i]) > fabs(A[w * N + max_idx_row[w]])) max_idx_row[w] = i; 174 } 175 for (CeedInt w = i + 1; w < j; w++) { // 0 <= i < w < j < N 176 A[w * N + i] = A[i * N + w]; // backup the previous value. store below diagonal (w>i) 177 A[i * N + w] = rotmat_cst[0] * A[i * N + w] - rotmat_cst[1] * A[w * N + j]; // A[i][w], A[w][j] from previous iteration 178 } 179 for (CeedInt w = j + 1; w < N; w++) { // 0 <= i < j+1 <= w < N 180 A[w * N + i] = A[i * N + w]; // backup the previous value. store below diagonal (w>i) 181 A[i * N + w] = rotmat_cst[0] * A[i * N + w] - rotmat_cst[1] * A[j * N + w]; // A[i][w], A[j][w] from previous iteration 182 } 183 184 // now that we're done modifying row i, we can update max_idx_row[i] 185 max_idx_row[i] = MaxEntryRow(A, N, i); 186 187 // compute A[w][j] and A[j][w] for all w!=j,considering above-diagonal elements 188 for (CeedInt w = 0; w < i; w++) { // 0 <= w < i < j < N 189 A[w * N + j] = rotmat_cst[1] * A[i * N + w] + rotmat_cst[0] * A[w * N + j]; // A[i][w], A[w][j] from previous iteration 190 if (j == max_idx_row[w]) max_idx_row[w] = MaxEntryRow(A, N, w); 191 else if (fabs(A[w * N + j]) > fabs(A[w * N + max_idx_row[w]])) max_idx_row[w] = j; 192 } 193 for (CeedInt w = i + 1; w < j; w++) { // 0 <= i+1 <= w < j < N 194 A[w * N + j] = rotmat_cst[1] * A[w * N + i] + rotmat_cst[0] * A[w * N + j]; // A[w][i], A[w][j] from previous iteration 195 if (j == max_idx_row[w]) max_idx_row[w] = MaxEntryRow(A, N, w); 196 else if (fabs(A[w * N + j]) > fabs(A[w * N + max_idx_row[w]])) max_idx_row[w] = j; 197 } 198 for (CeedInt w = j + 1; w < N; w++) { // 0 <= i < j < w < N 199 A[j * N + w] = rotmat_cst[1] * A[w * N + i] + rotmat_cst[0] * A[j * N + w]; // A[w][i], A[j][w] from previous iteration 200 } 201 // now that we're done modifying row j, we can update max_idx_row[j] 202 max_idx_row[j] = MaxEntryRow(A, N, j); 203 } 204 205 ///@brief Multiply matrix A on the LEFT side by a transposed rotation matrix R^T 206 /// This matrix performs a rotation in the i,j plane by angle θ (where 207 /// the arguments "s" and "c" refer to cos(θ) and sin(θ), respectively). 208 /// @verbatim 209 /// A'_uv = Σ_w R_wu * A_wv 210 /// @endverbatim 211 /// 212 /// @param[in] *A matrix 213 /// @param[in] i row index 214 /// @param[in] j column index 215 CEED_QFUNCTION_HELPER void ApplyRotLeft(CeedScalar *A, CeedInt N, CeedInt i, CeedInt j, CeedScalar *rotmat_cst) { 216 // Recall that c = cos(θ) and s = sin(θ) 217 for (CeedInt v = 0; v < N; v++) { 218 CeedScalar Aiv = A[i * N + v]; 219 A[i * N + v] = rotmat_cst[0] * A[i * N + v] - rotmat_cst[1] * A[j * N + v]; 220 A[j * N + v] = rotmat_cst[1] * Aiv + rotmat_cst[0] * A[j * N + v]; 221 } 222 } 223 224 /// @brief Sort the rows in evec according to the numbers in v (also sorted) 225 /// 226 /// @param[inout] *eval vector containing the keys used for sorting 227 /// @param[inout] *evec matrix whose rows will be sorted according to v 228 /// @param[in] n size of the vector and matrix 229 /// @param[in] s sort decreasing order? 230 CEED_QFUNCTION_HELPER void SortRows(CeedScalar *eval, CeedScalar *evec, CeedInt N, SortCriteria sort_criteria) { 231 if (sort_criteria == SORT_NONE) return; 232 233 for (CeedInt i = 0; i < N - 1; i++) { 234 CeedInt i_max = i; 235 for (CeedInt j = i + 1; j < N; j++) { 236 // find the "maximum" element in the array starting at position i+1 237 switch (sort_criteria) { 238 case SORT_DECREASING_EVALS: 239 if (eval[j] > eval[i_max]) i_max = j; 240 break; 241 case SORT_INCREASING_EVALS: 242 if (eval[j] < eval[i_max]) i_max = j; 243 break; 244 case SORT_DECREASING_ABS_EVALS: 245 if (fabs(eval[j]) > fabs(eval[i_max])) i_max = j; 246 break; 247 case SORT_INCREASING_ABS_EVALS: 248 if (fabs(eval[j]) < fabs(eval[i_max])) i_max = j; 249 break; 250 default: 251 break; 252 } 253 } 254 SwapScalar(&eval[i], &eval[i_max]); 255 for (CeedInt k = 0; k < N; k++) SwapScalar(&evec[i * N + k], &evec[i_max * N + k]); 256 } 257 } 258 259 /// @brief Calculate all the eigenvalues and eigevectors of a symmetric matrix 260 /// using the Jacobi eigenvalue algorithm: 261 /// https://en.wikipedia.org/wiki/Jacobi_eigenvalue_algorithm 262 /// @returns The number of Jacobi iterations attempted, which should be > 0. 263 /// If the return value is not strictly > 0 then convergence failed. 264 /// @note To reduce the computation time further, set calc_evecs=false. 265 /// Additionally, note that the output evecs should be normalized. It 266 /// simply takes the Identity matrix and performs (isometric) rotations 267 /// on it, so divergence from normalized is due to finite-precision 268 /// arithmetic of the rotations. 269 // 270 // @param[in] A the matrix you wish to diagonalize (size NxN) 271 // @param[in] N size of the matrix 272 // @param[out] eval store the eigenvalues here (size N) 273 // @param[out] evec store the eigenvectors here (in rows, size NxN) 274 // @param[out] max_idx_row work vector of size N 275 // @param[in] sort_criteria sort results? 276 // @param[in] calc_evecs calculate the eigenvectors? 277 // @param[in] max_num_sweeps maximum number of iterations = max_num_sweeps * number of off-diagonals (N*(N-1)/2) 278 CEED_QFUNCTION_HELPER CeedInt Diagonalize(CeedScalar *A, CeedInt N, CeedScalar *eval, CeedScalar *evec, CeedInt *max_idx_row, 279 SortCriteria sort_criteria, bool calc_evec, const CeedInt max_num_sweeps) { 280 CeedScalar rotmat_cst[3] = {0.}; // cos(θ), sin(θ), and tan(θ), 281 282 if (calc_evec) 283 for (CeedInt i = 0; i < N; i++) 284 for (CeedInt j = 0; j < N; j++) evec[i * N + j] = (i == j) ? 1.0 : 0.0; // Set evec equal to the identity matrix 285 286 for (CeedInt i = 0; i < N - 1; i++) max_idx_row[i] = MaxEntryRow(A, N, i); 287 288 // -- Iteration -- 289 CeedInt n_iters; 290 CeedInt max_num_iters = max_num_sweeps * N * (N - 1) / 2; 291 for (n_iters = 1; n_iters <= max_num_iters; n_iters++) { 292 CeedInt i, j; 293 MaxEntry(A, N, max_idx_row, &i, &j); 294 295 // If A[i][j] is small compared to A[i][i] and A[j][j], set it to 0. 296 if ((A[i * N + i] + A[i * N + j] == A[i * N + i]) && (A[j * N + j] + A[i * N + j] == A[j * N + j])) { 297 A[i * N + j] = 0.0; 298 max_idx_row[i] = MaxEntryRow(A, N, i); 299 } 300 301 if (A[i * N + j] == 0.0) break; 302 303 CalcRot(A, N, i, j, rotmat_cst); // Calculate the parameters of the rotation matrix. 304 ApplyRot(A, N, i, j, max_idx_row, rotmat_cst); // Apply this rotation to the A matrix. 305 if (calc_evec) ApplyRotLeft(evec, N, i, j, rotmat_cst); 306 } 307 308 for (CeedInt i = 0; i < N; i++) eval[i] = A[i * N + i]; 309 310 // Optional: Sort results by eigenvalue. 311 SortRows(eval, evec, N, sort_criteria); 312 313 if ((n_iters > max_num_iters) && (N > 1)) // If we exceeded max_num_iters, 314 return 0; // indicate an error occured. 315 316 return n_iters; 317 } 318 319 // @brief Interface to Diagonalize for 3x3 systems 320 CEED_QFUNCTION_HELPER CeedInt Diagonalize3(CeedScalar A[3][3], CeedScalar eval[3], CeedScalar evec[3][3], CeedInt max_idx_row[3], 321 SortCriteria sort_criteria, bool calc_evec, const CeedInt max_num_sweeps) { 322 return Diagonalize((CeedScalar *)A, 3, (CeedScalar *)eval, (CeedScalar *)evec, (CeedInt *)max_idx_row, sort_criteria, calc_evec, max_num_sweeps); 323 } 324