xref: /libCEED/interface/ceed-basis.c (revision 17be3a414c6fae47654f1361bae9c9dbcdd66795)
1 // Copyright (c) 2017-2022, 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 #include <ceed/ceed.h>
9 #include <ceed/backend.h>
10 #include <ceed-impl.h>
11 #include <math.h>
12 #include <stdbool.h>
13 #include <stdio.h>
14 #include <string.h>
15 
16 /// @file
17 /// Implementation of CeedBasis interfaces
18 
19 /// @cond DOXYGEN_SKIP
20 static struct CeedBasis_private ceed_basis_collocated;
21 /// @endcond
22 
23 /// @addtogroup CeedBasisUser
24 /// @{
25 
26 /// Indicate that the quadrature points are collocated with the nodes
27 const CeedBasis CEED_BASIS_COLLOCATED = &ceed_basis_collocated;
28 
29 /// @}
30 
31 /// ----------------------------------------------------------------------------
32 /// CeedBasis Library Internal Functions
33 /// ----------------------------------------------------------------------------
34 /// @addtogroup CeedBasisDeveloper
35 /// @{
36 
37 /**
38   @brief Compute Householder reflection
39 
40     Computes A = (I - b v v^T) A
41     where A is an mxn matrix indexed as A[i*row + j*col]
42 
43   @param[in,out] A  Matrix to apply Householder reflection to, in place
44   @param v          Householder vector
45   @param b          Scaling factor
46   @param m          Number of rows in A
47   @param n          Number of columns in A
48   @param row        Row stride
49   @param col        Col stride
50 
51   @return An error code: 0 - success, otherwise - failure
52 
53   @ref Developer
54 **/
55 static int CeedHouseholderReflect(CeedScalar *A, const CeedScalar *v,
56                                   CeedScalar b, CeedInt m, CeedInt n,
57                                   CeedInt row, CeedInt col) {
58   for (CeedInt j=0; j<n; j++) {
59     CeedScalar w = A[0*row + j*col];
60     for (CeedInt i=1; i<m; i++)
61       w += v[i] * A[i*row + j*col];
62     A[0*row + j*col] -= b * w;
63     for (CeedInt i=1; i<m; i++)
64       A[i*row + j*col] -= b * w * v[i];
65   }
66   return CEED_ERROR_SUCCESS;
67 }
68 
69 /**
70   @brief Apply Householder Q matrix
71 
72     Compute A = Q A where Q is mxm and A is mxn.
73 
74   @param[in,out] A  Matrix to apply Householder Q to, in place
75   @param Q          Householder Q matrix
76   @param tau        Householder scaling factors
77   @param t_mode     Transpose mode for application
78   @param m          Number of rows in A
79   @param n          Number of columns in A
80   @param k          Number of elementary reflectors in Q, k<m
81   @param row        Row stride in A
82   @param col        Col stride in A
83 
84   @return An error code: 0 - success, otherwise - failure
85 
86   @ref Developer
87 **/
88 int CeedHouseholderApplyQ(CeedScalar *A, const CeedScalar *Q,
89                           const CeedScalar *tau, CeedTransposeMode t_mode,
90                           CeedInt m, CeedInt n, CeedInt k,
91                           CeedInt row, CeedInt col) {
92   int ierr;
93   CeedScalar *v;
94   ierr = CeedMalloc(m, &v); CeedChk(ierr);
95   for (CeedInt ii=0; ii<k; ii++) {
96     CeedInt i = t_mode == CEED_TRANSPOSE ? ii : k-1-ii;
97     for (CeedInt j=i+1; j<m; j++)
98       v[j] = Q[j*k+i];
99     // Apply Householder reflector (I - tau v v^T) collo_grad_1d^T
100     ierr = CeedHouseholderReflect(&A[i*row], &v[i], tau[i], m-i, n, row, col);
101     CeedChk(ierr);
102   }
103   ierr = CeedFree(&v); CeedChk(ierr);
104   return CEED_ERROR_SUCCESS;
105 }
106 
107 /**
108   @brief Compute Givens rotation
109 
110     Computes A = G A (or G^T A in transpose mode)
111     where A is an mxn matrix indexed as A[i*n + j*m]
112 
113   @param[in,out] A  Row major matrix to apply Givens rotation to, in place
114   @param c          Cosine factor
115   @param s          Sine factor
116   @param t_mode     @ref CEED_NOTRANSPOSE to rotate the basis counter-clockwise,
117                     which has the effect of rotating columns of A clockwise;
118                     @ref CEED_TRANSPOSE for the opposite rotation
119   @param i          First row/column to apply rotation
120   @param k          Second row/column to apply rotation
121   @param m          Number of rows in A
122   @param n          Number of columns in A
123 
124   @return An error code: 0 - success, otherwise - failure
125 
126   @ref Developer
127 **/
128 static int CeedGivensRotation(CeedScalar *A, CeedScalar c, CeedScalar s,
129                               CeedTransposeMode t_mode, CeedInt i, CeedInt k,
130                               CeedInt m, CeedInt n) {
131   CeedInt stride_j = 1, stride_ik = m, num_its = n;
132   if (t_mode == CEED_NOTRANSPOSE) {
133     stride_j = n; stride_ik = 1; num_its = m;
134   }
135 
136   // Apply rotation
137   for (CeedInt j=0; j<num_its; j++) {
138     CeedScalar tau1 = A[i*stride_ik+j*stride_j], tau2 = A[k*stride_ik+j*stride_j];
139     A[i*stride_ik+j*stride_j] = c*tau1 - s*tau2;
140     A[k*stride_ik+j*stride_j] = s*tau1 + c*tau2;
141   }
142   return CEED_ERROR_SUCCESS;
143 }
144 
145 /**
146   @brief View an array stored in a CeedBasis
147 
148   @param[in] name      Name of array
149   @param[in] fp_fmt    Printing format
150   @param[in] m         Number of rows in array
151   @param[in] n         Number of columns in array
152   @param[in] a         Array to be viewed
153   @param[in] stream    Stream to view to, e.g., stdout
154 
155   @return An error code: 0 - success, otherwise - failure
156 
157   @ref Developer
158 **/
159 static int CeedScalarView(const char *name, const char *fp_fmt, CeedInt m,
160                           CeedInt n, const CeedScalar *a, FILE *stream) {
161   for (CeedInt i=0; i<m; i++) {
162     if (m > 1)
163       fprintf(stream, "%12s[%d]:", name, i);
164     else
165       fprintf(stream, "%12s:", name);
166     for (CeedInt j=0; j<n; j++)
167       fprintf(stream, fp_fmt, fabs(a[i*n+j]) > 1E-14 ? a[i*n+j] : 0);
168     fputs("\n", stream);
169   }
170   return CEED_ERROR_SUCCESS;
171 }
172 
173 /// @}
174 
175 /// ----------------------------------------------------------------------------
176 /// Ceed Backend API
177 /// ----------------------------------------------------------------------------
178 /// @addtogroup CeedBasisBackend
179 /// @{
180 
181 /**
182   @brief Return collocated grad matrix
183 
184   @param basis               CeedBasis
185   @param[out] collo_grad_1d  Row-major (Q_1d * Q_1d) matrix expressing derivatives of
186                                basis functions at quadrature points
187 
188   @return An error code: 0 - success, otherwise - failure
189 
190   @ref Backend
191 **/
192 int CeedBasisGetCollocatedGrad(CeedBasis basis, CeedScalar *collo_grad_1d) {
193   int i, j, k;
194   Ceed ceed;
195   CeedInt ierr, P_1d=(basis)->P_1d, Q_1d=(basis)->Q_1d;
196   CeedScalar *interp_1d, *grad_1d, *tau;
197 
198   ierr = CeedMalloc(Q_1d*P_1d, &interp_1d); CeedChk(ierr);
199   ierr = CeedMalloc(Q_1d*P_1d, &grad_1d); CeedChk(ierr);
200   ierr = CeedMalloc(Q_1d, &tau); CeedChk(ierr);
201   memcpy(interp_1d, (basis)->interp_1d, Q_1d*P_1d*sizeof(basis)->interp_1d[0]);
202   memcpy(grad_1d, (basis)->grad_1d, Q_1d*P_1d*sizeof(basis)->interp_1d[0]);
203 
204   // QR Factorization, interp_1d = Q R
205   ierr = CeedBasisGetCeed(basis, &ceed); CeedChk(ierr);
206   ierr = CeedQRFactorization(ceed, interp_1d, tau, Q_1d, P_1d); CeedChk(ierr);
207   // Note: This function is for backend use, so all errors are terminal
208   //   and we do not need to clean up memory on failure.
209 
210   // Apply Rinv, collo_grad_1d = grad_1d Rinv
211   for (i=0; i<Q_1d; i++) { // Row i
212     collo_grad_1d[Q_1d*i] = grad_1d[P_1d*i]/interp_1d[0];
213     for (j=1; j<P_1d; j++) { // Column j
214       collo_grad_1d[j+Q_1d*i] = grad_1d[j+P_1d*i];
215       for (k=0; k<j; k++)
216         collo_grad_1d[j+Q_1d*i] -= interp_1d[j+P_1d*k]*collo_grad_1d[k+Q_1d*i];
217       collo_grad_1d[j+Q_1d*i] /= interp_1d[j+P_1d*j];
218     }
219     for (j=P_1d; j<Q_1d; j++)
220       collo_grad_1d[j+Q_1d*i] = 0;
221   }
222 
223   // Apply Qtranspose, collo_grad = collo_grad Q_transpose
224   ierr = CeedHouseholderApplyQ(collo_grad_1d, interp_1d, tau, CEED_NOTRANSPOSE,
225                                Q_1d, Q_1d, P_1d, 1, Q_1d); CeedChk(ierr);
226 
227   ierr = CeedFree(&interp_1d); CeedChk(ierr);
228   ierr = CeedFree(&grad_1d); CeedChk(ierr);
229   ierr = CeedFree(&tau); CeedChk(ierr);
230   return CEED_ERROR_SUCCESS;
231 }
232 
233 /**
234   @brief Get tensor status for given CeedBasis
235 
236   @param basis           CeedBasis
237   @param[out] is_tensor  Variable to store tensor status
238 
239   @return An error code: 0 - success, otherwise - failure
240 
241   @ref Backend
242 **/
243 int CeedBasisIsTensor(CeedBasis basis, bool *is_tensor) {
244   *is_tensor = basis->tensor_basis;
245   return CEED_ERROR_SUCCESS;
246 }
247 
248 /**
249   @brief Get backend data of a CeedBasis
250 
251   @param basis      CeedBasis
252   @param[out] data  Variable to store data
253 
254   @return An error code: 0 - success, otherwise - failure
255 
256   @ref Backend
257 **/
258 int CeedBasisGetData(CeedBasis basis, void *data) {
259   *(void **)data = basis->data;
260   return CEED_ERROR_SUCCESS;
261 }
262 
263 /**
264   @brief Set backend data of a CeedBasis
265 
266   @param[out] basis  CeedBasis
267   @param data        Data to set
268 
269   @return An error code: 0 - success, otherwise - failure
270 
271   @ref Backend
272 **/
273 int CeedBasisSetData(CeedBasis basis, void *data) {
274   basis->data = data;
275   return CEED_ERROR_SUCCESS;
276 }
277 
278 /**
279   @brief Increment the reference counter for a CeedBasis
280 
281   @param basis  Basis to increment the reference counter
282 
283   @return An error code: 0 - success, otherwise - failure
284 
285   @ref Backend
286 **/
287 int CeedBasisReference(CeedBasis basis) {
288   basis->ref_count++;
289   return CEED_ERROR_SUCCESS;
290 }
291 
292 /**
293   @brief Estimate number of FLOPs required to apply CeedBasis in t_mode and eval_mode
294 
295   @param basis     Basis to estimate FLOPs for
296   @param t_mode    Apply basis or transpose
297   @param eval_mode Basis evaluation mode
298   @param flops     Address of variable to hold FLOPs estimate
299 
300   @ref Backend
301 **/
302 int CeedBasisGetFlopsEstimate(CeedBasis basis, CeedTransposeMode t_mode,
303                               CeedEvalMode eval_mode, CeedSize *flops) {
304   int ierr;
305   bool is_tensor;
306 
307   ierr = CeedBasisIsTensor(basis, &is_tensor); CeedChk(ierr);
308   if (is_tensor) {
309     CeedInt dim, num_comp, P_1d, Q_1d;
310     ierr = CeedBasisGetDimension(basis, &dim); CeedChk(ierr);
311     ierr = CeedBasisGetNumComponents(basis, &num_comp); CeedChk(ierr);
312     ierr = CeedBasisGetNumNodes1D(basis, &P_1d);  CeedChk(ierr);
313     ierr = CeedBasisGetNumQuadraturePoints1D(basis, &Q_1d);  CeedChk(ierr);
314     if (t_mode == CEED_TRANSPOSE) {
315       P_1d = Q_1d; Q_1d = P_1d;
316     }
317     CeedInt tensor_flops = 0, pre = num_comp * CeedIntPow(P_1d, dim-1), post = 1;
318     for (CeedInt d = 0; d < dim; d++) {
319       tensor_flops += 2 * pre * P_1d * post * Q_1d;
320       pre /= P_1d;
321       post *= Q_1d;
322     }
323     switch (eval_mode) {
324     case CEED_EVAL_NONE:   *flops = 0; break;
325     case CEED_EVAL_INTERP: *flops = tensor_flops; break;
326     case CEED_EVAL_GRAD:   *flops = tensor_flops * 2; break;
327     case CEED_EVAL_DIV:
328       // LCOV_EXCL_START
329       return CeedError(basis->ceed, CEED_ERROR_INCOMPATIBLE,
330                        "Tensor CEED_EVAL_DIV not supported"); break;
331     case CEED_EVAL_CURL:
332       return CeedError(basis->ceed, CEED_ERROR_INCOMPATIBLE,
333                        "Tensor CEED_EVAL_CURL not supported"); break;
334     // LCOV_EXCL_STOP
335     case CEED_EVAL_WEIGHT: *flops = dim * CeedIntPow(Q_1d, dim); break;
336     }
337   } else {
338     CeedInt dim, num_comp, num_nodes, num_qpts, Q_comp;
339     ierr = CeedBasisGetDimension(basis, &dim); CeedChk(ierr);
340     ierr = CeedBasisGetNumComponents(basis, &num_comp); CeedChk(ierr);
341     ierr = CeedBasisGetNumNodes(basis, &num_nodes); CeedChk(ierr);
342     ierr = CeedBasisGetNumQuadraturePoints(basis, &num_qpts); CeedChk(ierr);
343     ierr = CeedBasisGetNumQuadratureComponents(basis, &Q_comp); CeedChk(ierr);
344     switch (eval_mode) {
345     case CEED_EVAL_NONE:   *flops = 0; break;
346     case CEED_EVAL_INTERP: *flops = num_nodes * num_qpts * num_comp; break;
347     case CEED_EVAL_GRAD:   *flops = num_nodes * num_qpts * num_comp * dim; break;
348     case CEED_EVAL_DIV:    *flops = num_nodes * num_qpts; break;
349     case CEED_EVAL_CURL:   *flops = num_nodes * num_qpts * dim; break;
350     case CEED_EVAL_WEIGHT: *flops = 0; break;
351     }
352   }
353 
354   return CEED_ERROR_SUCCESS;
355 }
356 
357 /**
358   @brief Get dimension for given CeedElemTopology
359 
360   @param topo      CeedElemTopology
361   @param[out] dim  Variable to store dimension of topology
362 
363   @return An error code: 0 - success, otherwise - failure
364 
365   @ref Backend
366 **/
367 int CeedBasisGetTopologyDimension(CeedElemTopology topo, CeedInt *dim) {
368   *dim = (CeedInt) topo >> 16;
369   return CEED_ERROR_SUCCESS;
370 }
371 
372 /**
373   @brief Get CeedTensorContract of a CeedBasis
374 
375   @param basis          CeedBasis
376   @param[out] contract  Variable to store CeedTensorContract
377 
378   @return An error code: 0 - success, otherwise - failure
379 
380   @ref Backend
381 **/
382 int CeedBasisGetTensorContract(CeedBasis basis, CeedTensorContract *contract) {
383   *contract = basis->contract;
384   return CEED_ERROR_SUCCESS;
385 }
386 
387 /**
388   @brief Set CeedTensorContract of a CeedBasis
389 
390   @param[out] basis  CeedBasis
391   @param contract    CeedTensorContract to set
392 
393   @return An error code: 0 - success, otherwise - failure
394 
395   @ref Backend
396 **/
397 int CeedBasisSetTensorContract(CeedBasis basis, CeedTensorContract contract) {
398   int ierr;
399   basis->contract = contract;
400   ierr = CeedTensorContractReference(contract); CeedChk(ierr);
401   return CEED_ERROR_SUCCESS;
402 }
403 
404 /**
405   @brief Return a reference implementation of matrix multiplication C = A B.
406            Note, this is a reference implementation for CPU CeedScalar pointers
407            that is not intended for high performance.
408 
409   @param ceed        A Ceed context for error handling
410   @param[in] mat_A   Row-major matrix A
411   @param[in] mat_B   Row-major matrix B
412   @param[out] mat_C  Row-major output matrix C
413   @param m           Number of rows of C
414   @param n           Number of columns of C
415   @param kk          Number of columns of A/rows of B
416 
417   @return An error code: 0 - success, otherwise - failure
418 
419   @ref Utility
420 **/
421 int CeedMatrixMatrixMultiply(Ceed ceed, const CeedScalar *mat_A,
422                              const CeedScalar *mat_B, CeedScalar *mat_C,
423                              CeedInt m, CeedInt n, CeedInt kk) {
424   for (CeedInt i=0; i<m; i++)
425     for (CeedInt j=0; j<n; j++) {
426       CeedScalar sum = 0;
427       for (CeedInt k=0; k<kk; k++)
428         sum += mat_A[k+i*kk]*mat_B[j+k*n];
429       mat_C[j+i*n] = sum;
430     }
431   return CEED_ERROR_SUCCESS;
432 }
433 
434 /// @}
435 
436 /// ----------------------------------------------------------------------------
437 /// CeedBasis Public API
438 /// ----------------------------------------------------------------------------
439 /// @addtogroup CeedBasisUser
440 /// @{
441 
442 /**
443   @brief Create a tensor-product basis for H^1 discretizations
444 
445   @param ceed        A Ceed object where the CeedBasis will be created
446   @param dim         Topological dimension
447   @param num_comp    Number of field components (1 for scalar fields)
448   @param P_1d        Number of nodes in one dimension
449   @param Q_1d        Number of quadrature points in one dimension
450   @param interp_1d   Row-major (Q_1d * P_1d) matrix expressing the values of nodal
451                        basis functions at quadrature points
452   @param grad_1d     Row-major (Q_1d * P_1d) matrix expressing derivatives of nodal
453                        basis functions at quadrature points
454   @param q_ref_1d    Array of length Q_1d holding the locations of quadrature points
455                        on the 1D reference element [-1, 1]
456   @param q_weight_1d Array of length Q_1d holding the quadrature weights on the
457                        reference element
458   @param[out] basis  Address of the variable where the newly created
459                        CeedBasis will be stored.
460 
461   @return An error code: 0 - success, otherwise - failure
462 
463   @ref User
464 **/
465 int CeedBasisCreateTensorH1(Ceed ceed, CeedInt dim, CeedInt num_comp,
466                             CeedInt P_1d, CeedInt Q_1d,
467                             const CeedScalar *interp_1d,
468                             const CeedScalar *grad_1d, const CeedScalar *q_ref_1d,
469                             const CeedScalar *q_weight_1d, CeedBasis *basis) {
470   int ierr;
471 
472   if (!ceed->BasisCreateTensorH1) {
473     Ceed delegate;
474     ierr = CeedGetObjectDelegate(ceed, &delegate, "Basis"); CeedChk(ierr);
475 
476     if (!delegate)
477       // LCOV_EXCL_START
478       return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
479                        "Backend does not support BasisCreateTensorH1");
480     // LCOV_EXCL_STOP
481 
482     ierr = CeedBasisCreateTensorH1(delegate, dim, num_comp, P_1d,
483                                    Q_1d, interp_1d, grad_1d, q_ref_1d,
484                                    q_weight_1d, basis); CeedChk(ierr);
485     return CEED_ERROR_SUCCESS;
486   }
487 
488   if (dim < 1)
489     // LCOV_EXCL_START
490     return CeedError(ceed, CEED_ERROR_DIMENSION,
491                      "Basis dimension must be a positive value");
492   // LCOV_EXCL_STOP
493 
494   if (num_comp < 1)
495     // LCOV_EXCL_START
496     return CeedError(ceed, CEED_ERROR_DIMENSION,
497                      "Basis must have at least 1 component");
498   // LCOV_EXCL_STOP
499 
500   if (P_1d < 1)
501     // LCOV_EXCL_START
502     return CeedError(ceed, CEED_ERROR_DIMENSION,
503                      "Basis must have at least 1 node");
504   // LCOV_EXCL_STOP
505 
506   if (Q_1d < 1)
507     // LCOV_EXCL_START
508     return CeedError(ceed, CEED_ERROR_DIMENSION,
509                      "Basis must have at least 1 quadrature point");
510   // LCOV_EXCL_STOP
511 
512   CeedElemTopology topo = dim == 1 ? CEED_TOPOLOGY_LINE
513                           : dim == 2 ? CEED_TOPOLOGY_QUAD
514                           : CEED_TOPOLOGY_HEX;
515 
516   ierr = CeedCalloc(1, basis); CeedChk(ierr);
517   (*basis)->ceed = ceed;
518   ierr = CeedReference(ceed); CeedChk(ierr);
519   (*basis)->ref_count = 1;
520   (*basis)->tensor_basis = 1;
521   (*basis)->dim = dim;
522   (*basis)->topo = topo;
523   (*basis)->num_comp = num_comp;
524   (*basis)->P_1d = P_1d;
525   (*basis)->Q_1d = Q_1d;
526   (*basis)->P = CeedIntPow(P_1d, dim);
527   (*basis)->Q = CeedIntPow(Q_1d, dim);
528   (*basis)->Q_comp = 1;
529   (*basis)->basis_space = 1; // 1 for H^1 space
530   ierr = CeedCalloc(Q_1d, &(*basis)->q_ref_1d); CeedChk(ierr);
531   ierr = CeedCalloc(Q_1d, &(*basis)->q_weight_1d); CeedChk(ierr);
532   if (q_ref_1d) memcpy((*basis)->q_ref_1d, q_ref_1d, Q_1d*sizeof(q_ref_1d[0]));
533   if (q_weight_1d) memcpy((*basis)->q_weight_1d, q_weight_1d,
534                             Q_1d*sizeof(q_weight_1d[0]));
535   ierr = CeedCalloc(Q_1d*P_1d, &(*basis)->interp_1d); CeedChk(ierr);
536   ierr = CeedCalloc(Q_1d*P_1d, &(*basis)->grad_1d); CeedChk(ierr);
537   if (interp_1d) memcpy((*basis)->interp_1d, interp_1d,
538                           Q_1d*P_1d*sizeof(interp_1d[0]));
539   if (grad_1d) memcpy((*basis)->grad_1d, grad_1d, Q_1d*P_1d*sizeof(grad_1d[0]));
540   ierr = ceed->BasisCreateTensorH1(dim, P_1d, Q_1d, interp_1d, grad_1d, q_ref_1d,
541                                    q_weight_1d, *basis); CeedChk(ierr);
542   return CEED_ERROR_SUCCESS;
543 }
544 
545 /**
546   @brief Create a tensor-product Lagrange basis
547 
548   @param ceed        A Ceed object where the CeedBasis will be created
549   @param dim         Topological dimension of element
550   @param num_comp      Number of field components (1 for scalar fields)
551   @param P           Number of Gauss-Lobatto nodes in one dimension.  The
552                        polynomial degree of the resulting Q_k element is k=P-1.
553   @param Q           Number of quadrature points in one dimension.
554   @param quad_mode   Distribution of the Q quadrature points (affects order of
555                        accuracy for the quadrature)
556   @param[out] basis  Address of the variable where the newly created
557                        CeedBasis will be stored.
558 
559   @return An error code: 0 - success, otherwise - failure
560 
561   @ref User
562 **/
563 int CeedBasisCreateTensorH1Lagrange(Ceed ceed, CeedInt dim, CeedInt num_comp,
564                                     CeedInt P, CeedInt Q, CeedQuadMode quad_mode,
565                                     CeedBasis *basis) {
566   // Allocate
567   int ierr, ierr2, i, j, k;
568   CeedScalar c1, c2, c3, c4, dx, *nodes, *interp_1d, *grad_1d, *q_ref_1d,
569              *q_weight_1d;
570 
571   if (dim < 1)
572     // LCOV_EXCL_START
573     return CeedError(ceed, CEED_ERROR_DIMENSION,
574                      "Basis dimension must be a positive value");
575   // LCOV_EXCL_STOP
576 
577   if (num_comp < 1)
578     // LCOV_EXCL_START
579     return CeedError(ceed, CEED_ERROR_DIMENSION,
580                      "Basis must have at least 1 component");
581   // LCOV_EXCL_STOP
582 
583   if (P < 1)
584     // LCOV_EXCL_START
585     return CeedError(ceed, CEED_ERROR_DIMENSION,
586                      "Basis must have at least 1 node");
587   // LCOV_EXCL_STOP
588 
589   if (Q < 1)
590     // LCOV_EXCL_START
591     return CeedError(ceed, CEED_ERROR_DIMENSION,
592                      "Basis must have at least 1 quadrature point");
593   // LCOV_EXCL_STOP
594 
595   // Get Nodes and Weights
596   ierr = CeedCalloc(P*Q, &interp_1d); CeedChk(ierr);
597   ierr = CeedCalloc(P*Q, &grad_1d); CeedChk(ierr);
598   ierr = CeedCalloc(P, &nodes); CeedChk(ierr);
599   ierr = CeedCalloc(Q, &q_ref_1d); CeedChk(ierr);
600   ierr = CeedCalloc(Q, &q_weight_1d); CeedChk(ierr);
601   ierr = CeedLobattoQuadrature(P, nodes, NULL);
602   if (ierr) { goto cleanup; } CeedChk(ierr);
603   switch (quad_mode) {
604   case CEED_GAUSS:
605     ierr = CeedGaussQuadrature(Q, q_ref_1d, q_weight_1d);
606     break;
607   case CEED_GAUSS_LOBATTO:
608     ierr = CeedLobattoQuadrature(Q, q_ref_1d, q_weight_1d);
609     break;
610   }
611   if (ierr) { goto cleanup; } CeedChk(ierr);
612 
613   // Build B, D matrix
614   // Fornberg, 1998
615   for (i = 0; i  < Q; i++) {
616     c1 = 1.0;
617     c3 = nodes[0] - q_ref_1d[i];
618     interp_1d[i*P+0] = 1.0;
619     for (j = 1; j < P; j++) {
620       c2 = 1.0;
621       c4 = c3;
622       c3 = nodes[j] - q_ref_1d[i];
623       for (k = 0; k < j; k++) {
624         dx = nodes[j] - nodes[k];
625         c2 *= dx;
626         if (k == j - 1) {
627           grad_1d[i*P + j] = c1*(interp_1d[i*P + k] - c4*grad_1d[i*P + k]) / c2;
628           interp_1d[i*P + j] = - c1*c4*interp_1d[i*P + k] / c2;
629         }
630         grad_1d[i*P + k] = (c3*grad_1d[i*P + k] - interp_1d[i*P + k]) / dx;
631         interp_1d[i*P + k] = c3*interp_1d[i*P + k] / dx;
632       }
633       c1 = c2;
634     }
635   }
636   // Pass to CeedBasisCreateTensorH1
637   ierr = CeedBasisCreateTensorH1(ceed, dim, num_comp, P, Q, interp_1d, grad_1d,
638                                  q_ref_1d, q_weight_1d, basis); CeedChk(ierr);
639 cleanup:
640   ierr2 = CeedFree(&interp_1d); CeedChk(ierr2);
641   ierr2 = CeedFree(&grad_1d); CeedChk(ierr2);
642   ierr2 = CeedFree(&nodes); CeedChk(ierr2);
643   ierr2 = CeedFree(&q_ref_1d); CeedChk(ierr2);
644   ierr2 = CeedFree(&q_weight_1d); CeedChk(ierr2);
645   CeedChk(ierr);
646   return CEED_ERROR_SUCCESS;
647 }
648 
649 /**
650   @brief Create a non tensor-product basis for H^1 discretizations
651 
652   @param ceed        A Ceed object where the CeedBasis will be created
653   @param topo        Topology of element, e.g. hypercube, simplex, ect
654   @param num_comp    Number of field components (1 for scalar fields)
655   @param num_nodes   Total number of nodes
656   @param num_qpts    Total number of quadrature points
657   @param interp      Row-major (num_qpts * num_nodes) matrix expressing the values of
658                        nodal basis functions at quadrature points
659   @param grad        Row-major (num_qpts * dim * num_nodes) matrix expressing
660                        derivatives of nodal basis functions at quadrature points
661   @param q_ref       Array of length num_qpts holding the locations of quadrature
662                        points on the reference element
663   @param q_weight    Array of length num_qpts holding the quadrature weights on the
664                        reference element
665   @param[out] basis  Address of the variable where the newly created
666                        CeedBasis will be stored.
667 
668   @return An error code: 0 - success, otherwise - failure
669 
670   @ref User
671 **/
672 int CeedBasisCreateH1(Ceed ceed, CeedElemTopology topo, CeedInt num_comp,
673                       CeedInt num_nodes, CeedInt num_qpts, const CeedScalar *interp,
674                       const CeedScalar *grad, const CeedScalar *q_ref,
675                       const CeedScalar *q_weight, CeedBasis *basis) {
676   int ierr;
677   CeedInt P = num_nodes, Q = num_qpts, dim = 0;
678 
679   if (!ceed->BasisCreateH1) {
680     Ceed delegate;
681     ierr = CeedGetObjectDelegate(ceed, &delegate, "Basis"); CeedChk(ierr);
682 
683     if (!delegate)
684       // LCOV_EXCL_START
685       return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
686                        "Backend does not support BasisCreateH1");
687     // LCOV_EXCL_STOP
688 
689     ierr = CeedBasisCreateH1(delegate, topo, num_comp, num_nodes,
690                              num_qpts, interp, grad, q_ref,
691                              q_weight, basis); CeedChk(ierr);
692     return CEED_ERROR_SUCCESS;
693   }
694 
695   if (num_comp < 1)
696     // LCOV_EXCL_START
697     return CeedError(ceed, CEED_ERROR_DIMENSION,
698                      "Basis must have at least 1 component");
699   // LCOV_EXCL_STOP
700 
701   if (num_nodes < 1)
702     // LCOV_EXCL_START
703     return CeedError(ceed, CEED_ERROR_DIMENSION,
704                      "Basis must have at least 1 node");
705   // LCOV_EXCL_STOP
706 
707   if (num_qpts < 1)
708     // LCOV_EXCL_START
709     return CeedError(ceed, CEED_ERROR_DIMENSION,
710                      "Basis must have at least 1 quadrature point");
711   // LCOV_EXCL_STOP
712 
713   ierr = CeedCalloc(1, basis); CeedChk(ierr);
714 
715   ierr = CeedBasisGetTopologyDimension(topo, &dim); CeedChk(ierr);
716 
717   (*basis)->ceed = ceed;
718   ierr = CeedReference(ceed); CeedChk(ierr);
719   (*basis)->ref_count = 1;
720   (*basis)->tensor_basis = 0;
721   (*basis)->dim = dim;
722   (*basis)->topo = topo;
723   (*basis)->num_comp = num_comp;
724   (*basis)->P = P;
725   (*basis)->Q = Q;
726   (*basis)->Q_comp = 1;
727   (*basis)->basis_space = 1; // 1 for H^1 space
728   ierr = CeedCalloc(Q*dim, &(*basis)->q_ref_1d); CeedChk(ierr);
729   ierr = CeedCalloc(Q, &(*basis)->q_weight_1d); CeedChk(ierr);
730   if (q_ref) memcpy((*basis)->q_ref_1d, q_ref, Q*dim*sizeof(q_ref[0]));
731   if(q_weight) memcpy((*basis)->q_weight_1d, q_weight, Q*sizeof(q_weight[0]));
732   ierr = CeedCalloc(Q*P, &(*basis)->interp); CeedChk(ierr);
733   ierr = CeedCalloc(dim*Q*P, &(*basis)->grad); CeedChk(ierr);
734   if(interp) memcpy((*basis)->interp, interp, Q*P*sizeof(interp[0]));
735   if(grad) memcpy((*basis)->grad, grad, dim*Q*P*sizeof(grad[0]));
736   ierr = ceed->BasisCreateH1(topo, dim, P, Q, interp, grad, q_ref,
737                              q_weight, *basis); CeedChk(ierr);
738   return CEED_ERROR_SUCCESS;
739 }
740 
741 /**
742   @brief Create a non tensor-product basis for H(div) discretizations
743 
744   @param ceed        A Ceed object where the CeedBasis will be created
745   @param topo        Topology of element (`CEED_TOPOLOGY_QUAD`, `CEED_TOPOLOGY_PRISM`, etc.),
746                      dimension of which is used in some array sizes below
747   @param num_comp    Number of components (usually 1 for vectors in H(div) bases)
748   @param num_nodes   Total number of nodes (dofs per element)
749   @param num_qpts    Total number of quadrature points
750   @param interp      Row-major (dim*num_qpts * num_nodes) matrix expressing the values of
751                        nodal basis functions at quadrature points
752   @param div        Row-major (num_qpts * num_nodes) matrix expressing
753                        divergence of nodal basis functions at quadrature points
754   @param q_ref       Array of length num_qpts holding the locations of quadrature
755                        points on the reference element
756   @param q_weight    Array of length num_qpts holding the quadrature weights on the
757                        reference element
758   @param[out] basis  Address of the variable where the newly created
759                        CeedBasis will be stored.
760 
761   @return An error code: 0 - success, otherwise - failure
762 
763   @ref User
764 **/
765 int CeedBasisCreateHdiv(Ceed ceed, CeedElemTopology topo, CeedInt num_comp,
766                         CeedInt num_nodes, CeedInt num_qpts, const CeedScalar *interp,
767                         const CeedScalar *div, const CeedScalar *q_ref,
768                         const CeedScalar *q_weight, CeedBasis *basis) {
769   int ierr;
770   CeedInt Q = num_qpts, P = num_nodes, dim = 0;
771   ierr = CeedBasisGetTopologyDimension(topo, &dim); CeedChk(ierr);
772   if (!ceed->BasisCreateHdiv) {
773     Ceed delegate;
774     ierr = CeedGetObjectDelegate(ceed, &delegate, "Basis"); CeedChk(ierr);
775 
776     if (!delegate)
777       // LCOV_EXCL_START
778       return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
779                        "Backend does not implement BasisCreateHdiv");
780     // LCOV_EXCL_STOP
781 
782     ierr = CeedBasisCreateHdiv(delegate, topo, num_comp, num_nodes,
783                                num_qpts, interp, div, q_ref,
784                                q_weight, basis); CeedChk(ierr);
785     return CEED_ERROR_SUCCESS;
786   }
787 
788   if (num_comp < 1)
789     // LCOV_EXCL_START
790     return CeedError(ceed, CEED_ERROR_DIMENSION,
791                      "Basis must have at least 1 component");
792   // LCOV_EXCL_STOP
793 
794   if (num_nodes < 1)
795     // LCOV_EXCL_START
796     return CeedError(ceed, CEED_ERROR_DIMENSION,
797                      "Basis must have at least 1 node");
798   // LCOV_EXCL_STOP
799 
800   if (num_qpts < 1)
801     // LCOV_EXCL_START
802     return CeedError(ceed, CEED_ERROR_DIMENSION,
803                      "Basis must have at least 1 quadrature point");
804   // LCOV_EXCL_STOP
805 
806   ierr = CeedCalloc(1, basis); CeedChk(ierr);
807 
808   (*basis)->ceed = ceed;
809   ierr = CeedReference(ceed); CeedChk(ierr);
810   (*basis)->ref_count = 1;
811   (*basis)->tensor_basis = 0;
812   (*basis)->dim = dim;
813   (*basis)->topo = topo;
814   (*basis)->num_comp = num_comp;
815   (*basis)->P = P;
816   (*basis)->Q = Q;
817   (*basis)->Q_comp = dim;
818   (*basis)->basis_space = 2; // 2 for H(div) space
819   ierr = CeedMalloc(Q*dim, &(*basis)->q_ref_1d); CeedChk(ierr);
820   ierr = CeedMalloc(Q, &(*basis)->q_weight_1d); CeedChk(ierr);
821   if (q_ref) memcpy((*basis)->q_ref_1d, q_ref, Q*dim*sizeof(q_ref[0]));
822   if (q_weight) memcpy((*basis)->q_weight_1d, q_weight, Q*sizeof(q_weight[0]));
823   ierr = CeedMalloc(dim*Q*P, &(*basis)->interp); CeedChk(ierr);
824   ierr = CeedMalloc(Q*P, &(*basis)->div); CeedChk(ierr);
825   if (interp) memcpy((*basis)->interp, interp, dim*Q*P*sizeof(interp[0]));
826   if (div) memcpy((*basis)->div, div, Q*P*sizeof(div[0]));
827   ierr = ceed->BasisCreateHdiv(topo, dim, P, Q, interp, div, q_ref,
828                                q_weight, *basis); CeedChk(ierr);
829   return CEED_ERROR_SUCCESS;
830 }
831 
832 /**
833   @brief Create a CeedBasis for projection from the nodes of `basis_from`
834            to the nodes of `basis_to`. Only `CEED_EVAL_INTERP` will be
835            valid for the new basis, `basis_project`. This projection is
836            given by `interp_project = interp_to^+ * interp_from`, where
837            the pesudoinverse `interp_to^+` is given by QR factorization.
838          Note: `basis_from` and `basis_to` must have compatible quadrature
839            spaces.
840 
841   @param[in] basis_to        CeedBasis to prolong to
842   @param[in] basis_from      CeedBasis to prolong from
843   @param[out] basis_project  Address of the variable where the newly created
844                                CeedBasis will be stored.
845 
846   @return An error code: 0 - success, otherwise - failure
847 
848   @ref User
849 **/
850 int CeedBasisCreateProjection(CeedBasis basis_to, CeedBasis basis_from,
851                               CeedBasis *basis_project) {
852   int ierr;
853   Ceed ceed;
854   ierr = CeedBasisGetCeed(basis_to, &ceed); CeedChk(ierr);
855 
856   // Create projectior matrix
857   CeedScalar *interp_project;
858   ierr = CeedBasisCreateProjectionMatrix(basis_to, basis_from,
859                                          &interp_project); CeedChk(ierr);
860 
861   // Build basis
862   bool is_tensor;
863   CeedInt dim, num_comp;
864   CeedScalar *q_ref, *q_weight, *grad;
865   ierr = CeedBasisIsTensor(basis_to, &is_tensor); CeedChk(ierr);
866   ierr = CeedBasisGetDimension(basis_to, &dim); CeedChk(ierr);
867   ierr = CeedBasisGetNumComponents(basis_to, &num_comp); CeedChk(ierr);
868   if (is_tensor) {
869     CeedInt P_1d_to, P_1d_from;
870     ierr = CeedBasisGetNumNodes1D(basis_from, &P_1d_from); CeedChk(ierr);
871     ierr = CeedBasisGetNumNodes1D(basis_to, &P_1d_to); CeedChk(ierr);
872     ierr = CeedCalloc(P_1d_to, &q_ref); CeedChk(ierr);
873     ierr = CeedCalloc(P_1d_to, &q_weight); CeedChk(ierr);
874     ierr = CeedCalloc(P_1d_to * P_1d_from * dim, &grad); CeedChk(ierr);
875     ierr = CeedBasisCreateTensorH1(ceed, dim, num_comp, P_1d_from, P_1d_to,
876                                    interp_project, grad, q_ref, q_weight, basis_project);
877     CeedChk(ierr);
878   } else {
879     CeedElemTopology topo;
880     ierr = CeedBasisGetTopology(basis_to, &topo); CeedChk(ierr);
881     CeedInt num_nodes_to, num_nodes_from;
882     ierr = CeedBasisGetNumNodes(basis_from, &num_nodes_from); CeedChk(ierr);
883     ierr = CeedBasisGetNumNodes(basis_to, &num_nodes_to); CeedChk(ierr);
884     ierr = CeedCalloc(num_nodes_to * dim, &q_ref); CeedChk(ierr);
885     ierr = CeedCalloc(num_nodes_to, &q_weight); CeedChk(ierr);
886     ierr = CeedCalloc(num_nodes_to * num_nodes_from * dim, &grad); CeedChk(ierr);
887     ierr = CeedBasisCreateH1(ceed, topo, num_comp, num_nodes_from, num_nodes_to,
888                              interp_project, grad, q_ref, q_weight, basis_project);
889     CeedChk(ierr);
890   }
891 
892   // Cleanup
893   ierr = CeedFree(&interp_project); CeedChk(ierr);
894   ierr = CeedFree(&q_ref); CeedChk(ierr);
895   ierr = CeedFree(&q_weight); CeedChk(ierr);
896   ierr = CeedFree(&grad); CeedChk(ierr);
897 
898   return CEED_ERROR_SUCCESS;
899 }
900 
901 /**
902   @brief Create the interpolation matrix for projection from the nodes of
903            `basis_from` to the nodes of `basis_to`. This projection is
904            given by `interp_project = interp_to^+ * interp_from`, where
905            the pesudoinverse `interp_to^+` is given by QR factorization.
906          Note: `basis_from` and `basis_to` must have compatible quadrature
907            spaces.
908 
909   @param[in] basis_to         CeedBasis to project to
910   @param[in] basis_from       CeedBasis to project from
911   @param[out] interp_project  Address of the variable where the newly created
912                                 projection matrix will be stored.
913 
914   @return An error code: 0 - success, otherwise - failure
915 
916   @ref User
917 **/
918 int CeedBasisCreateProjectionMatrix(CeedBasis basis_to,
919                                     CeedBasis basis_from,
920                                     CeedScalar **interp_project) {
921   int ierr;
922   Ceed ceed;
923   ierr = CeedBasisGetCeed(basis_to, &ceed); CeedChk(ierr);
924 
925   // Check for compatible quadrature spaces
926   CeedInt Q_to, Q_from;
927   ierr = CeedBasisGetNumQuadraturePoints(basis_to, &Q_to); CeedChk(ierr);
928   ierr = CeedBasisGetNumQuadraturePoints(basis_from, &Q_from); CeedChk(ierr);
929   if (Q_to != Q_from)
930     // LCOV_EXCL_START
931     return CeedError(ceed, CEED_ERROR_DIMENSION,
932                      "Bases must have compatible quadrature spaces");
933   // LCOV_EXCL_STOP
934 
935   // Coarse to fine basis
936   CeedInt P_to, P_from, Q = Q_to;
937   bool is_tensor_to, is_tensor_from;
938   ierr = CeedBasisIsTensor(basis_to, &is_tensor_to); CeedChk(ierr);
939   ierr = CeedBasisIsTensor(basis_from, &is_tensor_from); CeedChk(ierr);
940   CeedScalar *interp_to, *interp_from, *tau;
941   if (is_tensor_to && is_tensor_from) {
942     ierr = CeedBasisGetNumNodes1D(basis_to, &P_to); CeedChk(ierr);
943     ierr = CeedBasisGetNumNodes1D(basis_from, &P_from); CeedChk(ierr);
944     ierr = CeedBasisGetNumQuadraturePoints1D(basis_from, &Q); CeedChk(ierr);
945   } else if (!is_tensor_to && !is_tensor_from) {
946     ierr = CeedBasisGetNumNodes(basis_to, &P_to); CeedChk(ierr);
947     ierr = CeedBasisGetNumNodes(basis_from, &P_from); CeedChk(ierr);
948   } else {
949     // LCOV_EXCL_START
950     return CeedError(ceed, CEED_ERROR_MINOR,
951                      "Bases must both be tensor or non-tensor");
952     // LCOV_EXCL_STOP
953   }
954 
955   ierr = CeedMalloc(Q * P_from, &interp_from); CeedChk(ierr);
956   ierr = CeedMalloc(Q * P_to, &interp_to); CeedChk(ierr);
957   ierr = CeedCalloc(P_to * P_from, interp_project); CeedChk(ierr);
958   ierr = CeedMalloc(Q, &tau); CeedChk(ierr);
959   const CeedScalar *interp_to_source = NULL, *interp_from_source = NULL;
960   if (is_tensor_to) {
961     ierr = CeedBasisGetInterp1D(basis_to, &interp_to_source); CeedChk(ierr);
962     ierr = CeedBasisGetInterp1D(basis_from, &interp_from_source); CeedChk(ierr);
963   } else {
964     ierr = CeedBasisGetInterp(basis_to, &interp_to_source); CeedChk(ierr);
965     ierr = CeedBasisGetInterp(basis_from, &interp_from_source); CeedChk(ierr);
966   }
967   memcpy(interp_to, interp_to_source, Q * P_to * sizeof(interp_to_source[0]));
968   memcpy(interp_from, interp_from_source,
969          Q * P_from * sizeof(interp_from_source[0]));
970 
971   // -- QR Factorization, interp_to = Q R
972   ierr = CeedQRFactorization(ceed, interp_to, tau, Q, P_to); CeedChk(ierr);
973 
974   // -- Apply Qtranspose, interp_to = Qtranspose interp_from
975   ierr = CeedHouseholderApplyQ(interp_from, interp_to, tau, CEED_TRANSPOSE,
976                                Q, P_from, P_to, P_from, 1); CeedChk(ierr);
977 
978   // -- Apply Rinv, interp_project = Rinv interp_c
979   for (CeedInt j = 0; j < P_from; j++) { // Column j
980     (*interp_project)[j + P_from * (P_to - 1)] = interp_from[j + P_from *
981         (P_to - 1)] / interp_to[P_to * P_to - 1];
982     for (CeedInt i = P_to - 2; i >= 0; i--) { // Row i
983       (*interp_project)[j + P_from * i] = interp_from[j + P_from * i];
984       for (CeedInt k = i+1; k < P_to; k++) {
985         (*interp_project)[j + P_from * i] -= interp_to[k + P_to * i]*
986                                              (*interp_project)[j + P_from * k];
987       }
988       (*interp_project)[j + P_from * i] /= interp_to[i + P_to * i];
989     }
990   }
991   ierr = CeedFree(&tau); CeedChk(ierr);
992   ierr = CeedFree(&interp_to); CeedChk(ierr);
993   ierr = CeedFree(&interp_from); CeedChk(ierr);
994 
995   return CEED_ERROR_SUCCESS;
996 }
997 
998 /**
999   @brief Copy the pointer to a CeedBasis. Both pointers should
1000            be destroyed with `CeedBasisDestroy()`;
1001            Note: If `*basis_copy` is non-NULL, then it is assumed that
1002            `*basis_copy` is a pointer to a CeedBasis. This CeedBasis
1003            will be destroyed if `*basis_copy` is the only
1004            reference to this CeedBasis.
1005 
1006   @param basis            CeedBasis to copy reference to
1007   @param[out] basis_copy  Variable to store copied reference
1008 
1009   @return An error code: 0 - success, otherwise - failure
1010 
1011   @ref User
1012 **/
1013 int CeedBasisReferenceCopy(CeedBasis basis, CeedBasis *basis_copy) {
1014   int ierr;
1015 
1016   ierr = CeedBasisReference(basis); CeedChk(ierr);
1017   ierr = CeedBasisDestroy(basis_copy); CeedChk(ierr);
1018   *basis_copy = basis;
1019   return CEED_ERROR_SUCCESS;
1020 }
1021 
1022 /**
1023   @brief View a CeedBasis
1024 
1025   @param basis   CeedBasis to view
1026   @param stream  Stream to view to, e.g., stdout
1027 
1028   @return An error code: 0 - success, otherwise - failure
1029 
1030   @ref User
1031 **/
1032 int CeedBasisView(CeedBasis basis, FILE *stream) {
1033   int ierr;
1034   CeedFESpace FE_space = basis->basis_space;
1035   CeedElemTopology topo = basis->topo;
1036   // Print FE space and element topology of the basis
1037   if (basis->tensor_basis) {
1038     fprintf(stream, "CeedBasis (%s on a %s element): dim=%d P=%d Q=%d\n",
1039             CeedFESpaces[FE_space], CeedElemTopologies[topo],
1040             basis->dim, basis->P_1d, basis->Q_1d);
1041   } else {
1042     fprintf(stream, "CeedBasis (%s on a %s element): dim=%d P=%d Q=%d\n",
1043             CeedFESpaces[FE_space], CeedElemTopologies[topo],
1044             basis->dim, basis->P, basis->Q);
1045   }
1046   // Print quadrature data, interpolation/gradient/divergene/curl of the basis
1047   if (basis->tensor_basis) { // tensor basis
1048     ierr = CeedScalarView("qref1d", "\t% 12.8f", 1, basis->Q_1d, basis->q_ref_1d,
1049                           stream); CeedChk(ierr);
1050     ierr = CeedScalarView("qweight1d", "\t% 12.8f", 1, basis->Q_1d,
1051                           basis->q_weight_1d, stream); CeedChk(ierr);
1052     ierr = CeedScalarView("interp1d", "\t% 12.8f", basis->Q_1d, basis->P_1d,
1053                           basis->interp_1d, stream); CeedChk(ierr);
1054     ierr = CeedScalarView("grad1d", "\t% 12.8f", basis->Q_1d, basis->P_1d,
1055                           basis->grad_1d, stream); CeedChk(ierr);
1056   } else { // non-tensor basis
1057     ierr = CeedScalarView("qref", "\t% 12.8f", 1, basis->Q*basis->dim,
1058                           basis->q_ref_1d,
1059                           stream); CeedChk(ierr);
1060     ierr = CeedScalarView("qweight", "\t% 12.8f", 1, basis->Q, basis->q_weight_1d,
1061                           stream); CeedChk(ierr);
1062     ierr = CeedScalarView("interp", "\t% 12.8f", basis->Q_comp*basis->Q, basis->P,
1063                           basis->interp, stream); CeedChk(ierr);
1064     if (basis->grad) {
1065       ierr = CeedScalarView("grad", "\t% 12.8f", basis->dim*basis->Q, basis->P,
1066                             basis->grad, stream); CeedChk(ierr);
1067     }
1068     if (basis->div) {
1069       ierr = CeedScalarView("div", "\t% 12.8f", basis->Q, basis->P,
1070                             basis->div, stream); CeedChk(ierr);
1071     }
1072   }
1073   return CEED_ERROR_SUCCESS;
1074 }
1075 
1076 /**
1077   @brief Apply basis evaluation from nodes to quadrature points or vice versa
1078 
1079   @param basis     CeedBasis to evaluate
1080   @param num_elem  The number of elements to apply the basis evaluation to;
1081                      the backend will specify the ordering in
1082                      CeedElemRestrictionCreateBlocked()
1083   @param t_mode    \ref CEED_NOTRANSPOSE to evaluate from nodes to quadrature
1084                      points, \ref CEED_TRANSPOSE to apply the transpose, mapping
1085                      from quadrature points to nodes
1086   @param eval_mode \ref CEED_EVAL_NONE to use values directly,
1087                      \ref CEED_EVAL_INTERP to use interpolated values,
1088                      \ref CEED_EVAL_GRAD to use gradients,
1089                      \ref CEED_EVAL_WEIGHT to use quadrature weights.
1090   @param[in] u     Input CeedVector
1091   @param[out] v    Output CeedVector
1092 
1093   @return An error code: 0 - success, otherwise - failure
1094 
1095   @ref User
1096 **/
1097 int CeedBasisApply(CeedBasis basis, CeedInt num_elem, CeedTransposeMode t_mode,
1098                    CeedEvalMode eval_mode, CeedVector u, CeedVector v) {
1099   int ierr;
1100   CeedSize u_length = 0, v_length;
1101   CeedInt dim, num_comp, num_nodes, num_qpts;
1102   ierr = CeedBasisGetDimension(basis, &dim); CeedChk(ierr);
1103   ierr = CeedBasisGetNumComponents(basis, &num_comp); CeedChk(ierr);
1104   ierr = CeedBasisGetNumNodes(basis, &num_nodes); CeedChk(ierr);
1105   ierr = CeedBasisGetNumQuadraturePoints(basis, &num_qpts); CeedChk(ierr);
1106   ierr = CeedVectorGetLength(v, &v_length); CeedChk(ierr);
1107   if (u) {
1108     ierr = CeedVectorGetLength(u, &u_length); CeedChk(ierr);
1109   }
1110 
1111   if (!basis->Apply)
1112     // LCOV_EXCL_START
1113     return CeedError(basis->ceed, CEED_ERROR_UNSUPPORTED,
1114                      "Backend does not support BasisApply");
1115   // LCOV_EXCL_STOP
1116 
1117   // Check compatibility of topological and geometrical dimensions
1118   if ((t_mode == CEED_TRANSPOSE && (v_length%num_nodes != 0 ||
1119                                     u_length%num_qpts != 0)) ||
1120       (t_mode == CEED_NOTRANSPOSE && (u_length%num_nodes != 0 ||
1121                                       v_length%num_qpts != 0)))
1122     // LCOV_EXCL_START
1123     return CeedError(basis->ceed, CEED_ERROR_DIMENSION,
1124                      "Length of input/output vectors "
1125                      "incompatible with basis dimensions");
1126   // LCOV_EXCL_STOP
1127 
1128   // Check vector lengths to prevent out of bounds issues
1129   bool bad_dims = false;
1130   switch (eval_mode) {
1131   case CEED_EVAL_NONE:
1132   case CEED_EVAL_INTERP: bad_dims =
1133       ((t_mode == CEED_TRANSPOSE && (u_length < num_elem*num_comp*num_qpts ||
1134                                      v_length < num_elem*num_comp*num_nodes)) ||
1135        (t_mode == CEED_NOTRANSPOSE && (v_length < num_elem*num_qpts*num_comp ||
1136                                        u_length < num_elem*num_comp*num_nodes)));
1137     break;
1138   case CEED_EVAL_GRAD: bad_dims =
1139       ((t_mode == CEED_TRANSPOSE && (u_length < num_elem*num_comp*num_qpts*dim ||
1140                                      v_length < num_elem*num_comp*num_nodes)) ||
1141        (t_mode == CEED_NOTRANSPOSE && (v_length < num_elem*num_qpts*num_comp*dim ||
1142                                        u_length < num_elem*num_comp*num_nodes)));
1143     break;
1144   case CEED_EVAL_WEIGHT:
1145     bad_dims = v_length < num_elem*num_qpts;
1146     break;
1147   // LCOV_EXCL_START
1148   case CEED_EVAL_DIV: bad_dims =
1149       ((t_mode == CEED_TRANSPOSE && (u_length < num_elem*num_comp*num_qpts ||
1150                                      v_length < num_elem*num_comp*num_nodes)) ||
1151        (t_mode == CEED_NOTRANSPOSE && (v_length < num_elem*num_qpts*num_comp ||
1152                                        u_length < num_elem*num_comp*num_nodes)));
1153     break;
1154   case CEED_EVAL_CURL: bad_dims =
1155       ((t_mode == CEED_TRANSPOSE && (u_length < num_elem*num_comp*num_qpts ||
1156                                      v_length < num_elem*num_comp*num_nodes)) ||
1157        (t_mode == CEED_NOTRANSPOSE && (v_length < num_elem*num_qpts*num_comp ||
1158                                        u_length < num_elem*num_comp*num_nodes)));
1159     break;
1160     // LCOV_EXCL_STOP
1161   }
1162   if (bad_dims)
1163     // LCOV_EXCL_START
1164     return CeedError(basis->ceed, CEED_ERROR_DIMENSION,
1165                      "Input/output vectors too short for basis and evaluation mode");
1166   // LCOV_EXCL_STOP
1167 
1168   ierr = basis->Apply(basis, num_elem, t_mode, eval_mode, u, v); CeedChk(ierr);
1169   return CEED_ERROR_SUCCESS;
1170 }
1171 
1172 /**
1173   @brief Get Ceed associated with a CeedBasis
1174 
1175   @param basis      CeedBasis
1176   @param[out] ceed  Variable to store Ceed
1177 
1178   @return An error code: 0 - success, otherwise - failure
1179 
1180   @ref Advanced
1181 **/
1182 int CeedBasisGetCeed(CeedBasis basis, Ceed *ceed) {
1183   *ceed = basis->ceed;
1184   return CEED_ERROR_SUCCESS;
1185 }
1186 
1187 /**
1188   @brief Get dimension for given CeedBasis
1189 
1190   @param basis     CeedBasis
1191   @param[out] dim  Variable to store dimension of basis
1192 
1193   @return An error code: 0 - success, otherwise - failure
1194 
1195   @ref Advanced
1196 **/
1197 int CeedBasisGetDimension(CeedBasis basis, CeedInt *dim) {
1198   *dim = basis->dim;
1199   return CEED_ERROR_SUCCESS;
1200 }
1201 
1202 /**
1203   @brief Get topology for given CeedBasis
1204 
1205   @param basis      CeedBasis
1206   @param[out] topo  Variable to store topology of basis
1207 
1208   @return An error code: 0 - success, otherwise - failure
1209 
1210   @ref Advanced
1211 **/
1212 int CeedBasisGetTopology(CeedBasis basis, CeedElemTopology *topo) {
1213   *topo = basis->topo;
1214   return CEED_ERROR_SUCCESS;
1215 }
1216 
1217 /**
1218   @brief Get number of Q-vector components for given CeedBasis
1219 
1220   @param basis          CeedBasis
1221   @param[out] Q_comp  Variable to store number of Q-vector components of basis
1222 
1223   @return An error code: 0 - success, otherwise - failure
1224 
1225   @ref Advanced
1226 **/
1227 int CeedBasisGetNumQuadratureComponents(CeedBasis basis, CeedInt *Q_comp) {
1228   *Q_comp = basis->Q_comp;
1229   return CEED_ERROR_SUCCESS;
1230 }
1231 
1232 /**
1233   @brief Get number of components for given CeedBasis
1234 
1235   @param basis          CeedBasis
1236   @param[out] num_comp  Variable to store number of components of basis
1237 
1238   @return An error code: 0 - success, otherwise - failure
1239 
1240   @ref Advanced
1241 **/
1242 int CeedBasisGetNumComponents(CeedBasis basis, CeedInt *num_comp) {
1243   *num_comp = basis->num_comp;
1244   return CEED_ERROR_SUCCESS;
1245 }
1246 
1247 /**
1248   @brief Get total number of nodes (in dim dimensions) of a CeedBasis
1249 
1250   @param basis   CeedBasis
1251   @param[out] P  Variable to store number of nodes
1252 
1253   @return An error code: 0 - success, otherwise - failure
1254 
1255   @ref Utility
1256 **/
1257 int CeedBasisGetNumNodes(CeedBasis basis, CeedInt *P) {
1258   *P = basis->P;
1259   return CEED_ERROR_SUCCESS;
1260 }
1261 
1262 /**
1263   @brief Get total number of nodes (in 1 dimension) of a CeedBasis
1264 
1265   @param basis     CeedBasis
1266   @param[out] P_1d  Variable to store number of nodes
1267 
1268   @return An error code: 0 - success, otherwise - failure
1269 
1270   @ref Advanced
1271 **/
1272 int CeedBasisGetNumNodes1D(CeedBasis basis, CeedInt *P_1d) {
1273   if (!basis->tensor_basis)
1274     // LCOV_EXCL_START
1275     return CeedError(basis->ceed, CEED_ERROR_MINOR,
1276                      "Cannot supply P_1d for non-tensor basis");
1277   // LCOV_EXCL_STOP
1278 
1279   *P_1d = basis->P_1d;
1280   return CEED_ERROR_SUCCESS;
1281 }
1282 
1283 /**
1284   @brief Get total number of quadrature points (in dim dimensions) of a CeedBasis
1285 
1286   @param basis   CeedBasis
1287   @param[out] Q  Variable to store number of quadrature points
1288 
1289   @return An error code: 0 - success, otherwise - failure
1290 
1291   @ref Utility
1292 **/
1293 int CeedBasisGetNumQuadraturePoints(CeedBasis basis, CeedInt *Q) {
1294   *Q = basis->Q;
1295   return CEED_ERROR_SUCCESS;
1296 }
1297 
1298 /**
1299   @brief Get total number of quadrature points (in 1 dimension) of a CeedBasis
1300 
1301   @param basis      CeedBasis
1302   @param[out] Q_1d  Variable to store number of quadrature points
1303 
1304   @return An error code: 0 - success, otherwise - failure
1305 
1306   @ref Advanced
1307 **/
1308 int CeedBasisGetNumQuadraturePoints1D(CeedBasis basis, CeedInt *Q_1d) {
1309   if (!basis->tensor_basis)
1310     // LCOV_EXCL_START
1311     return CeedError(basis->ceed, CEED_ERROR_MINOR,
1312                      "Cannot supply Q_1d for non-tensor basis");
1313   // LCOV_EXCL_STOP
1314 
1315   *Q_1d = basis->Q_1d;
1316   return CEED_ERROR_SUCCESS;
1317 }
1318 
1319 /**
1320   @brief Get reference coordinates of quadrature points (in dim dimensions)
1321          of a CeedBasis
1322 
1323   @param basis       CeedBasis
1324   @param[out] q_ref  Variable to store reference coordinates of quadrature points
1325 
1326   @return An error code: 0 - success, otherwise - failure
1327 
1328   @ref Advanced
1329 **/
1330 int CeedBasisGetQRef(CeedBasis basis, const CeedScalar **q_ref) {
1331   *q_ref = basis->q_ref_1d;
1332   return CEED_ERROR_SUCCESS;
1333 }
1334 
1335 /**
1336   @brief Get quadrature weights of quadrature points (in dim dimensions)
1337          of a CeedBasis
1338 
1339   @param basis          CeedBasis
1340   @param[out] q_weight  Variable to store quadrature weights
1341 
1342   @return An error code: 0 - success, otherwise - failure
1343 
1344   @ref Advanced
1345 **/
1346 int CeedBasisGetQWeights(CeedBasis basis, const CeedScalar **q_weight) {
1347   *q_weight = basis->q_weight_1d;
1348   return CEED_ERROR_SUCCESS;
1349 }
1350 
1351 /**
1352   @brief Get interpolation matrix of a CeedBasis
1353 
1354   @param basis        CeedBasis
1355   @param[out] interp  Variable to store interpolation matrix
1356 
1357   @return An error code: 0 - success, otherwise - failure
1358 
1359   @ref Advanced
1360 **/
1361 int CeedBasisGetInterp(CeedBasis basis, const CeedScalar **interp) {
1362   if (!basis->interp && basis->tensor_basis) {
1363     // Allocate
1364     int ierr;
1365     ierr = CeedMalloc(basis->Q*basis->P, &basis->interp); CeedChk(ierr);
1366 
1367     // Initialize
1368     for (CeedInt i=0; i<basis->Q*basis->P; i++)
1369       basis->interp[i] = 1.0;
1370 
1371     // Calculate
1372     for (CeedInt d=0; d<basis->dim; d++)
1373       for (CeedInt qpt=0; qpt<basis->Q; qpt++)
1374         for (CeedInt node=0; node<basis->P; node++) {
1375           CeedInt p = (node / CeedIntPow(basis->P_1d, d)) % basis->P_1d;
1376           CeedInt q = (qpt / CeedIntPow(basis->Q_1d, d)) % basis->Q_1d;
1377           basis->interp[qpt*(basis->P)+node] *= basis->interp_1d[q*basis->P_1d+p];
1378         }
1379   }
1380   *interp = basis->interp;
1381   return CEED_ERROR_SUCCESS;
1382 }
1383 
1384 /**
1385   @brief Get 1D interpolation matrix of a tensor product CeedBasis
1386 
1387   @param basis           CeedBasis
1388   @param[out] interp_1d  Variable to store interpolation matrix
1389 
1390   @return An error code: 0 - success, otherwise - failure
1391 
1392   @ref Backend
1393 **/
1394 int CeedBasisGetInterp1D(CeedBasis basis, const CeedScalar **interp_1d) {
1395   if (!basis->tensor_basis)
1396     // LCOV_EXCL_START
1397     return CeedError(basis->ceed, CEED_ERROR_MINOR,
1398                      "CeedBasis is not a tensor product basis.");
1399   // LCOV_EXCL_STOP
1400 
1401   *interp_1d = basis->interp_1d;
1402   return CEED_ERROR_SUCCESS;
1403 }
1404 
1405 /**
1406   @brief Get gradient matrix of a CeedBasis
1407 
1408   @param basis      CeedBasis
1409   @param[out] grad  Variable to store gradient matrix
1410 
1411   @return An error code: 0 - success, otherwise - failure
1412 
1413   @ref Advanced
1414 **/
1415 int CeedBasisGetGrad(CeedBasis basis, const CeedScalar **grad) {
1416   if (!basis->grad && basis->tensor_basis) {
1417     // Allocate
1418     int ierr;
1419     ierr = CeedMalloc(basis->dim*basis->Q*basis->P, &basis->grad);
1420     CeedChk(ierr);
1421 
1422     // Initialize
1423     for (CeedInt i=0; i<basis->dim*basis->Q*basis->P; i++)
1424       basis->grad[i] = 1.0;
1425 
1426     // Calculate
1427     for (CeedInt d=0; d<basis->dim; d++)
1428       for (CeedInt i=0; i<basis->dim; i++)
1429         for (CeedInt qpt=0; qpt<basis->Q; qpt++)
1430           for (CeedInt node=0; node<basis->P; node++) {
1431             CeedInt p = (node / CeedIntPow(basis->P_1d, d)) % basis->P_1d;
1432             CeedInt q = (qpt / CeedIntPow(basis->Q_1d, d)) % basis->Q_1d;
1433             if (i == d)
1434               basis->grad[(i*basis->Q+qpt)*(basis->P)+node] *=
1435                 basis->grad_1d[q*basis->P_1d+p];
1436             else
1437               basis->grad[(i*basis->Q+qpt)*(basis->P)+node] *=
1438                 basis->interp_1d[q*basis->P_1d+p];
1439           }
1440   }
1441   *grad = basis->grad;
1442   return CEED_ERROR_SUCCESS;
1443 }
1444 
1445 /**
1446   @brief Get 1D gradient matrix of a tensor product CeedBasis
1447 
1448   @param basis         CeedBasis
1449   @param[out] grad_1d  Variable to store gradient matrix
1450 
1451   @return An error code: 0 - success, otherwise - failure
1452 
1453   @ref Advanced
1454 **/
1455 int CeedBasisGetGrad1D(CeedBasis basis, const CeedScalar **grad_1d) {
1456   if (!basis->tensor_basis)
1457     // LCOV_EXCL_START
1458     return CeedError(basis->ceed, CEED_ERROR_MINOR,
1459                      "CeedBasis is not a tensor product basis.");
1460   // LCOV_EXCL_STOP
1461 
1462   *grad_1d = basis->grad_1d;
1463   return CEED_ERROR_SUCCESS;
1464 }
1465 
1466 /**
1467   @brief Get divergence matrix of a CeedBasis
1468 
1469   @param basis     CeedBasis
1470   @param[out] div  Variable to store divergence matrix
1471 
1472   @return An error code: 0 - success, otherwise - failure
1473 
1474   @ref Advanced
1475 **/
1476 int CeedBasisGetDiv(CeedBasis basis, const CeedScalar **div) {
1477   if (!basis->div)
1478     // LCOV_EXCL_START
1479     return CeedError(basis->ceed, CEED_ERROR_MINOR,
1480                      "CeedBasis does not have divergence matrix.");
1481   // LCOV_EXCL_STOP
1482 
1483   *div = basis->div;
1484   return CEED_ERROR_SUCCESS;
1485 }
1486 
1487 /**
1488   @brief Destroy a CeedBasis
1489 
1490   @param basis CeedBasis to destroy
1491 
1492   @return An error code: 0 - success, otherwise - failure
1493 
1494   @ref User
1495 **/
1496 int CeedBasisDestroy(CeedBasis *basis) {
1497   int ierr;
1498 
1499   if (!*basis || --(*basis)->ref_count > 0) return CEED_ERROR_SUCCESS;
1500   if ((*basis)->Destroy) {
1501     ierr = (*basis)->Destroy(*basis); CeedChk(ierr);
1502   }
1503   if ((*basis)->contract) {
1504     ierr = CeedTensorContractDestroy(&(*basis)->contract); CeedChk(ierr);
1505   }
1506   ierr = CeedFree(&(*basis)->interp); CeedChk(ierr);
1507   ierr = CeedFree(&(*basis)->interp_1d); CeedChk(ierr);
1508   ierr = CeedFree(&(*basis)->grad); CeedChk(ierr);
1509   ierr = CeedFree(&(*basis)->div); CeedChk(ierr);
1510   ierr = CeedFree(&(*basis)->grad_1d); CeedChk(ierr);
1511   ierr = CeedFree(&(*basis)->q_ref_1d); CeedChk(ierr);
1512   ierr = CeedFree(&(*basis)->q_weight_1d); CeedChk(ierr);
1513   ierr = CeedDestroy(&(*basis)->ceed); CeedChk(ierr);
1514   ierr = CeedFree(basis); CeedChk(ierr);
1515   return CEED_ERROR_SUCCESS;
1516 }
1517 
1518 /**
1519   @brief Construct a Gauss-Legendre quadrature
1520 
1521   @param Q                 Number of quadrature points (integrates polynomials of
1522                              degree 2*Q-1 exactly)
1523   @param[out] q_ref_1d     Array of length Q to hold the abscissa on [-1, 1]
1524   @param[out] q_weight_1d  Array of length Q to hold the weights
1525 
1526   @return An error code: 0 - success, otherwise - failure
1527 
1528   @ref Utility
1529 **/
1530 int CeedGaussQuadrature(CeedInt Q, CeedScalar *q_ref_1d,
1531                         CeedScalar *q_weight_1d) {
1532   // Allocate
1533   CeedScalar P0, P1, P2, dP2, xi, wi, PI = 4.0*atan(1.0);
1534   // Build q_ref_1d, q_weight_1d
1535   for (CeedInt i = 0; i <= Q/2; i++) {
1536     // Guess
1537     xi = cos(PI*(CeedScalar)(2*i+1)/((CeedScalar)(2*Q)));
1538     // Pn(xi)
1539     P0 = 1.0;
1540     P1 = xi;
1541     P2 = 0.0;
1542     for (CeedInt j = 2; j <= Q; j++) {
1543       P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j));
1544       P0 = P1;
1545       P1 = P2;
1546     }
1547     // First Newton Step
1548     dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0);
1549     xi = xi-P2/dP2;
1550     // Newton to convergence
1551     for (CeedInt k=0; k<100 && fabs(P2)>10*CEED_EPSILON; k++) {
1552       P0 = 1.0;
1553       P1 = xi;
1554       for (CeedInt j = 2; j <= Q; j++) {
1555         P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j));
1556         P0 = P1;
1557         P1 = P2;
1558       }
1559       dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0);
1560       xi = xi-P2/dP2;
1561     }
1562     // Save xi, wi
1563     wi = 2.0/((1.0-xi*xi)*dP2*dP2);
1564     q_weight_1d[i] = wi;
1565     q_weight_1d[Q-1-i] = wi;
1566     q_ref_1d[i] = -xi;
1567     q_ref_1d[Q-1-i]= xi;
1568   }
1569   return CEED_ERROR_SUCCESS;
1570 }
1571 
1572 /**
1573   @brief Construct a Gauss-Legendre-Lobatto quadrature
1574 
1575   @param Q                 Number of quadrature points (integrates polynomials of
1576                              degree 2*Q-3 exactly)
1577   @param[out] q_ref_1d     Array of length Q to hold the abscissa on [-1, 1]
1578   @param[out] q_weight_1d  Array of length Q to hold the weights
1579 
1580   @return An error code: 0 - success, otherwise - failure
1581 
1582   @ref Utility
1583 **/
1584 int CeedLobattoQuadrature(CeedInt Q, CeedScalar *q_ref_1d,
1585                           CeedScalar *q_weight_1d) {
1586   // Allocate
1587   CeedScalar P0, P1, P2, dP2, d2P2, xi, wi, PI = 4.0*atan(1.0);
1588   // Build q_ref_1d, q_weight_1d
1589   // Set endpoints
1590   if (Q < 2)
1591     // LCOV_EXCL_START
1592     return CeedError(NULL, CEED_ERROR_DIMENSION,
1593                      "Cannot create Lobatto quadrature with Q=%d < 2 points", Q);
1594   // LCOV_EXCL_STOP
1595   wi = 2.0/((CeedScalar)(Q*(Q-1)));
1596   if (q_weight_1d) {
1597     q_weight_1d[0] = wi;
1598     q_weight_1d[Q-1] = wi;
1599   }
1600   q_ref_1d[0] = -1.0;
1601   q_ref_1d[Q-1] = 1.0;
1602   // Interior
1603   for (CeedInt i = 1; i <= (Q-1)/2; i++) {
1604     // Guess
1605     xi = cos(PI*(CeedScalar)(i)/(CeedScalar)(Q-1));
1606     // Pn(xi)
1607     P0 = 1.0;
1608     P1 = xi;
1609     P2 = 0.0;
1610     for (CeedInt j = 2; j < Q; j++) {
1611       P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j));
1612       P0 = P1;
1613       P1 = P2;
1614     }
1615     // First Newton step
1616     dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0);
1617     d2P2 = (2*xi*dP2 - (CeedScalar)(Q*(Q-1))*P2)/(1.0-xi*xi);
1618     xi = xi-dP2/d2P2;
1619     // Newton to convergence
1620     for (CeedInt k=0; k<100 && fabs(dP2)>10*CEED_EPSILON; k++) {
1621       P0 = 1.0;
1622       P1 = xi;
1623       for (CeedInt j = 2; j < Q; j++) {
1624         P2 = (((CeedScalar)(2*j-1))*xi*P1-((CeedScalar)(j-1))*P0)/((CeedScalar)(j));
1625         P0 = P1;
1626         P1 = P2;
1627       }
1628       dP2 = (xi*P2 - P0)*(CeedScalar)Q/(xi*xi-1.0);
1629       d2P2 = (2*xi*dP2 - (CeedScalar)(Q*(Q-1))*P2)/(1.0-xi*xi);
1630       xi = xi-dP2/d2P2;
1631     }
1632     // Save xi, wi
1633     wi = 2.0/(((CeedScalar)(Q*(Q-1)))*P2*P2);
1634     if (q_weight_1d) {
1635       q_weight_1d[i] = wi;
1636       q_weight_1d[Q-1-i] = wi;
1637     }
1638     q_ref_1d[i] = -xi;
1639     q_ref_1d[Q-1-i]= xi;
1640   }
1641   return CEED_ERROR_SUCCESS;
1642 }
1643 
1644 /**
1645   @brief Return QR Factorization of a matrix
1646 
1647   @param ceed         A Ceed context for error handling
1648   @param[in,out] mat  Row-major matrix to be factorized in place
1649   @param[in,out] tau  Vector of length m of scaling factors
1650   @param m            Number of rows
1651   @param n            Number of columns
1652 
1653   @return An error code: 0 - success, otherwise - failure
1654 
1655   @ref Utility
1656 **/
1657 int CeedQRFactorization(Ceed ceed, CeedScalar *mat, CeedScalar *tau,
1658                         CeedInt m, CeedInt n) {
1659   CeedScalar v[m];
1660 
1661   // Check m >= n
1662   if (n > m)
1663     // LCOV_EXCL_START
1664     return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
1665                      "Cannot compute QR factorization with n > m");
1666   // LCOV_EXCL_STOP
1667 
1668   for (CeedInt i=0; i<n; i++) {
1669     if (i >= m-1) { // last row of matrix, no reflection needed
1670       tau[i] = 0.;
1671       break;
1672     }
1673     // Calculate Householder vector, magnitude
1674     CeedScalar sigma = 0.0;
1675     v[i] = mat[i+n*i];
1676     for (CeedInt j=i+1; j<m; j++) {
1677       v[j] = mat[i+n*j];
1678       sigma += v[j] * v[j];
1679     }
1680     CeedScalar norm = sqrt(v[i]*v[i] + sigma); // norm of v[i:m]
1681     CeedScalar R_ii = -copysign(norm, v[i]);
1682     v[i] -= R_ii;
1683     // norm of v[i:m] after modification above and scaling below
1684     //   norm = sqrt(v[i]*v[i] + sigma) / v[i];
1685     //   tau = 2 / (norm*norm)
1686     tau[i] = 2 * v[i]*v[i] / (v[i]*v[i] + sigma);
1687     for (CeedInt j=i+1; j<m; j++)
1688       v[j] /= v[i];
1689 
1690     // Apply Householder reflector to lower right panel
1691     CeedHouseholderReflect(&mat[i*n+i+1], &v[i], tau[i], m-i, n-i-1, n, 1);
1692     // Save v
1693     mat[i+n*i] = R_ii;
1694     for (CeedInt j=i+1; j<m; j++)
1695       mat[i+n*j] = v[j];
1696   }
1697   return CEED_ERROR_SUCCESS;
1698 }
1699 
1700 /**
1701   @brief Return symmetric Schur decomposition of the symmetric matrix mat via
1702            symmetric QR factorization
1703 
1704   @param ceed         A Ceed context for error handling
1705   @param[in,out] mat  Row-major matrix to be factorized in place
1706   @param[out] lambda  Vector of length n of eigenvalues
1707   @param n            Number of rows/columns
1708 
1709   @return An error code: 0 - success, otherwise - failure
1710 
1711   @ref Utility
1712 **/
1713 CeedPragmaOptimizeOff
1714 int CeedSymmetricSchurDecomposition(Ceed ceed, CeedScalar *mat,
1715                                     CeedScalar *lambda, CeedInt n) {
1716   // Check bounds for clang-tidy
1717   if (n<2)
1718     // LCOV_EXCL_START
1719     return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
1720                      "Cannot compute symmetric Schur decomposition of scalars");
1721   // LCOV_EXCL_STOP
1722 
1723   CeedScalar v[n-1], tau[n-1], mat_T[n*n];
1724 
1725   // Copy mat to mat_T and set mat to I
1726   memcpy(mat_T, mat, n*n*sizeof(mat[0]));
1727   for (CeedInt i=0; i<n; i++)
1728     for (CeedInt j=0; j<n; j++)
1729       mat[j+n*i] = (i==j) ? 1 : 0;
1730 
1731   // Reduce to tridiagonal
1732   for (CeedInt i=0; i<n-1; i++) {
1733     // Calculate Householder vector, magnitude
1734     CeedScalar sigma = 0.0;
1735     v[i] = mat_T[i+n*(i+1)];
1736     for (CeedInt j=i+1; j<n-1; j++) {
1737       v[j] = mat_T[i+n*(j+1)];
1738       sigma += v[j] * v[j];
1739     }
1740     CeedScalar norm = sqrt(v[i]*v[i] + sigma); // norm of v[i:n-1]
1741     CeedScalar R_ii = -copysign(norm, v[i]);
1742     v[i] -= R_ii;
1743     // norm of v[i:m] after modification above and scaling below
1744     //   norm = sqrt(v[i]*v[i] + sigma) / v[i];
1745     //   tau = 2 / (norm*norm)
1746     tau[i] = i == n - 2 ? 2 : 2 * v[i]*v[i] / (v[i]*v[i] + sigma);
1747     for (CeedInt j=i+1; j<n-1; j++)
1748       v[j] /= v[i];
1749 
1750     // Update sub and super diagonal
1751     for (CeedInt j=i+2; j<n; j++) {
1752       mat_T[i+n*j] = 0; mat_T[j+n*i] = 0;
1753     }
1754     // Apply symmetric Householder reflector to lower right panel
1755     CeedHouseholderReflect(&mat_T[(i+1)+n*(i+1)], &v[i], tau[i],
1756                            n-(i+1), n-(i+1), n, 1);
1757     CeedHouseholderReflect(&mat_T[(i+1)+n*(i+1)], &v[i], tau[i],
1758                            n-(i+1), n-(i+1), 1, n);
1759 
1760     // Save v
1761     mat_T[i+n*(i+1)] = R_ii;
1762     mat_T[(i+1)+n*i] = R_ii;
1763     for (CeedInt j=i+1; j<n-1; j++) {
1764       mat_T[i+n*(j+1)] = v[j];
1765     }
1766   }
1767   // Backwards accumulation of Q
1768   for (CeedInt i=n-2; i>=0; i--) {
1769     if (tau[i] > 0.0) {
1770       v[i] = 1;
1771       for (CeedInt j=i+1; j<n-1; j++) {
1772         v[j] = mat_T[i+n*(j+1)];
1773         mat_T[i+n*(j+1)] = 0;
1774       }
1775       CeedHouseholderReflect(&mat[(i+1)+n*(i+1)], &v[i], tau[i],
1776                              n-(i+1), n-(i+1), n, 1);
1777     }
1778   }
1779 
1780   // Reduce sub and super diagonal
1781   CeedInt p = 0, q = 0, itr = 0, max_itr = n*n*n*n;
1782   CeedScalar tol = CEED_EPSILON;
1783 
1784   while (itr < max_itr) {
1785     // Update p, q, size of reduced portions of diagonal
1786     p = 0; q = 0;
1787     for (CeedInt i=n-2; i>=0; i--) {
1788       if (fabs(mat_T[i+n*(i+1)]) < tol)
1789         q += 1;
1790       else
1791         break;
1792     }
1793     for (CeedInt i=0; i<n-q-1; i++) {
1794       if (fabs(mat_T[i+n*(i+1)]) < tol)
1795         p += 1;
1796       else
1797         break;
1798     }
1799     if (q == n-1) break; // Finished reducing
1800 
1801     // Reduce tridiagonal portion
1802     CeedScalar t_nn = mat_T[(n-1-q)+n*(n-1-q)],
1803                t_nnm1 = mat_T[(n-2-q)+n*(n-1-q)];
1804     CeedScalar d = (mat_T[(n-2-q)+n*(n-2-q)] - t_nn)/2;
1805     CeedScalar mu = t_nn - t_nnm1*t_nnm1 /
1806                     (d + copysign(sqrt(d*d + t_nnm1*t_nnm1), d));
1807     CeedScalar x = mat_T[p+n*p] - mu;
1808     CeedScalar z = mat_T[p+n*(p+1)];
1809     for (CeedInt k=p; k<n-q-1; k++) {
1810       // Compute Givens rotation
1811       CeedScalar c = 1, s = 0;
1812       if (fabs(z) > tol) {
1813         if (fabs(z) > fabs(x)) {
1814           CeedScalar tau = -x/z;
1815           s = 1/sqrt(1+tau*tau), c = s*tau;
1816         } else {
1817           CeedScalar tau = -z/x;
1818           c = 1/sqrt(1+tau*tau), s = c*tau;
1819         }
1820       }
1821 
1822       // Apply Givens rotation to T
1823       CeedGivensRotation(mat_T, c, s, CEED_NOTRANSPOSE, k, k+1, n, n);
1824       CeedGivensRotation(mat_T, c, s, CEED_TRANSPOSE, k, k+1, n, n);
1825 
1826       // Apply Givens rotation to Q
1827       CeedGivensRotation(mat, c, s, CEED_NOTRANSPOSE, k, k+1, n, n);
1828 
1829       // Update x, z
1830       if (k < n-q-2) {
1831         x = mat_T[k+n*(k+1)];
1832         z = mat_T[k+n*(k+2)];
1833       }
1834     }
1835     itr++;
1836   }
1837 
1838   // Save eigenvalues
1839   for (CeedInt i=0; i<n; i++)
1840     lambda[i] = mat_T[i+n*i];
1841 
1842   // Check convergence
1843   if (itr == max_itr && q < n-1)
1844     // LCOV_EXCL_START
1845     return CeedError(ceed, CEED_ERROR_MINOR,
1846                      "Symmetric QR failed to converge");
1847   // LCOV_EXCL_STOP
1848   return CEED_ERROR_SUCCESS;
1849 }
1850 CeedPragmaOptimizeOn
1851 
1852 /**
1853   @brief Return Simultaneous Diagonalization of two matrices. This solves the
1854            generalized eigenvalue problem A x = lambda B x, where A and B
1855            are symmetric and B is positive definite. We generate the matrix X
1856            and vector Lambda such that X^T A X = Lambda and X^T B X = I. This
1857            is equivalent to the LAPACK routine 'sygv' with TYPE = 1.
1858 
1859   @param ceed         A Ceed context for error handling
1860   @param[in] mat_A    Row-major matrix to be factorized with eigenvalues
1861   @param[in] mat_B    Row-major matrix to be factorized to identity
1862   @param[out] mat_X   Row-major orthogonal matrix
1863   @param[out] lambda  Vector of length n of generalized eigenvalues
1864   @param n            Number of rows/columns
1865 
1866   @return An error code: 0 - success, otherwise - failure
1867 
1868   @ref Utility
1869 **/
1870 CeedPragmaOptimizeOff
1871 int CeedSimultaneousDiagonalization(Ceed ceed, CeedScalar *mat_A,
1872                                     CeedScalar *mat_B, CeedScalar *mat_X,
1873                                     CeedScalar *lambda, CeedInt n) {
1874   int ierr;
1875   CeedScalar *mat_C, *mat_G, *vec_D;
1876   ierr = CeedCalloc(n*n, &mat_C); CeedChk(ierr);
1877   ierr = CeedCalloc(n*n, &mat_G); CeedChk(ierr);
1878   ierr = CeedCalloc(n, &vec_D); CeedChk(ierr);
1879 
1880   // Compute B = G D G^T
1881   memcpy(mat_G, mat_B, n*n*sizeof(mat_B[0]));
1882   ierr = CeedSymmetricSchurDecomposition(ceed, mat_G, vec_D, n); CeedChk(ierr);
1883 
1884   // Sort eigenvalues
1885   for (CeedInt i=n-1; i>=0; i--)
1886     for (CeedInt j=0; j<i; j++) {
1887       if (fabs(vec_D[j]) > fabs(vec_D[j+1])) {
1888         CeedScalar temp;
1889         temp = vec_D[j]; vec_D[j] = vec_D[j+1]; vec_D[j+1] = temp;
1890         for (CeedInt k=0; k<n; k++) {
1891           temp = mat_G[k*n+j]; mat_G[k*n+j] = mat_G[k*n+j+1]; mat_G[k*n+j+1] = temp;
1892         }
1893       }
1894     }
1895 
1896   // Compute C = (G D^1/2)^-1 A (G D^1/2)^-T
1897   //           = D^-1/2 G^T A G D^-1/2
1898   // -- D = D^-1/2
1899   for (CeedInt i=0; i<n; i++)
1900     vec_D[i] = 1./sqrt(vec_D[i]);
1901   // -- G = G D^-1/2
1902   // -- C = D^-1/2 G^T
1903   for (CeedInt i=0; i<n; i++)
1904     for (CeedInt j=0; j<n; j++) {
1905       mat_G[i*n+j] *= vec_D[j];
1906       mat_C[j*n+i]  = mat_G[i*n+j];
1907     }
1908   // -- X = (D^-1/2 G^T) A
1909   ierr = CeedMatrixMatrixMultiply(ceed, (const CeedScalar *)mat_C,
1910                                   (const CeedScalar *)mat_A, mat_X, n, n, n);
1911   CeedChk(ierr);
1912   // -- C = (D^-1/2 G^T A) (G D^-1/2)
1913   ierr = CeedMatrixMatrixMultiply(ceed, (const CeedScalar *)mat_X,
1914                                   (const CeedScalar *)mat_G, mat_C, n, n, n);
1915   CeedChk(ierr);
1916 
1917   // Compute Q^T C Q = lambda
1918   ierr = CeedSymmetricSchurDecomposition(ceed, mat_C, lambda, n); CeedChk(ierr);
1919 
1920   // Sort eigenvalues
1921   for (CeedInt i=n-1; i>=0; i--)
1922     for (CeedInt j=0; j<i; j++) {
1923       if (fabs(lambda[j]) > fabs(lambda[j+1])) {
1924         CeedScalar temp;
1925         temp = lambda[j]; lambda[j] = lambda[j+1]; lambda[j+1] = temp;
1926         for (CeedInt k=0; k<n; k++) {
1927           temp = mat_C[k*n+j]; mat_C[k*n+j] = mat_C[k*n+j+1]; mat_C[k*n+j+1] = temp;
1928         }
1929       }
1930     }
1931 
1932   // Set X = (G D^1/2)^-T Q
1933   //       = G D^-1/2 Q
1934   ierr = CeedMatrixMatrixMultiply(ceed, (const CeedScalar *)mat_G,
1935                                   (const CeedScalar *)mat_C, mat_X, n, n, n);
1936   CeedChk(ierr);
1937 
1938   // Cleanup
1939   ierr = CeedFree(&mat_C); CeedChk(ierr);
1940   ierr = CeedFree(&mat_G); CeedChk(ierr);
1941   ierr = CeedFree(&vec_D); CeedChk(ierr);
1942   return CEED_ERROR_SUCCESS;
1943 }
1944 CeedPragmaOptimizeOn
1945 
1946 /// @}
1947