1 // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at 2 // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights 3 // reserved. See files LICENSE and NOTICE for details. 4 // 5 // This file is part of CEED, a collection of benchmarks, miniapps, software 6 // libraries and APIs for efficient high-order finite element and spectral 7 // element discretizations for exascale applications. For more information and 8 // source code availability see http://github.com/ceed. 9 // 10 // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, 11 // a collaborative effort of two U.S. Department of Energy organizations (Office 12 // of Science and the National Nuclear Security Administration) responsible for 13 // the planning and preparation of a capable exascale ecosystem, including 14 // software, applications, hardware, advanced system engineering and early 15 // testbed platforms, in support of the nation's exascale computing imperative. 16 17 #include <ceed-impl.h> 18 #include <ceed-backend.h> 19 #include <math.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 24 /// @cond DOXYGEN_SKIP 25 static struct CeedBasis_private ceed_basis_collocated; 26 /// @endcond 27 28 /// @file 29 /// Implementation of public CeedBasis interfaces 30 /// 31 /// @addtogroup CeedBasis 32 /// @{ 33 34 /** 35 @brief Create a tensor product basis for H^1 discretizations 36 37 @param ceed A Ceed object where the CeedBasis will be created 38 @param dim Topological dimension 39 @param ncomp Number of field components (1 for scalar fields) 40 @param P1d Number of nodes in one dimension 41 @param Q1d Number of quadrature points in one dimension 42 @param interp1d Row-major Q1d × P1d matrix expressing the values of nodal 43 basis functions at quadrature points 44 @param grad1d Row-major Q1d × P1d matrix expressing derivatives of nodal 45 basis functions at quadrature points 46 @param qref1d Array of length Q1d holding the locations of quadrature points 47 on the 1D reference element [-1, 1] 48 @param qweight1d Array of length Q1d holding the quadrature weights on the 49 reference element 50 @param[out] basis Address of the variable where the newly created 51 CeedBasis will be stored. 52 53 @return An error code: 0 - success, otherwise - failure 54 55 @ref Basic 56 **/ 57 int CeedBasisCreateTensorH1(Ceed ceed, CeedInt dim, CeedInt ncomp, CeedInt P1d, 58 CeedInt Q1d, const CeedScalar *interp1d, 59 const CeedScalar *grad1d, const CeedScalar *qref1d, 60 const CeedScalar *qweight1d, CeedBasis *basis) { 61 int ierr; 62 63 if (dim<1) 64 return CeedError(ceed, 1, "Basis dimension must be a positive value"); 65 66 if (!ceed->BasisCreateTensorH1) { 67 Ceed delegate; 68 ierr = CeedGetObjectDelegate(ceed, &delegate, "Basis"); CeedChk(ierr); 69 70 if (!delegate) 71 return CeedError(ceed, 1, "Backend does not support BasisCreateTensorH1"); 72 73 ierr = CeedBasisCreateTensorH1(delegate, dim, ncomp, P1d, 74 Q1d, interp1d, grad1d, qref1d, 75 qweight1d, basis); CeedChk(ierr); 76 return 0; 77 } 78 ierr = CeedCalloc(1,basis); CeedChk(ierr); 79 (*basis)->ceed = ceed; 80 ceed->refcount++; 81 (*basis)->refcount = 1; 82 (*basis)->tensorbasis = 1; 83 (*basis)->dim = dim; 84 (*basis)->ncomp = ncomp; 85 (*basis)->P1d = P1d; 86 (*basis)->Q1d = Q1d; 87 (*basis)->P = CeedIntPow(P1d, dim); 88 (*basis)->Q = CeedIntPow(Q1d, dim); 89 ierr = CeedMalloc(Q1d,&(*basis)->qref1d); CeedChk(ierr); 90 ierr = CeedMalloc(Q1d,&(*basis)->qweight1d); CeedChk(ierr); 91 memcpy((*basis)->qref1d, qref1d, Q1d*sizeof(qref1d[0])); 92 memcpy((*basis)->qweight1d, qweight1d, Q1d*sizeof(qweight1d[0])); 93 ierr = CeedMalloc(Q1d*P1d,&(*basis)->interp1d); CeedChk(ierr); 94 ierr = CeedMalloc(Q1d*P1d,&(*basis)->grad1d); CeedChk(ierr); 95 memcpy((*basis)->interp1d, interp1d, Q1d*P1d*sizeof(interp1d[0])); 96 memcpy((*basis)->grad1d, grad1d, Q1d*P1d*sizeof(grad1d[0])); 97 ierr = ceed->BasisCreateTensorH1(dim, P1d, Q1d, interp1d, grad1d, qref1d, 98 qweight1d, *basis); CeedChk(ierr); 99 return 0; 100 } 101 102 /** 103 @brief Create a tensor product Lagrange basis 104 105 @param ceed A Ceed object where the CeedBasis will be created 106 @param dim Topological dimension of element 107 @param ncomp Number of field components 108 @param P Number of Gauss-Lobatto nodes in one dimension. The 109 polynomial degree of the resulting Q_k element is k=P-1. 110 @param Q Number of quadrature points in one dimension. 111 @param qmode Distribution of the Q quadrature points (affects order of 112 accuracy for the quadrature) 113 @param[out] basis Address of the variable where the newly created 114 CeedBasis will be stored. 115 116 @return An error code: 0 - success, otherwise - failure 117 118 @ref Basic 119 **/ 120 int CeedBasisCreateTensorH1Lagrange(Ceed ceed, CeedInt dim, CeedInt ncomp, 121 CeedInt P, CeedInt Q, 122 CeedQuadMode qmode, CeedBasis *basis) { 123 // Allocate 124 int ierr, i, j, k; 125 CeedScalar c1, c2, c3, c4, dx, *nodes, *interp1d, *grad1d, *qref1d, *qweight1d; 126 127 if (dim<1) 128 return CeedError(ceed, 1, "Basis dimension must be a positive value"); 129 130 ierr = CeedCalloc(P*Q, &interp1d); CeedChk(ierr); 131 ierr = CeedCalloc(P*Q, &grad1d); CeedChk(ierr); 132 ierr = CeedCalloc(P, &nodes); CeedChk(ierr); 133 ierr = CeedCalloc(Q, &qref1d); CeedChk(ierr); 134 ierr = CeedCalloc(Q, &qweight1d); CeedChk(ierr); 135 // Get Nodes and Weights 136 ierr = CeedLobattoQuadrature(P, nodes, NULL); CeedChk(ierr); 137 switch (qmode) { 138 case CEED_GAUSS: 139 ierr = CeedGaussQuadrature(Q, qref1d, qweight1d); CeedChk(ierr); 140 break; 141 case CEED_GAUSS_LOBATTO: 142 ierr = CeedLobattoQuadrature(Q, qref1d, qweight1d); CeedChk(ierr); 143 break; 144 } 145 // Build B, D matrix 146 // Fornberg, 1998 147 for (i = 0; i < Q; i++) { 148 c1 = 1.0; 149 c3 = nodes[0] - qref1d[i]; 150 interp1d[i*P+0] = 1.0; 151 for (j = 1; j < P; j++) { 152 c2 = 1.0; 153 c4 = c3; 154 c3 = nodes[j] - qref1d[i]; 155 for (k = 0; k < j; k++) { 156 dx = nodes[j] - nodes[k]; 157 c2 *= dx; 158 if (k == j - 1) { 159 grad1d[i*P + j] = c1*(interp1d[i*P + k] - c4*grad1d[i*P + k]) / c2; 160 interp1d[i*P + j] = - c1*c4*interp1d[i*P + k] / c2; 161 } 162 grad1d[i*P + k] = (c3*grad1d[i*P + k] - interp1d[i*P + k]) / dx; 163 interp1d[i*P + k] = c3*interp1d[i*P + k] / dx; 164 } 165 c1 = c2; 166 } 167 } 168 // // Pass to CeedBasisCreateTensorH1 169 ierr = CeedBasisCreateTensorH1(ceed, dim, ncomp, P, Q, interp1d, grad1d, qref1d, 170 qweight1d, basis); CeedChk(ierr); 171 ierr = CeedFree(&interp1d); CeedChk(ierr); 172 ierr = CeedFree(&grad1d); CeedChk(ierr); 173 ierr = CeedFree(&nodes); CeedChk(ierr); 174 ierr = CeedFree(&qref1d); CeedChk(ierr); 175 ierr = CeedFree(&qweight1d); CeedChk(ierr); 176 return 0; 177 } 178 179 /** 180 @brief Create a non tensor product basis for H^1 discretizations 181 182 @param ceed A Ceed object where the CeedBasis will be created 183 @param topo Topology of element, e.g. hypercube, simplex, ect 184 @param ncomp Number of field components (1 for scalar fields) 185 @param nnodes Total number of nodes 186 @param nqpts Total number of quadrature points 187 @param interp Row-major nqpts × nnodes matrix expressing the values of 188 nodal basis functions at quadrature points 189 @param grad Row-major (nqpts x dim) × nnodes matrix expressing 190 derivatives of nodal basis functions at quadrature points 191 @param qref Array of length nqpts holding the locations of quadrature 192 points on the reference element [-1, 1] 193 @param qweight Array of length nqpts holding the quadrature weights on the 194 reference element 195 @param[out] basis Address of the variable where the newly created 196 CeedBasis will be stored. 197 198 @return An error code: 0 - success, otherwise - failure 199 200 @ref Basic 201 **/ 202 int CeedBasisCreateH1(Ceed ceed, CeedElemTopology topo, CeedInt ncomp, 203 CeedInt nnodes, CeedInt nqpts, 204 const CeedScalar *interp, 205 const CeedScalar *grad, const CeedScalar *qref, 206 const CeedScalar *qweight, CeedBasis *basis) { 207 int ierr; 208 CeedInt P = nnodes, Q = nqpts, dim = 0; 209 210 if (!ceed->BasisCreateH1) { 211 Ceed delegate; 212 ierr = CeedGetObjectDelegate(ceed, &delegate, "Basis"); CeedChk(ierr); 213 214 if (!delegate) 215 return CeedError(ceed, 1, "Backend does not support BasisCreateH1"); 216 217 ierr = CeedBasisCreateH1(delegate, topo, ncomp, nnodes, 218 nqpts, interp, grad, qref, 219 qweight, basis); CeedChk(ierr); 220 return 0; 221 } 222 223 ierr = CeedCalloc(1,basis); CeedChk(ierr); 224 225 ierr = CeedBasisGetTopologyDimension(topo, &dim); CeedChk(ierr); 226 227 (*basis)->ceed = ceed; 228 ceed->refcount++; 229 (*basis)->refcount = 1; 230 (*basis)->tensorbasis = 0; 231 (*basis)->dim = dim; 232 (*basis)->ncomp = ncomp; 233 (*basis)->P = P; 234 (*basis)->Q = Q; 235 ierr = CeedMalloc(Q*dim,&(*basis)->qref1d); CeedChk(ierr); 236 ierr = CeedMalloc(Q,&(*basis)->qweight1d); CeedChk(ierr); 237 memcpy((*basis)->qref1d, qref, Q*dim*sizeof(qref[0])); 238 memcpy((*basis)->qweight1d, qweight, Q*sizeof(qweight[0])); 239 ierr = CeedMalloc(Q*P,&(*basis)->interp1d); CeedChk(ierr); 240 ierr = CeedMalloc(dim*Q*P,&(*basis)->grad1d); CeedChk(ierr); 241 memcpy((*basis)->interp1d, interp, Q*P*sizeof(interp[0])); 242 memcpy((*basis)->grad1d, grad, dim*Q*P*sizeof(grad[0])); 243 ierr = ceed->BasisCreateH1(topo, dim, P, Q, interp, grad, qref, 244 qweight, *basis); CeedChk(ierr); 245 return 0; 246 } 247 248 /** 249 @brief Construct a Gauss-Legendre quadrature 250 251 @param Q Number of quadrature points (integrates polynomials of 252 degree 2*Q-1 exactly) 253 @param[out] qref1d Array of length Q to hold the abscissa on [-1, 1] 254 @param[out] qweight1d Array of length Q to hold the weights 255 256 @return An error code: 0 - success, otherwise - failure 257 258 @ref Utility 259 **/ 260 int CeedGaussQuadrature(CeedInt Q, CeedScalar *qref1d, CeedScalar *qweight1d) { 261 // Allocate 262 CeedScalar P0, P1, P2, dP2, xi, wi, PI = 4.0*atan(1.0); 263 // Build qref1d, qweight1d 264 for (int i = 0; i <= Q/2; i++) { 265 // Guess 266 xi = cos(PI*(CeedScalar)(2*i+1)/((CeedScalar)(2*Q))); 267 // Pn(xi) 268 P0 = 1.0; 269 P1 = xi; 270 P2 = 0.0; 271 for (int j = 2; j <= Q; j++) { 272 P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j)); 273 P0 = P1; 274 P1 = P2; 275 } 276 // First Newton Step 277 dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0); 278 xi = xi-P2/dP2; 279 // Newton to convergence 280 for (int k=0; k<100 && fabs(P2)>1e-15; k++) { 281 P0 = 1.0; 282 P1 = xi; 283 for (int j = 2; j <= Q; j++) { 284 P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j)); 285 P0 = P1; 286 P1 = P2; 287 } 288 dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0); 289 xi = xi-P2/dP2; 290 } 291 // Save xi, wi 292 wi = 2.0/((1.0-xi*xi)*dP2*dP2); 293 qweight1d[i] = wi; 294 qweight1d[Q-1-i] = wi; 295 qref1d[i] = -xi; 296 qref1d[Q-1-i]= xi; 297 } 298 return 0; 299 } 300 301 /** 302 @brief Construct a Gauss-Legendre-Lobatto quadrature 303 304 @param Q Number of quadrature points (integrates polynomials of 305 degree 2*Q-3 exactly) 306 @param[out] qref1d Array of length Q to hold the abscissa on [-1, 1] 307 @param[out] qweight1d Array of length Q to hold the weights 308 309 @return An error code: 0 - success, otherwise - failure 310 311 @ref Utility 312 **/ 313 int CeedLobattoQuadrature(CeedInt Q, CeedScalar *qref1d, 314 CeedScalar *qweight1d) { 315 // Allocate 316 CeedScalar P0, P1, P2, dP2, d2P2, xi, wi, PI = 4.0*atan(1.0); 317 // Build qref1d, qweight1d 318 // Set endpoints 319 wi = 2.0/((CeedScalar)(Q*(Q-1))); 320 if (qweight1d) { 321 qweight1d[0] = wi; 322 qweight1d[Q-1] = wi; 323 } 324 qref1d[0] = -1.0; 325 qref1d[Q-1] = 1.0; 326 // Interior 327 for (int i = 1; i <= (Q-1)/2; i++) { 328 // Guess 329 xi = cos(PI*(CeedScalar)(i)/(CeedScalar)(Q-1)); 330 // Pn(xi) 331 P0 = 1.0; 332 P1 = xi; 333 P2 = 0.0; 334 for (int j = 2; j < Q; j++) { 335 P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j)); 336 P0 = P1; 337 P1 = P2; 338 } 339 // First Newton step 340 dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0); 341 d2P2 = (2*xi*dP2 - (CeedScalar)(Q*(Q-1))*P2)/(1.0-xi*xi); 342 xi = xi-dP2/d2P2; 343 // Newton to convergence 344 for (int k=0; k<100 && fabs(dP2)>1e-15; k++) { 345 P0 = 1.0; 346 P1 = xi; 347 for (int j = 2; j < Q; j++) { 348 P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j)); 349 P0 = P1; 350 P1 = P2; 351 } 352 dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0); 353 d2P2 = (2*xi*dP2 - (CeedScalar)(Q*(Q-1))*P2)/(1.0-xi*xi); 354 xi = xi-dP2/d2P2; 355 } 356 // Save xi, wi 357 wi = 2.0/(((CeedScalar)(Q*(Q-1)))*P2*P2); 358 if (qweight1d) { 359 qweight1d[i] = wi; 360 qweight1d[Q-1-i] = wi; 361 } 362 qref1d[i] = -xi; 363 qref1d[Q-1-i]= xi; 364 } 365 return 0; 366 } 367 368 /** 369 @brief View an array stored in a CeedBasis 370 371 @param name Name of array 372 @param fpformat Printing format 373 @param m Number of rows in array 374 @param n Number of columns in array 375 @param a Array to be viewed 376 @param stream Stream to view to, e.g., stdout 377 378 @return An error code: 0 - success, otherwise - failure 379 380 @ref Utility 381 **/ 382 static int CeedScalarView(const char *name, const char *fpformat, CeedInt m, 383 CeedInt n, const CeedScalar *a, FILE *stream) { 384 for (int i=0; i<m; i++) { 385 if (m > 1) fprintf(stream, "%12s[%d]:", name, i); 386 else fprintf(stream, "%12s:", name); 387 for (int j=0; j<n; j++) { 388 fprintf(stream, fpformat, fabs(a[i*n+j]) > 1E-14 ? a[i*n+j] : 0); 389 } 390 fputs("\n", stream); 391 } 392 return 0; 393 } 394 395 /** 396 @brief View a CeedBasis 397 398 @param basis CeedBasis to view 399 @param stream Stream to view to, e.g., stdout 400 401 @return An error code: 0 - success, otherwise - failure 402 403 @ref Utility 404 **/ 405 int CeedBasisView(CeedBasis basis, FILE *stream) { 406 int ierr; 407 408 if (basis->tensorbasis) { 409 fprintf(stream, "CeedBasis: dim=%d P=%d Q=%d\n", basis->dim, basis->P1d, 410 basis->Q1d); 411 ierr = CeedScalarView("qref1d", "\t% 12.8f", 1, basis->Q1d, basis->qref1d, 412 stream); CeedChk(ierr); 413 ierr = CeedScalarView("qweight1d", "\t% 12.8f", 1, basis->Q1d, 414 basis->qweight1d, stream); CeedChk(ierr); 415 ierr = CeedScalarView("interp1d", "\t% 12.8f", basis->Q1d, basis->P1d, 416 basis->interp1d, stream); CeedChk(ierr); 417 ierr = CeedScalarView("grad1d", "\t% 12.8f", basis->Q1d, basis->P1d, 418 basis->grad1d, stream); CeedChk(ierr); 419 } else { 420 fprintf(stream, "CeedBasis: dim=%d P=%d Q=%d\n", basis->dim, basis->P, 421 basis->Q); 422 ierr = CeedScalarView("qref", "\t% 12.8f", 1, basis->Q*basis->dim, 423 basis->qref1d, 424 stream); CeedChk(ierr); 425 ierr = CeedScalarView("qweight", "\t% 12.8f", 1, basis->Q, basis->qweight1d, 426 stream); CeedChk(ierr); 427 ierr = CeedScalarView("interp", "\t% 12.8f", basis->Q, basis->P, 428 basis->interp1d, stream); CeedChk(ierr); 429 ierr = CeedScalarView("grad", "\t% 12.8f", basis->dim*basis->Q, basis->P, 430 basis->grad1d, stream); CeedChk(ierr); 431 } 432 return 0; 433 } 434 435 /** 436 @brief Compute Householder reflection 437 438 Computes A = (I - b v v^T) A 439 where A is an mxn matrix indexed as A[i*row + j*col] 440 441 @param[in,out] A Matrix to apply Householder reflection to, in place 442 @param v Householder vector 443 @param b Scaling factor 444 @param m Number of rows in A 445 @param n Number of columns in A 446 @param row Row stride 447 @param col Col stride 448 449 @return An error code: 0 - success, otherwise - failure 450 451 @ref Developer 452 **/ 453 static int CeedHouseholderReflect(CeedScalar *A, const CeedScalar *v, 454 CeedScalar b, CeedInt m, CeedInt n, 455 CeedInt row, CeedInt col) { 456 for (CeedInt j=0; j<n; j++) { 457 CeedScalar w = A[0*row + j*col]; 458 for (CeedInt i=1; i<m; i++) w += v[i] * A[i*row + j*col]; 459 A[0*row + j*col] -= b * w; 460 for (CeedInt i=1; i<m; i++) A[i*row + j*col] -= b * w * v[i]; 461 } 462 return 0; 463 } 464 465 /** 466 @brief Apply Householder Q matrix 467 468 Compute A = Q A where Q is mxm and A is mxn. 469 470 @param[in,out] A Matrix to apply Householder Q to, in place 471 @param Q Householder Q matrix 472 @param tau Householder scaling factors 473 @param tmode Transpose mode for application 474 @param m Number of rows in A 475 @param n Number of columns in A 476 @param k Number of elementary reflectors in Q, k<m 477 @param row Row stride in A 478 @param col Col stride in A 479 480 @return An error code: 0 - success, otherwise - failure 481 482 @ref Developer 483 **/ 484 static int CeedHouseholderApplyQ(CeedScalar *A, const CeedScalar *Q, 485 const CeedScalar *tau, CeedTransposeMode tmode, 486 CeedInt m, CeedInt n, CeedInt k, 487 CeedInt row, CeedInt col) { 488 CeedScalar v[m]; 489 for (CeedInt ii=0; ii<k; ii++) { 490 CeedInt i = tmode == CEED_TRANSPOSE ? ii : k-1-ii; 491 for (CeedInt j=i+1; j<m; j++) 492 v[j] = Q[j*k+i]; 493 // Apply Householder reflector (I - tau v v^T) colograd1d^T 494 CeedHouseholderReflect(&A[i*row], &v[i], tau[i], m-i, n, row, col); 495 } 496 return 0; 497 } 498 499 /** 500 @brief Compute Givens rotation 501 502 Computes A = G A (or G^T A in transpose mode) 503 where A is an mxn matrix indexed as A[i*n + j*m] 504 505 @param[in,out] A Row major matrix to apply Givens rotation to, in place 506 @param c Cosine factor 507 @param s Sine factor 508 @param i First row/column to apply rotation 509 @param k Second row/column to apply rotation 510 @param m Number of rows in A 511 @param n Number of columns in A 512 513 @return An error code: 0 - success, otherwise - failure 514 515 @ref Developer 516 **/ 517 static int CeedGivensRotation(CeedScalar *A, CeedScalar c, CeedScalar s, 518 CeedTransposeMode tmode, CeedInt i, CeedInt k, 519 CeedInt m, CeedInt n) { 520 CeedInt stridej = 1, strideik = m, numits = n; 521 if (tmode == CEED_NOTRANSPOSE) { 522 stridej = n; strideik = 1; numits = m; 523 } 524 525 // Apply rotation 526 for (CeedInt j=0; j<numits; j++) { 527 CeedScalar tau1 = A[i*strideik+j*stridej], tau2 = A[k*strideik+j*stridej]; 528 A[i*strideik+j*stridej] = c*tau1 - s*tau2; 529 A[k*strideik+j*stridej] = s*tau1 + c*tau2; 530 } 531 532 return 0; 533 } 534 535 /** 536 @brief Return QR Factorization of matrix 537 538 @param ceed A Ceed object currently in use 539 @param[in,out] mat Row-major matrix to be factorized in place 540 @param[in,out] tau Vector of length m of scaling factors 541 @param m Number of rows 542 @param n Number of columns 543 544 @return An error code: 0 - success, otherwise - failure 545 546 @ref Utility 547 **/ 548 int CeedQRFactorization(Ceed ceed, CeedScalar *mat, CeedScalar *tau, 549 CeedInt m, CeedInt n) { 550 CeedScalar v[m]; 551 552 // Check m >= n 553 if (n > m) 554 return CeedError(ceed, 1, "Cannot compute QR factorization with n > m"); 555 556 for (CeedInt i=0; i<n; i++) { 557 // Calculate Householder vector, magnitude 558 CeedScalar sigma = 0.0; 559 v[i] = mat[i+n*i]; 560 for (CeedInt j=i+1; j<m; j++) { 561 v[j] = mat[i+n*j]; 562 sigma += v[j] * v[j]; 563 } 564 CeedScalar norm = sqrt(v[i]*v[i] + sigma); // norm of v[i:m] 565 CeedScalar Rii = -copysign(norm, v[i]); 566 v[i] -= Rii; 567 // norm of v[i:m] after modification above and scaling below 568 // norm = sqrt(v[i]*v[i] + sigma) / v[i]; 569 // tau = 2 / (norm*norm) 570 tau[i] = 2 * v[i]*v[i] / (v[i]*v[i] + sigma); 571 for (CeedInt j=i+1; j<m; j++) v[j] /= v[i]; 572 573 // Apply Householder reflector to lower right panel 574 CeedHouseholderReflect(&mat[i*n+i+1], &v[i], tau[i], m-i, n-i-1, n, 1); 575 // Save v 576 mat[i+n*i] = Rii; 577 for (CeedInt j=i+1; j<m; j++) { 578 mat[i+n*j] = v[j]; 579 } 580 } 581 582 return 0; 583 } 584 585 /** 586 @brief Return symmetric Schur decomposition of the symmetric matrix mat via 587 symmetric QR factorization 588 589 @param[in,out] mat Row-major matrix to be factorized in place 590 @param[out] lambda Vector of length m of eigenvalues 591 @param n Number of rows/columns 592 593 @return An error code: 0 - success, otherwise - failure 594 595 @ref Utility 596 **/ 597 int CeedSymmetricSchurDecomposition(Ceed ceed, CeedScalar *mat, 598 CeedScalar *lambda, CeedInt n) { 599 // Check bounds for clang-tidy 600 if (n<2) 601 return CeedError(ceed, 1, "Cannot compute symmetric Schur decomposition of scalars"); 602 603 CeedScalar v[n-1], tau[n-1], matT[n*n]; 604 605 // Copy mat to matT and set mat to I 606 memcpy(matT, mat, n*n*sizeof(mat[0])); 607 for (CeedInt i=0; i<n; i++) 608 for (CeedInt j=0; j<n; j++) 609 mat[j+n*i] = (i==j) ? 1 : 0; 610 611 // Reduce to tridiagonal 612 for (CeedInt i=0; i<n-1; i++) { 613 // Calculate Householder vector, magnitude 614 CeedScalar sigma = 0.0; 615 v[i] = matT[i+n*(i+1)]; 616 for (CeedInt j=i+1; j<n-1; j++) { 617 v[j] = matT[i+n*(j+1)]; 618 sigma += v[j] * v[j]; 619 } 620 CeedScalar norm = sqrt(v[i]*v[i] + sigma); // norm of v[i:n-1] 621 CeedScalar Rii = -copysign(norm, v[i]); 622 v[i] -= Rii; 623 // norm of v[i:m] after modification above and scaling below 624 // norm = sqrt(v[i]*v[i] + sigma) / v[i]; 625 // tau = 2 / (norm*norm) 626 tau[i] = 2 * v[i]*v[i] / (v[i]*v[i] + sigma); 627 for (CeedInt j=i+1; j<n-1; j++) v[j] /= v[i]; 628 629 // Update sub and super diagonal 630 matT[i+n*(i+1)] = Rii; 631 matT[(i+1)+n*i] = Rii; 632 for (CeedInt j=i+2; j<n; j++) { 633 matT[i+n*j] = 0; matT[j+n*i] = 0; 634 } 635 // Apply symmetric Householder reflector to lower right panel 636 CeedHouseholderReflect(&matT[(i+1)+n*(i+1)], &v[i], tau[i], 637 n-(i+1), n-(i+1), n, 1); 638 CeedHouseholderReflect(&matT[(i+1)+n*(i+1)], &v[i], tau[i], 639 n-(i+1), n-(i+1), 1, n); 640 // Save v 641 for (CeedInt j=i+1; j<n-1; j++) { 642 matT[i+n*(j+1)] = v[j]; 643 } 644 } 645 // Backwards accumulation of Q 646 for (CeedInt i=n-2; i>=0; i--) { 647 v[i] = 1; 648 for (CeedInt j=i+1; j<n-1; j++) { 649 v[j] = matT[i+n*(j+1)]; 650 matT[i+n*(j+1)] = 0; 651 } 652 CeedHouseholderReflect(&mat[(i+1)+n*(i+1)], &v[i], tau[i], 653 n-(i+1), n-(i+1), n, 1); 654 } 655 656 // Reduce sub and super diagonal 657 CeedInt p = 0, q = 0, itr = 0, maxitr = n*n*n; 658 CeedScalar tol = 1e-15; 659 660 while (q < n && itr < maxitr) { 661 // Update p, q, size of reduced portions of diagonal 662 p = 0; q = 0; 663 for (CeedInt i=n-2; i>=0; i--) { 664 if (fabs(matT[i+n*(i+1)]) < tol) 665 q += 1; 666 else 667 break; 668 } 669 for (CeedInt i=0; i<n-1-q; i++) { 670 if (fabs(matT[i+n*(i+1)]) < tol) 671 p += 1; 672 else 673 break; 674 } 675 if (q == n-1) break; // Finished reducing 676 677 // Reduce tridiagonal portion 678 CeedScalar tnn = matT[(n-1-q)+n*(n-1-q)], 679 tnnm1 = matT[(n-2-q)+n*(n-1-q)]; 680 CeedScalar d = (matT[(n-2-q)+n*(n-2-q)] - tnn)/2; 681 CeedScalar mu = tnn - tnnm1*tnnm1 / 682 (d + copysign(sqrt(d*d + tnnm1*tnnm1), d)); 683 CeedScalar x = matT[p+n*p] - mu; 684 CeedScalar z = matT[p+n*(p+1)]; 685 for (CeedInt k=p; k<n-1-q; k++) { 686 // Compute Givens rotation 687 CeedScalar c = 1, s = 0; 688 if (fabs(z) > tol) { 689 if (fabs(z) > fabs(x)) { 690 CeedScalar tau = -x/z; 691 s = 1/sqrt(1+tau*tau), c = s*tau; 692 } else { 693 CeedScalar tau = -z/x; 694 c = 1/sqrt(1+tau*tau), s = c*tau; 695 } 696 } 697 698 // Apply Givens rotation to T 699 CeedGivensRotation(matT, c, s, CEED_NOTRANSPOSE, k, k+1, n, n); 700 CeedGivensRotation(matT, c, s, CEED_TRANSPOSE, k, k+1, n, n); 701 702 // Apply Givens rotation to Q 703 CeedGivensRotation(mat, c, s, CEED_NOTRANSPOSE, k, k+1, n, n); 704 705 // Update x, z 706 if (k < n-q-2) { 707 x = matT[k+n*(k+1)]; 708 z = matT[k+n*(k+2)]; 709 } 710 } 711 itr++; 712 } 713 // Save eigenvalues 714 for (CeedInt i=0; i<n; i++) 715 lambda[i] = matT[i+n*i]; 716 717 // Check convergence 718 if (itr == maxitr && q < n-1) 719 return CeedError(ceed, 1, "Symmetric QR failed to converge"); 720 721 return 0; 722 } 723 724 /** 725 @brief Return C = A B 726 727 @param[in] matA Row-major matrix A 728 @param[in] matB Row-major matrix B 729 @param[out] matC Row-major output matrix C 730 @param m Number of rows of C 731 @param n Number of columns of C 732 @param kk Number of columns of A/rows of B 733 734 @return An error code: 0 - success, otherwise - failure 735 736 @ref Utility 737 **/ 738 static int CeedMatrixMultiply(Ceed ceed, CeedScalar *matA, CeedScalar *matB, 739 CeedScalar *matC, CeedInt m, CeedInt n, 740 CeedInt kk) { 741 for (CeedInt i=0; i<m; i++) 742 for (CeedInt j=0; j<n; j++) { 743 CeedScalar sum = 0; 744 for (CeedInt k=0; k<kk; k++) 745 sum += matA[k+i*kk]*matB[j+k*n]; 746 matC[j+i*n] = sum; 747 } 748 return 0; 749 } 750 751 /** 752 @brief Return Simultaneous Diagonalization of two matrices. This solves the 753 generalized eigenvalue problem A x = lambda B x, where A and B 754 are symmetric and B is positive definite. We generate the matrix X 755 and vector Lambda such that X^T A X = Lambda and X^T B X = I. This 756 is equivalent to the LAPACK routine 'sygv' with TYPE = 1. 757 758 @param[in] matA Row-major matrix to be factorized with eigenvalues 759 @param[in] matB Row-major matrix to be factorized to identity 760 @param[out] x Row-major orthogonal matrix 761 @param[out] lambda Vector of length m of generalized eigenvalues 762 @param n Number of rows/columns 763 764 @return An error code: 0 - success, otherwise - failure 765 766 @ref Utility 767 **/ 768 int CeedSimultaneousDiagonalization(Ceed ceed, CeedScalar *matA, 769 CeedScalar *matB, CeedScalar *x, 770 CeedScalar *lambda, CeedInt n) { 771 int ierr; 772 CeedScalar matC[n*n], matG[n*n], vecD[n]; 773 774 // Compute B = G D G^T 775 memcpy(matG, matB, n*n*sizeof(matB[0])); 776 ierr = CeedSymmetricSchurDecomposition(ceed, matG, vecD, n); CeedChk(ierr); 777 for (CeedInt i=0; i<n; i++) vecD[i] = sqrt(vecD[i]); 778 779 // Compute C = (G D^-1/2)^-1 A (G D^-1/2)^-T 780 // = D^1/2 G^T A D^1/2 G 781 for (CeedInt i=0; i<n; i++) 782 for (CeedInt j=0; j<n; j++) 783 matC[j+i*n] = vecD[i] * matG[i+j*n]; 784 CeedMatrixMultiply(ceed, matC, matA, x, n, n, n); 785 for (CeedInt i=0; i<n; i++) 786 for (CeedInt j=0; j<n; j++) 787 matG[j+i*n] = vecD[i] * matG[j+i*n]; 788 CeedMatrixMultiply(ceed, x, matG, matC, n, n, n); 789 790 // Compute Q^T C Q = lambda 791 ierr = CeedSymmetricSchurDecomposition(ceed, matC, lambda, n); CeedChk(ierr); 792 793 // Set x = (G D^-1/2)^-T Q 794 // = D^1/2 G Q 795 CeedMatrixMultiply(ceed, matG, matC, x, n, n, n); 796 797 return 0; 798 } 799 800 /** 801 @brief Return collocated grad matrix 802 803 @param basis CeedBasis 804 @param[out] colograd1d Row-major Q1d × Q1d matrix expressing derivatives of 805 basis functions at quadrature points 806 807 @return An error code: 0 - success, otherwise - failure 808 809 @ref Advanced 810 **/ 811 int CeedBasisGetCollocatedGrad(CeedBasis basis, CeedScalar *colograd1d) { 812 int i, j, k; 813 Ceed ceed; 814 CeedInt ierr, P1d=(basis)->P1d, Q1d=(basis)->Q1d; 815 CeedScalar *interp1d, *grad1d, tau[Q1d]; 816 817 ierr = CeedMalloc(Q1d*P1d, &interp1d); CeedChk(ierr); 818 ierr = CeedMalloc(Q1d*P1d, &grad1d); CeedChk(ierr); 819 memcpy(interp1d, (basis)->interp1d, Q1d*P1d*sizeof(basis)->interp1d[0]); 820 memcpy(grad1d, (basis)->grad1d, Q1d*P1d*sizeof(basis)->interp1d[0]); 821 822 // QR Factorization, interp1d = Q R 823 ierr = CeedBasisGetCeed(basis, &ceed); CeedChk(ierr); 824 ierr = CeedQRFactorization(ceed, interp1d, tau, Q1d, P1d); CeedChk(ierr); 825 826 // Apply Rinv, colograd1d = grad1d Rinv 827 for (i=0; i<Q1d; i++) { // Row i 828 colograd1d[Q1d*i] = grad1d[P1d*i]/interp1d[0]; 829 for (j=1; j<P1d; j++) { // Column j 830 colograd1d[j+Q1d*i] = grad1d[j+P1d*i]; 831 for (k=0; k<j; k++) { 832 colograd1d[j+Q1d*i] -= interp1d[j+P1d*k]*colograd1d[k+Q1d*i]; 833 } 834 colograd1d[j+Q1d*i] /= interp1d[j+P1d*j]; 835 } 836 for (j=P1d; j<Q1d; j++) { 837 colograd1d[j+Q1d*i] = 0; 838 } 839 } 840 841 // Apply Qtranspose, colograd = colograd Qtranspose 842 CeedHouseholderApplyQ(colograd1d, interp1d, tau, CEED_NOTRANSPOSE, 843 Q1d, Q1d, P1d, 1, Q1d); 844 845 ierr = CeedFree(&interp1d); CeedChk(ierr); 846 ierr = CeedFree(&grad1d); CeedChk(ierr); 847 848 return 0; 849 } 850 851 /** 852 @brief Apply basis evaluation from nodes to quadrature points or vice-versa 853 854 @param basis CeedBasis to evaluate 855 @param nelem The number of elements to apply the basis evaluation to; 856 the backend will specify the ordering in 857 ElemRestrictionCreateBlocked 858 @param tmode \ref CEED_NOTRANSPOSE to evaluate from nodes to quadrature 859 points, \ref CEED_TRANSPOSE to apply the transpose, mapping 860 from quadrature points to nodes 861 @param emode \ref CEED_EVAL_INTERP to obtain interpolated values, 862 \ref CEED_EVAL_GRAD to obtain gradients. 863 @param[in] u Input array 864 @param[out] v Output array 865 866 @return An error code: 0 - success, otherwise - failure 867 868 @ref Advanced 869 **/ 870 int CeedBasisApply(CeedBasis basis, CeedInt nelem, CeedTransposeMode tmode, 871 CeedEvalMode emode, CeedVector u, CeedVector v) { 872 int ierr; 873 CeedInt ulength = 0, vlength, nnodes, nqpt; 874 if (!basis->Apply) return CeedError(basis->ceed, 1, 875 "Backend does not support BasisApply"); 876 // check compatibility of topological and geometrical dimensions 877 ierr = CeedBasisGetNumNodes(basis, &nnodes); CeedChk(ierr); 878 ierr = CeedBasisGetNumQuadraturePoints(basis, &nqpt); CeedChk(ierr); 879 ierr = CeedVectorGetLength(v, &vlength); CeedChk(ierr); 880 881 if (u) { 882 ierr = CeedVectorGetLength(u, &ulength); CeedChk(ierr); 883 } 884 885 if ((tmode == CEED_TRANSPOSE && (vlength % nnodes != 0 886 || ulength % nqpt != 0)) 887 || 888 (tmode == CEED_NOTRANSPOSE && (ulength % nnodes != 0 || vlength % nqpt != 0))) 889 return CeedError(basis->ceed, 1, 890 "Length of input/output vectors incompatible with basis dimensions"); 891 892 ierr = basis->Apply(basis, nelem, tmode, emode, u, v); CeedChk(ierr); 893 return 0; 894 } 895 896 /** 897 @brief Get Ceed associated with a CeedBasis 898 899 @param basis CeedBasis 900 @param[out] ceed Variable to store Ceed 901 902 @return An error code: 0 - success, otherwise - failure 903 904 @ref Advanced 905 **/ 906 int CeedBasisGetCeed(CeedBasis basis, Ceed *ceed) { 907 *ceed = basis->ceed; 908 909 return 0; 910 }; 911 912 /** 913 @brief Get dimension for given CeedBasis 914 915 @param basis CeedBasis 916 @param[out] dim Variable to store dimension of basis 917 918 @return An error code: 0 - success, otherwise - failure 919 920 @ref Advanced 921 **/ 922 int CeedBasisGetDimension(CeedBasis basis, CeedInt *dim) { 923 *dim = basis->dim; 924 925 return 0; 926 }; 927 928 /** 929 @brief Get tensor status for given CeedBasis 930 931 @param basis CeedBasis 932 @param[out] tensor Variable to store tensor status 933 934 @return An error code: 0 - success, otherwise - failure 935 936 @ref Advanced 937 **/ 938 int CeedBasisGetTensorStatus(CeedBasis basis, bool *tensor) { 939 *tensor = basis->tensorbasis; 940 941 return 0; 942 }; 943 944 /** 945 @brief Get number of components for given CeedBasis 946 947 @param basis CeedBasis 948 @param[out] numcomp Variable to store number of components of basis 949 950 @return An error code: 0 - success, otherwise - failure 951 952 @ref Advanced 953 **/ 954 int CeedBasisGetNumComponents(CeedBasis basis, CeedInt *numcomp) { 955 *numcomp = basis->ncomp; 956 957 return 0; 958 }; 959 960 /** 961 @brief Get total number of nodes (in 1 dimension) of a CeedBasis 962 963 @param basis CeedBasis 964 @param[out] P1d Variable to store number of nodes 965 966 @return An error code: 0 - success, otherwise - failure 967 968 @ref Advanced 969 **/ 970 int CeedBasisGetNumNodes1D(CeedBasis basis, CeedInt *P1d) { 971 if (!basis->tensorbasis) return CeedError(basis->ceed, 1, 972 "Cannot supply P1d for non-tensor basis"); 973 *P1d = basis->P1d; 974 return 0; 975 } 976 977 /** 978 @brief Get total number of quadrature points (in 1 dimension) of a CeedBasis 979 980 @param basis CeedBasis 981 @param[out] Q1d Variable to store number of quadrature points 982 983 @return An error code: 0 - success, otherwise - failure 984 985 @ref Advanced 986 **/ 987 int CeedBasisGetNumQuadraturePoints1D(CeedBasis basis, CeedInt *Q1d) { 988 if (!basis->tensorbasis) return CeedError(basis->ceed, 1, 989 "Cannot supply Q1d for non-tensor basis"); 990 *Q1d = basis->Q1d; 991 return 0; 992 } 993 994 /** 995 @brief Get total number of nodes (in dim dimensions) of a CeedBasis 996 997 @param basis CeedBasis 998 @param[out] P Variable to store number of nodes 999 1000 @return An error code: 0 - success, otherwise - failure 1001 1002 @ref Utility 1003 **/ 1004 int CeedBasisGetNumNodes(CeedBasis basis, CeedInt *P) { 1005 *P = basis->P; 1006 return 0; 1007 } 1008 1009 /** 1010 @brief Get total number of quadrature points (in dim dimensions) of a CeedBasis 1011 1012 @param basis CeedBasis 1013 @param[out] Q Variable to store number of quadrature points 1014 1015 @return An error code: 0 - success, otherwise - failure 1016 1017 @ref Utility 1018 **/ 1019 int CeedBasisGetNumQuadraturePoints(CeedBasis basis, CeedInt *Q) { 1020 *Q = basis->Q; 1021 return 0; 1022 } 1023 1024 /** 1025 @brief Get reference coordinates of quadrature points (in dim dimensions) 1026 of a CeedBasis 1027 1028 @param basis CeedBasis 1029 @param[out] qref Variable to store reference coordinates of quadrature points 1030 1031 @return An error code: 0 - success, otherwise - failure 1032 1033 @ref Advanced 1034 **/ 1035 int CeedBasisGetQRef(CeedBasis basis, CeedScalar* *qref) { 1036 *qref = basis->qref1d; 1037 return 0; 1038 } 1039 1040 /** 1041 @brief Get quadrature weights of quadrature points (in dim dimensions) 1042 of a CeedBasis 1043 1044 @param basis CeedBasis 1045 @param[out] qweight Variable to store quadrature weights 1046 1047 @return An error code: 0 - success, otherwise - failure 1048 1049 @ref Advanced 1050 **/ 1051 int CeedBasisGetQWeights(CeedBasis basis, CeedScalar* *qweight) { 1052 *qweight = basis->qweight1d; 1053 return 0; 1054 } 1055 1056 /** 1057 @brief Get interpolation matrix of a CeedBasis 1058 1059 @param basis CeedBasis 1060 @param[out] interp Variable to store interpolation matrix 1061 1062 @return An error code: 0 - success, otherwise - failure 1063 1064 @ref Advanced 1065 **/ 1066 int CeedBasisGetInterp(CeedBasis basis, CeedScalar* *interp) { 1067 *interp = basis->interp1d; 1068 return 0; 1069 } 1070 1071 /** 1072 @brief Get gradient matrix of a CeedBasis 1073 1074 @param basis CeedBasis 1075 @param[out] grad Variable to store gradient matrix 1076 1077 @return An error code: 0 - success, otherwise - failure 1078 1079 @ref Advanced 1080 **/ 1081 int CeedBasisGetGrad(CeedBasis basis, CeedScalar* *grad) { 1082 *grad = basis->grad1d; 1083 return 0; 1084 } 1085 1086 /** 1087 @brief Get backend data of a CeedBasis 1088 1089 @param basis CeedBasis 1090 @param[out] data Variable to store data 1091 1092 @return An error code: 0 - success, otherwise - failure 1093 1094 @ref Advanced 1095 **/ 1096 int CeedBasisGetData(CeedBasis basis, void* *data) { 1097 *data = basis->data; 1098 return 0; 1099 } 1100 1101 /** 1102 @brief Set backend data of a CeedBasis 1103 1104 @param[out] basis CeedBasis 1105 @param data Data to set 1106 1107 @return An error code: 0 - success, otherwise - failure 1108 1109 @ref Advanced 1110 **/ 1111 int CeedBasisSetData(CeedBasis basis, void* *data) { 1112 basis->data = *data; 1113 return 0; 1114 } 1115 1116 /** 1117 @brief Get CeedTensorContract of a CeedBasis 1118 1119 @param basis CeedBasis 1120 @param[out] contract Variable to store CeedTensorContract 1121 1122 @return An error code: 0 - success, otherwise - failure 1123 1124 @ref Advanced 1125 **/ 1126 int CeedBasisGetTensorContract(CeedBasis basis, 1127 CeedTensorContract *contract) { 1128 *contract = basis->contract; 1129 return 0; 1130 } 1131 1132 /** 1133 @brief Set CeedTensorContract of a CeedBasis 1134 1135 @param[out] basis CeedBasis 1136 @param contract CeedTensorContract to set 1137 1138 @return An error code: 0 - success, otherwise - failure 1139 1140 @ref Advanced 1141 **/ 1142 int CeedBasisSetTensorContract(CeedBasis basis, 1143 CeedTensorContract *contract) { 1144 basis->contract = *contract; 1145 return 0; 1146 } 1147 1148 /** 1149 @brief Get dimension for given CeedElemTopology 1150 1151 @param topo CeedElemTopology 1152 @param[out] dim Variable to store dimension of topology 1153 1154 @return An error code: 0 - success, otherwise - failure 1155 1156 @ref Advanced 1157 **/ 1158 int CeedBasisGetTopologyDimension(CeedElemTopology topo, CeedInt *dim) { 1159 *dim = (CeedInt) topo >> 16; 1160 1161 return 0; 1162 }; 1163 1164 /** 1165 @brief Destroy a CeedBasis 1166 1167 @param basis CeedBasis to destroy 1168 1169 @return An error code: 0 - success, otherwise - failure 1170 1171 @ref Basic 1172 **/ 1173 int CeedBasisDestroy(CeedBasis *basis) { 1174 int ierr; 1175 1176 if (!*basis || --(*basis)->refcount > 0) return 0; 1177 if ((*basis)->Destroy) { 1178 ierr = (*basis)->Destroy(*basis); CeedChk(ierr); 1179 } 1180 ierr = CeedFree(&(*basis)->interp1d); CeedChk(ierr); 1181 ierr = CeedFree(&(*basis)->grad1d); CeedChk(ierr); 1182 ierr = CeedFree(&(*basis)->qref1d); CeedChk(ierr); 1183 ierr = CeedFree(&(*basis)->qweight1d); CeedChk(ierr); 1184 ierr = CeedDestroy(&(*basis)->ceed); CeedChk(ierr); 1185 ierr = CeedFree(basis); CeedChk(ierr); 1186 return 0; 1187 } 1188 1189 /// @cond DOXYGEN_SKIP 1190 // Indicate that the quadrature points are collocated with the nodes 1191 CeedBasis CEED_BASIS_COLLOCATED = &ceed_basis_collocated; 1192 /// @endcond 1193 /// @} 1194