xref: /libCEED/interface/ceed-qfunction.c (revision 6e15d496119073f7bc35f61df7ac100e9376600e)
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/jit-tools.h>
11 #include <ceed-impl.h>
12 #include <limits.h>
13 #include <stdbool.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 
18 /// @file
19 /// Implementation of public CeedQFunction interfaces
20 
21 /// @cond DOXYGEN_SKIP
22 static struct CeedQFunction_private ceed_qfunction_none;
23 /// @endcond
24 
25 /// @addtogroup CeedQFunctionUser
26 /// @{
27 
28 // Indicate that no QFunction is provided by the user
29 const CeedQFunction CEED_QFUNCTION_NONE = &ceed_qfunction_none;
30 
31 /// @}
32 
33 /// @cond DOXYGEN_SKIP
34 static struct {
35   char name[CEED_MAX_RESOURCE_LEN];
36   char source[CEED_MAX_RESOURCE_LEN];
37   CeedInt vec_length;
38   CeedQFunctionUser f;
39   int (*init)(Ceed ceed, const char *name, CeedQFunction qf);
40 } gallery_qfunctions[1024];
41 static size_t num_qfunctions;
42 /// @endcond
43 
44 /// ----------------------------------------------------------------------------
45 /// CeedQFunction Library Internal Functions
46 /// ----------------------------------------------------------------------------
47 /// @addtogroup CeedQFunctionDeveloper
48 /// @{
49 
50 /**
51   @brief Register a gallery QFunction
52 
53   @param name        Name for this backend to respond to
54   @param source      Absolute path to source of QFunction,
55                        "\path\CEED_DIR\gallery\folder\file.h:function_name"
56   @param vec_length  Vector length.  Caller must ensure that number of quadrature
57                        points is a multiple of vec_length.
58   @param f           Function pointer to evaluate action at quadrature points.
59                        See \ref CeedQFunctionUser.
60   @param init        Initialization function called by CeedQFunctionInit() when the
61                        QFunction is selected.
62 
63   @return An error code: 0 - success, otherwise - failure
64 
65   @ref Developer
66 **/
67 int CeedQFunctionRegister(const char *name, const char *source,
68                           CeedInt vec_length, CeedQFunctionUser f,
69                           int (*init)(Ceed, const char *, CeedQFunction)) {
70   if (num_qfunctions >= sizeof(gallery_qfunctions) / sizeof(
71         gallery_qfunctions[0]))
72     // LCOV_EXCL_START
73     return CeedError(NULL, CEED_ERROR_MAJOR, "Too many gallery QFunctions");
74   // LCOV_EXCL_STOP
75 
76   CeedDebugEnv("Gallery Register: %s", name);
77 
78   strncpy(gallery_qfunctions[num_qfunctions].name, name, CEED_MAX_RESOURCE_LEN);
79   gallery_qfunctions[num_qfunctions].name[CEED_MAX_RESOURCE_LEN-1] = 0;
80   strncpy(gallery_qfunctions[num_qfunctions].source, source,
81           CEED_MAX_RESOURCE_LEN);
82   gallery_qfunctions[num_qfunctions].source[CEED_MAX_RESOURCE_LEN-1] = 0;
83   gallery_qfunctions[num_qfunctions].vec_length = vec_length;
84   gallery_qfunctions[num_qfunctions].f = f;
85   gallery_qfunctions[num_qfunctions].init = init;
86   num_qfunctions++;
87   return CEED_ERROR_SUCCESS;
88 }
89 
90 /**
91   @brief Set a CeedQFunction field, used by CeedQFunctionAddInput/Output
92 
93   @param f           CeedQFunctionField
94   @param field_name  Name of QFunction field
95   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
96                        (num_comp * 1) for @ref CEED_EVAL_NONE, @ref CEED_EVAL_INTERP, and @ref CEED_EVAL_WEIGHT
97   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
98                        \ref CEED_EVAL_INTERP to use interpolated values,
99                        \ref CEED_EVAL_GRAD to use gradients,
100                        \ref CEED_EVAL_WEIGHT to use quadrature weights.
101 
102   @return An error code: 0 - success, otherwise - failure
103 
104   @ref Developer
105 **/
106 static int CeedQFunctionFieldSet(CeedQFunctionField *f, const char *field_name,
107                                  CeedInt size, CeedEvalMode eval_mode) {
108   int ierr;
109 
110   ierr = CeedCalloc(1, f); CeedChk(ierr);
111   ierr = CeedStringAllocCopy(field_name, (char **)&(*f)->field_name);
112   CeedChk(ierr);
113   (*f)->size = size;
114   (*f)->eval_mode = eval_mode;
115   return CEED_ERROR_SUCCESS;
116 }
117 
118 /**
119   @brief View a field of a CeedQFunction
120 
121   @param[in] field         QFunction field to view
122   @param[in] field_number  Number of field being viewed
123   @param[in] in            true for input field, false for output
124   @param[in] stream        Stream to view to, e.g., stdout
125 
126   @return An error code: 0 - success, otherwise - failure
127 
128   @ref Utility
129 **/
130 static int CeedQFunctionFieldView(CeedQFunctionField field,
131                                   CeedInt field_number,
132                                   bool in, FILE *stream) {
133   int ierr;
134   const char *inout = in ? "Input" : "Output";
135   char *field_name;
136   ierr = CeedQFunctionFieldGetName(field, &field_name); CeedChk(ierr);
137   CeedInt size;
138   ierr = CeedQFunctionFieldGetSize(field, &size); CeedChk(ierr);
139   CeedEvalMode eval_mode;
140   ierr = CeedQFunctionFieldGetEvalMode(field, &eval_mode); CeedChk(ierr);
141   fprintf(stream, "    %s Field [%d]:\n"
142           "      Name: \"%s\"\n"
143           "      Size: %d\n"
144           "      EvalMode: \"%s\"\n",
145           inout, field_number, field_name, size, CeedEvalModes[eval_mode]);
146   return CEED_ERROR_SUCCESS;
147 }
148 
149 /**
150   @brief Set flag to determine if Fortran interface is used
151 
152   @param qf      CeedQFunction
153   @param status  Boolean value to set as Fortran status
154 
155   @return An error code: 0 - success, otherwise - failure
156 
157   @ref Backend
158 **/
159 int CeedQFunctionSetFortranStatus(CeedQFunction qf, bool status) {
160   qf->is_fortran = status;
161   return CEED_ERROR_SUCCESS;
162 }
163 
164 /// @}
165 
166 /// ----------------------------------------------------------------------------
167 /// CeedQFunction Backend API
168 /// ----------------------------------------------------------------------------
169 /// @addtogroup CeedQFunctionBackend
170 /// @{
171 
172 /**
173   @brief Get the vector length of a CeedQFunction
174 
175   @param qf               CeedQFunction
176   @param[out] vec_length  Variable to store vector length
177 
178   @return An error code: 0 - success, otherwise - failure
179 
180   @ref Backend
181 **/
182 int CeedQFunctionGetVectorLength(CeedQFunction qf, CeedInt *vec_length) {
183   *vec_length = qf->vec_length;
184   return CEED_ERROR_SUCCESS;
185 }
186 
187 /**
188   @brief Get the number of inputs and outputs to a CeedQFunction
189 
190   @param qf               CeedQFunction
191   @param[out] num_input   Variable to store number of input fields
192   @param[out] num_output  Variable to store number of output fields
193 
194   @return An error code: 0 - success, otherwise - failure
195 
196   @ref Backend
197 **/
198 int CeedQFunctionGetNumArgs(CeedQFunction qf, CeedInt *num_input,
199                             CeedInt *num_output) {
200   if (num_input) *num_input = qf->num_input_fields;
201   if (num_output) *num_output = qf->num_output_fields;
202   return CEED_ERROR_SUCCESS;
203 }
204 
205 /**
206   @brief Get the name of the user function for a CeedQFunction
207 
208   @param qf                CeedQFunction
209   @param[out] kernel_name  Variable to store source path string
210 
211   @return An error code: 0 - success, otherwise - failure
212 
213   @ref Backend
214 **/
215 int CeedQFunctionGetKernelName(CeedQFunction qf, char **kernel_name) {
216   *kernel_name = (char *) qf->kernel_name;
217   return CEED_ERROR_SUCCESS;
218 }
219 
220 /**
221   @brief Get the source path string for a CeedQFunction
222 
223   @param qf                CeedQFunction
224   @param[out] source_path  Variable to store source path string
225 
226   @return An error code: 0 - success, otherwise - failure
227 
228   @ref Backend
229 **/
230 int CeedQFunctionGetSourcePath(CeedQFunction qf, char **source_path) {
231   *source_path = (char *) qf->source_path;
232   return CEED_ERROR_SUCCESS;
233 }
234 
235 /**
236   @brief Initalize and load QFunction source file into string buffer, including
237            full text of local files in place of `#include "local.h"`.
238            The `buffer` is set to `NULL` if there is no QFunction source file.
239          Note: Caller is responsible for freeing the string buffer with `CeedFree()`.
240 
241   @param qf                  CeedQFunction
242   @param[out] source_buffer  String buffer for source file contents
243 
244   @return An error code: 0 - success, otherwise - failure
245 
246   @ref Backend
247 **/
248 int CeedQFunctionLoadSourceToBuffer(CeedQFunction qf, char **source_buffer) {
249   int ierr;
250   char *source_path;
251 
252   ierr = CeedQFunctionGetSourcePath(qf, &source_path); CeedChk(ierr);
253   *source_buffer = NULL;
254   if (source_path) {
255     ierr = CeedLoadSourceToBuffer(qf->ceed, source_path, source_buffer);
256     CeedChk(ierr);
257   }
258 
259   return CEED_ERROR_SUCCESS;
260 }
261 
262 /**
263   @brief Get the User Function for a CeedQFunction
264 
265   @param qf      CeedQFunction
266   @param[out] f  Variable to store user function
267 
268   @return An error code: 0 - success, otherwise - failure
269 
270   @ref Backend
271 **/
272 int CeedQFunctionGetUserFunction(CeedQFunction qf, CeedQFunctionUser *f) {
273   *f = qf->function;
274   return CEED_ERROR_SUCCESS;
275 }
276 
277 /**
278   @brief Get global context for a CeedQFunction.
279            Note: For QFunctions from the Fortran interface, this
280              function will return the Fortran context
281              CeedQFunctionContext.
282 
283   @param qf        CeedQFunction
284   @param[out] ctx  Variable to store CeedQFunctionContext
285 
286   @return An error code: 0 - success, otherwise - failure
287 
288   @ref Backend
289 **/
290 int CeedQFunctionGetContext(CeedQFunction qf, CeedQFunctionContext *ctx) {
291   *ctx = qf->ctx;
292   return CEED_ERROR_SUCCESS;
293 }
294 
295 /**
296   @brief Get context data of a CeedQFunction
297 
298   @param qf         CeedQFunction
299   @param mem_type   Memory type on which to access the data. If the backend
300                       uses a different memory type, this will perform a copy.
301   @param[out] data  Data on memory type mem_type
302 
303   @return An error code: 0 - success, otherwise - failure
304 
305   @ref Backend
306 **/
307 int CeedQFunctionGetContextData(CeedQFunction qf, CeedMemType mem_type,
308                                 void *data) {
309   int ierr;
310   bool is_writable;
311   CeedQFunctionContext ctx;
312 
313   ierr = CeedQFunctionGetContext(qf, &ctx); CeedChk(ierr);
314   if (ctx) {
315     ierr = CeedQFunctionIsContextWritable(qf, &is_writable); CeedChk(ierr);
316     if (is_writable) {
317       ierr = CeedQFunctionContextGetData(ctx, mem_type, data); CeedChk(ierr);
318     } else {
319       ierr = CeedQFunctionContextGetDataRead(ctx, mem_type, data); CeedChk(ierr);
320     }
321   } else {
322     *(void **)data = NULL;
323   }
324   return CEED_ERROR_SUCCESS;
325 }
326 
327 /**
328   @brief Restore context data of a CeedQFunction
329 
330   @param qf    CeedQFunction
331   @param data  Data to restore
332 
333   @return An error code: 0 - success, otherwise - failure
334 
335   @ref Backend
336 **/
337 int CeedQFunctionRestoreContextData(CeedQFunction qf, void *data) {
338   int ierr;
339   bool is_writable;
340   CeedQFunctionContext ctx;
341 
342   ierr = CeedQFunctionGetContext(qf, &ctx); CeedChk(ierr);
343   if (ctx) {
344     ierr = CeedQFunctionIsContextWritable(qf, &is_writable); CeedChk(ierr);
345     if (is_writable) {
346       ierr = CeedQFunctionContextRestoreData(ctx, data); CeedChk(ierr);
347     } else {
348       ierr = CeedQFunctionContextRestoreDataRead(ctx, data); CeedChk(ierr);
349     }
350   }
351   return CEED_ERROR_SUCCESS;
352 }
353 
354 /**
355   @brief Get true user context for a CeedQFunction
356            Note: For all QFunctions this function will return the user
357              CeedQFunctionContext and not interface context
358              CeedQFunctionContext, if any such object exists.
359 
360   @param qf        CeedQFunction
361   @param[out] ctx  Variable to store CeedQFunctionContext
362 
363   @return An error code: 0 - success, otherwise - failure
364   @ref Backend
365 **/
366 int CeedQFunctionGetInnerContext(CeedQFunction qf, CeedQFunctionContext *ctx) {
367   int ierr;
368   if (qf->is_fortran) {
369     CeedFortranContext fortran_ctx = NULL;
370     ierr = CeedQFunctionContextGetData(qf->ctx, CEED_MEM_HOST, &fortran_ctx);
371     CeedChk(ierr);
372     *ctx = fortran_ctx->inner_ctx;
373     ierr = CeedQFunctionContextRestoreData(qf->ctx, (void *)&fortran_ctx);
374     CeedChk(ierr);
375   } else {
376     *ctx = qf->ctx;
377   }
378   return CEED_ERROR_SUCCESS;
379 }
380 
381 /**
382   @brief Get inner context data of a CeedQFunction
383 
384   @param qf         CeedQFunction
385   @param mem_type   Memory type on which to access the data. If the backend
386                       uses a different memory type, this will perform a copy.
387   @param[out] data  Data on memory type mem_type
388 
389   @return An error code: 0 - success, otherwise - failure
390 
391   @ref Backend
392 **/
393 int CeedQFunctionGetInnerContextData(CeedQFunction qf, CeedMemType mem_type,
394                                      void *data) {
395   int ierr;
396   bool is_writable;
397   CeedQFunctionContext ctx;
398 
399   ierr = CeedQFunctionGetInnerContext(qf, &ctx); CeedChk(ierr);
400   if (ctx) {
401     ierr = CeedQFunctionIsContextWritable(qf, &is_writable); CeedChk(ierr);
402     if (is_writable) {
403       ierr = CeedQFunctionContextGetData(ctx, mem_type, data); CeedChk(ierr);
404     } else {
405       ierr = CeedQFunctionContextGetDataRead(ctx, mem_type, data); CeedChk(ierr);
406     }
407   } else {
408     *(void **)data = NULL;
409   }
410   return CEED_ERROR_SUCCESS;
411 }
412 
413 /**
414   @brief Restore inner context data of a CeedQFunction
415 
416   @param qf    CeedQFunction
417   @param data  Data to restore
418 
419   @return An error code: 0 - success, otherwise - failure
420 
421   @ref Backend
422 **/
423 int CeedQFunctionRestoreInnerContextData(CeedQFunction qf, void *data) {
424   int ierr;
425   bool is_writable;
426   CeedQFunctionContext ctx;
427 
428   ierr = CeedQFunctionGetInnerContext(qf, &ctx); CeedChk(ierr);
429   if (ctx) {
430     ierr = CeedQFunctionIsContextWritable(qf, &is_writable); CeedChk(ierr);
431     if (is_writable) {
432       ierr = CeedQFunctionContextRestoreData(ctx, data); CeedChk(ierr);
433     } else {
434       ierr = CeedQFunctionContextRestoreDataRead(ctx, data); CeedChk(ierr);
435     }
436   }
437   return CEED_ERROR_SUCCESS;
438 }
439 
440 /**
441   @brief Determine if QFunction is identity
442 
443   @param qf                CeedQFunction
444   @param[out] is_identity  Variable to store identity status
445 
446   @return An error code: 0 - success, otherwise - failure
447 
448   @ref Backend
449 **/
450 int CeedQFunctionIsIdentity(CeedQFunction qf, bool *is_identity) {
451   *is_identity = qf->is_identity;
452   return CEED_ERROR_SUCCESS;
453 }
454 
455 /**
456   @brief Determine if QFunctionContext is writable
457 
458   @param qf                CeedQFunction
459   @param[out] is_writable  Variable to store context writeable staus
460 
461   @return An error code: 0 - success, otherwise - failure
462 
463   @ref Backend
464 **/
465 int CeedQFunctionIsContextWritable(CeedQFunction qf, bool *is_writable) {
466   *is_writable = qf->is_context_writable;
467   return CEED_ERROR_SUCCESS;
468 }
469 
470 /**
471   @brief Get backend data of a CeedQFunction
472 
473   @param qf         CeedQFunction
474   @param[out] data  Variable to store data
475 
476   @return An error code: 0 - success, otherwise - failure
477 
478   @ref Backend
479 **/
480 int CeedQFunctionGetData(CeedQFunction qf, void *data) {
481   *(void **)data = qf->data;
482   return CEED_ERROR_SUCCESS;
483 }
484 
485 /**
486   @brief Set backend data of a CeedQFunction
487 
488   @param[out] qf  CeedQFunction
489   @param data     Data to set
490 
491   @return An error code: 0 - success, otherwise - failure
492 
493   @ref Backend
494 **/
495 int CeedQFunctionSetData(CeedQFunction qf, void *data) {
496   qf->data = data;
497   return CEED_ERROR_SUCCESS;
498 }
499 
500 /**
501   @brief Increment the reference counter for a CeedQFunction
502 
503   @param qf  CeedQFunction to increment the reference counter
504 
505   @return An error code: 0 - success, otherwise - failure
506 
507   @ref Backend
508 **/
509 int CeedQFunctionReference(CeedQFunction qf) {
510   qf->ref_count++;
511   return CEED_ERROR_SUCCESS;
512 }
513 
514 /**
515   @brief Estimate number of FLOPs per quadrature required to apply QFunction
516 
517   @param qf    QFunction to estimate FLOPs for
518   @param flops Address of variable to hold FLOPs estimate
519 
520   @ref Backend
521 **/
522 int CeedQFunctionGetFlopsEstimate(CeedQFunction qf, CeedInt *flops) {
523   if (qf->user_flop_estimate == -1)
524     // LCOV_EXCL_START
525     return CeedError(qf->ceed, CEED_ERROR_INCOMPLETE,
526                      "Must set FLOPs estimate with CeedQFunctionSetUserFlopsEstimate");
527   // LCOV_EXCL_STOP
528   *flops = qf->user_flop_estimate;
529   return CEED_ERROR_SUCCESS;
530 }
531 
532 /// @}
533 
534 /// ----------------------------------------------------------------------------
535 /// CeedQFunction Public API
536 /// ----------------------------------------------------------------------------
537 /// @addtogroup CeedQFunctionUser
538 /// @{
539 
540 /**
541   @brief Create a CeedQFunction for evaluating interior (volumetric) terms.
542 
543   @param ceed        A Ceed object where the CeedQFunction will be created
544   @param vec_length  Vector length. Caller must ensure that number of quadrature
545                        points is a multiple of vec_length.
546   @param f           Function pointer to evaluate action at quadrature points.
547                        See \ref CeedQFunctionUser.
548   @param source      Absolute path to source of QFunction,
549                        "\abs_path\file.h:function_name".
550                        For support across all backends, this source must only
551                        contain constructs supported by C99, C++11, and CUDA.
552   @param[out] qf     Address of the variable where the newly created
553                        CeedQFunction will be stored
554 
555   @return An error code: 0 - success, otherwise - failure
556 
557   See \ref CeedQFunctionUser for details on the call-back function @a f's
558     arguments.
559 
560   @ref User
561 **/
562 int CeedQFunctionCreateInterior(Ceed ceed, CeedInt vec_length,
563                                 CeedQFunctionUser f,
564                                 const char *source, CeedQFunction *qf) {
565   int ierr;
566   char *source_copy, *kernel_name_copy;
567 
568   if (!ceed->QFunctionCreate) {
569     Ceed delegate;
570     ierr = CeedGetObjectDelegate(ceed, &delegate, "QFunction"); CeedChk(ierr);
571 
572     if (!delegate)
573       // LCOV_EXCL_START
574       return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
575                        "Backend does not support QFunctionCreate");
576     // LCOV_EXCL_STOP
577 
578     ierr = CeedQFunctionCreateInterior(delegate, vec_length, f, source, qf);
579     CeedChk(ierr);
580     return CEED_ERROR_SUCCESS;
581   }
582 
583   if (strlen(source) && !strrchr(source, ':'))
584     // LCOV_EXCL_START
585     return CeedError(ceed, CEED_ERROR_INCOMPLETE,
586                      "Provided path to source does not include function name. "
587                      "Provided: \"%s\"\nRequired: \"\\abs_path\\file.h:function_name\"",
588                      source);
589   // LCOV_EXCL_STOP
590 
591   ierr = CeedCalloc(1, qf); CeedChk(ierr);
592   (*qf)->ceed = ceed;
593   ierr = CeedReference(ceed); CeedChk(ierr);
594   (*qf)->ref_count = 1;
595   (*qf)->vec_length = vec_length;
596   (*qf)->is_identity = false;
597   (*qf)->is_context_writable = true;
598   (*qf)->function = f;
599   (*qf)->user_flop_estimate = -1;
600   if (strlen(source)) {
601     const char *kernel_name = strrchr(source, ':') + 1;
602     size_t kernel_name_len = strlen(kernel_name);
603     ierr = CeedCalloc(kernel_name_len + 1, &kernel_name_copy); CeedChk(ierr);
604     strncpy(kernel_name_copy, kernel_name, kernel_name_len);
605     (*qf)->kernel_name = kernel_name_copy;
606 
607     size_t source_len = strlen(source) - kernel_name_len - 1;
608     ierr = CeedCalloc(source_len + 1, &source_copy); CeedChk(ierr);
609     strncpy(source_copy, source, source_len);
610     (*qf)->source_path = source_copy;
611   }
612   ierr = CeedCalloc(CEED_FIELD_MAX, &(*qf)->input_fields); CeedChk(ierr);
613   ierr = CeedCalloc(CEED_FIELD_MAX, &(*qf)->output_fields); CeedChk(ierr);
614   ierr = ceed->QFunctionCreate(*qf); CeedChk(ierr);
615   return CEED_ERROR_SUCCESS;
616 }
617 
618 /**
619   @brief Create a CeedQFunction for evaluating interior (volumetric) terms by name.
620 
621   @param ceed     A Ceed object where the CeedQFunction will be created
622   @param name     Name of QFunction to use from gallery
623   @param[out] qf  Address of the variable where the newly created
624                     CeedQFunction will be stored
625 
626   @return An error code: 0 - success, otherwise - failure
627 
628   @ref User
629 **/
630 int CeedQFunctionCreateInteriorByName(Ceed ceed,  const char *name,
631                                       CeedQFunction *qf) {
632   int ierr;
633   size_t match_len = 0, match_index = UINT_MAX;
634 
635   ierr = CeedQFunctionRegisterAll(); CeedChk(ierr);
636   // Find matching backend
637   if (!name) return CeedError(ceed, CEED_ERROR_INCOMPLETE,
638                                 "No QFunction name provided");
639   for (size_t i=0; i<num_qfunctions; i++) {
640     size_t n;
641     const char *curr_name = gallery_qfunctions[i].name;
642     for (n = 0; curr_name[n] && curr_name[n] == name[n]; n++) {}
643     if (n > match_len) {
644       match_len = n;
645       match_index = i;
646     }
647   }
648   if (!match_len)
649     // LCOV_EXCL_START
650     return CeedError(ceed, CEED_ERROR_UNSUPPORTED, "No suitable gallery QFunction");
651   // LCOV_EXCL_STOP
652 
653   // Create QFunction
654   ierr = CeedQFunctionCreateInterior(ceed,
655                                      gallery_qfunctions[match_index].vec_length,
656                                      gallery_qfunctions[match_index].f,
657                                      gallery_qfunctions[match_index].source, qf);
658   CeedChk(ierr);
659 
660   // QFunction specific setup
661   ierr = gallery_qfunctions[match_index].init(ceed, name, *qf); CeedChk(ierr);
662 
663   // Copy name
664   ierr = CeedStringAllocCopy(name, (char **)&(*qf)->gallery_name); CeedChk(ierr);
665   (*qf)->is_gallery = true;
666   return CEED_ERROR_SUCCESS;
667 }
668 
669 /**
670   @brief Create an identity CeedQFunction. Inputs are written into outputs in
671            the order given. This is useful for CeedOperators that can be
672            represented with only the action of a CeedRestriction and CeedBasis,
673            such as restriction and prolongation operators for p-multigrid.
674            Backends may optimize CeedOperators with this CeedQFunction to avoid
675            the copy of input data to output fields by using the same memory
676            location for both.
677 
678   @param ceed          A Ceed object where the CeedQFunction will be created
679   @param[in] size      Size of the QFunction fields
680   @param[in] in_mode   CeedEvalMode for input to CeedQFunction
681   @param[in] out_mode  CeedEvalMode for output to CeedQFunction
682   @param[out] qf       Address of the variable where the newly created
683                          CeedQFunction will be stored
684 
685   @return An error code: 0 - success, otherwise - failure
686 
687   @ref User
688 **/
689 int CeedQFunctionCreateIdentity(Ceed ceed, CeedInt size, CeedEvalMode in_mode,
690                                 CeedEvalMode out_mode, CeedQFunction *qf) {
691   int ierr;
692 
693   ierr = CeedQFunctionCreateInteriorByName(ceed, "Identity", qf); CeedChk(ierr);
694   ierr = CeedQFunctionAddInput(*qf, "input", size, in_mode); CeedChk(ierr);
695   ierr = CeedQFunctionAddOutput(*qf, "output", size, out_mode); CeedChk(ierr);
696 
697   (*qf)->is_identity = true;
698 
699   CeedQFunctionContext ctx;
700   CeedContextFieldLabel size_label;
701   ierr = CeedQFunctionGetContext(*qf, &ctx); CeedChk(ierr);
702   ierr = CeedQFunctionContextGetFieldLabel(ctx, "size", &size_label);
703   CeedChk(ierr);
704   ierr = CeedQFunctionContextSetInt32(ctx, size_label, &size); CeedChk(ierr);
705 
706   return CEED_ERROR_SUCCESS;
707 }
708 
709 /**
710   @brief Copy the pointer to a CeedQFunction. Both pointers should
711            be destroyed with `CeedQFunctionDestroy()`;
712            Note: If `*qf_copy` is non-NULL, then it is assumed that
713            `*qf_copy` is a pointer to a CeedQFunction. This
714            CeedQFunction will be destroyed if `*qf_copy` is the only
715            reference to this CeedQFunction.
716 
717   @param qf            CeedQFunction to copy reference to
718   @param[out] qf_copy  Variable to store copied reference
719 
720   @return An error code: 0 - success, otherwise - failure
721 
722   @ref User
723 **/
724 int CeedQFunctionReferenceCopy(CeedQFunction qf, CeedQFunction *qf_copy) {
725   int ierr;
726 
727   ierr = CeedQFunctionReference(qf); CeedChk(ierr);
728   ierr = CeedQFunctionDestroy(qf_copy); CeedChk(ierr);
729   *qf_copy = qf;
730   return CEED_ERROR_SUCCESS;
731 }
732 
733 /**
734   @brief Add a CeedQFunction input
735 
736   @param qf          CeedQFunction
737   @param field_name  Name of QFunction field
738   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
739                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
740   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
741                        \ref CEED_EVAL_INTERP to use interpolated values,
742                        \ref CEED_EVAL_GRAD to use gradients.
743 
744   @return An error code: 0 - success, otherwise - failure
745 
746   @ref User
747 **/
748 int CeedQFunctionAddInput(CeedQFunction qf, const char *field_name,
749                           CeedInt size,
750                           CeedEvalMode eval_mode) {
751   if (qf->is_immutable)
752     // LCOV_EXCL_START
753     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
754                      "QFunction cannot be changed after set as immutable");
755   // LCOV_EXCL_STOP
756   if ((eval_mode == CEED_EVAL_WEIGHT) && (size != 1))
757     // LCOV_EXCL_START
758     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
759                      "CEED_EVAL_WEIGHT should have size 1");
760   // LCOV_EXCL_STOP
761   int ierr = CeedQFunctionFieldSet(&qf->input_fields[qf->num_input_fields],
762                                    field_name, size, eval_mode);
763   CeedChk(ierr);
764   qf->num_input_fields++;
765   return CEED_ERROR_SUCCESS;
766 }
767 
768 /**
769   @brief Add a CeedQFunction output
770 
771   @param qf          CeedQFunction
772   @param field_name  Name of QFunction field
773   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
774                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
775   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
776                        \ref CEED_EVAL_INTERP to use interpolated values,
777                        \ref CEED_EVAL_GRAD to use gradients.
778 
779   @return An error code: 0 - success, otherwise - failure
780 
781   @ref User
782 **/
783 int CeedQFunctionAddOutput(CeedQFunction qf, const char *field_name,
784                            CeedInt size, CeedEvalMode eval_mode) {
785   if (qf->is_immutable)
786     // LCOV_EXCL_START
787     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
788                      "QFunction cannot be changed after set as immutable");
789   // LCOV_EXCL_STOP
790   if (eval_mode == CEED_EVAL_WEIGHT)
791     // LCOV_EXCL_START
792     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
793                      "Cannot create QFunction output with "
794                      "CEED_EVAL_WEIGHT");
795   // LCOV_EXCL_STOP
796   int ierr = CeedQFunctionFieldSet(&qf->output_fields[qf->num_output_fields],
797                                    field_name, size, eval_mode);
798   CeedChk(ierr);
799   qf->num_output_fields++;
800   return CEED_ERROR_SUCCESS;
801 }
802 
803 /**
804   @brief Get the CeedQFunctionFields of a CeedQFunction
805 
806   Note: Calling this function asserts that setup is complete
807           and sets the CeedQFunction as immutable.
808 
809   @param qf                      CeedQFunction
810   @param[out] num_input_fields   Variable to store number of input fields
811   @param[out] input_fields       Variable to store input fields
812   @param[out] num_output_fields  Variable to store number of output fields
813   @param[out] output_fields      Variable to store output fields
814 
815   @return An error code: 0 - success, otherwise - failure
816 
817   @ref Advanced
818 **/
819 int CeedQFunctionGetFields(CeedQFunction qf, CeedInt *num_input_fields,
820                            CeedQFunctionField **input_fields,
821                            CeedInt *num_output_fields,
822                            CeedQFunctionField **output_fields) {
823   qf->is_immutable = true;
824   if (num_input_fields) *num_input_fields = qf->num_input_fields;
825   if (input_fields) *input_fields = qf->input_fields;
826   if (num_output_fields) *num_output_fields = qf->num_output_fields;
827   if (output_fields) *output_fields = qf->output_fields;
828   return CEED_ERROR_SUCCESS;
829 }
830 
831 /**
832   @brief Get the name of a CeedQFunctionField
833 
834   @param qf_field         CeedQFunctionField
835   @param[out] field_name  Variable to store the field name
836 
837   @return An error code: 0 - success, otherwise - failure
838 
839   @ref Advanced
840 **/
841 int CeedQFunctionFieldGetName(CeedQFunctionField qf_field, char **field_name) {
842   *field_name = (char *)qf_field->field_name;
843   return CEED_ERROR_SUCCESS;
844 }
845 
846 /**
847   @brief Get the number of components of a CeedQFunctionField
848 
849   @param qf_field   CeedQFunctionField
850   @param[out] size  Variable to store the size of the field
851 
852   @return An error code: 0 - success, otherwise - failure
853 
854   @ref Advanced
855 **/
856 int CeedQFunctionFieldGetSize(CeedQFunctionField qf_field, CeedInt *size) {
857   *size = qf_field->size;
858   return CEED_ERROR_SUCCESS;
859 }
860 
861 /**
862   @brief Get the CeedEvalMode of a CeedQFunctionField
863 
864   @param qf_field        CeedQFunctionField
865   @param[out] eval_mode  Variable to store the field evaluation mode
866 
867   @return An error code: 0 - success, otherwise - failure
868 
869   @ref Advanced
870 **/
871 int CeedQFunctionFieldGetEvalMode(CeedQFunctionField qf_field,
872                                   CeedEvalMode *eval_mode) {
873   *eval_mode = qf_field->eval_mode;
874   return CEED_ERROR_SUCCESS;
875 }
876 
877 /**
878   @brief Set global context for a CeedQFunction
879 
880   @param qf   CeedQFunction
881   @param ctx  Context data to set
882 
883   @return An error code: 0 - success, otherwise - failure
884 
885   @ref User
886 **/
887 int CeedQFunctionSetContext(CeedQFunction qf, CeedQFunctionContext ctx) {
888   int ierr;
889   ierr = CeedQFunctionContextDestroy(&qf->ctx); CeedChk(ierr);
890   qf->ctx = ctx;
891   ierr = CeedQFunctionContextReference(ctx); CeedChk(ierr);
892   return CEED_ERROR_SUCCESS;
893 }
894 
895 /**
896   @brief Set writability of CeedQFunctionContext when calling the `CeedQFunctionUser`.
897            The default value is 'is_writable == true'.
898 
899            Setting `is_writable == true` indicates the `CeedQFunctionUser` writes
900            into the CeedQFunctionContextData and requires memory syncronization
901            after calling `CeedQFunctionApply()`.
902 
903            Setting 'is_writable == false' asserts that `CeedQFunctionUser` does not
904            modify the CeedQFunctionContextData. Violating this assertion may lead
905            to inconsistent data.
906 
907            Setting `is_writable == false` may offer a performance improvement on GPU backends.
908 
909   @param qf           CeedQFunction
910   @param is_writable  Writability status
911 
912   @return An error code: 0 - success, otherwise - failure
913 
914   @ref User
915 **/
916 int CeedQFunctionSetContextWritable(CeedQFunction qf, bool is_writable) {
917   qf->is_context_writable = is_writable;
918   return CEED_ERROR_SUCCESS;
919 }
920 
921 /**
922   @brief Set estimated number of FLOPs per quadrature required to apply QFunction
923 
924   @param qf    QFunction to estimate FLOPs for
925   @param flops FLOPs per quadrature point estimate
926 
927   @ref Backend
928 **/
929 int CeedQFunctionSetUserFlopsEstimate(CeedQFunction qf, CeedInt flops) {
930   if (flops < 0)
931     // LCOV_EXCL_START
932     return CeedError(qf->ceed, CEED_ERROR_INCOMPATIBLE,
933                      "Must set non-negative FLOPs estimate");
934   // LCOV_EXCL_STOP
935   qf->user_flop_estimate = flops;
936   return CEED_ERROR_SUCCESS;
937 }
938 
939 /**
940   @brief View a CeedQFunction
941 
942   @param[in] qf      CeedQFunction to view
943   @param[in] stream  Stream to write; typically stdout/stderr or a file
944 
945   @return Error code: 0 - success, otherwise - failure
946 
947   @ref User
948 **/
949 int CeedQFunctionView(CeedQFunction qf, FILE *stream) {
950   int ierr;
951 
952   fprintf(stream, "%sCeedQFunction %s\n",
953           qf->is_gallery ? "Gallery " : "User ",
954           qf->is_gallery ? qf->gallery_name : qf->kernel_name);
955 
956   fprintf(stream, "  %d Input Field%s:\n", qf->num_input_fields,
957           qf->num_input_fields>1 ? "s" : "");
958   for (CeedInt i=0; i<qf->num_input_fields; i++) {
959     ierr = CeedQFunctionFieldView(qf->input_fields[i], i, 1, stream);
960     CeedChk(ierr);
961   }
962 
963   fprintf(stream, "  %d Output Field%s:\n", qf->num_output_fields,
964           qf->num_output_fields>1 ? "s" : "");
965   for (CeedInt i=0; i<qf->num_output_fields; i++) {
966     ierr = CeedQFunctionFieldView(qf->output_fields[i], i, 0, stream);
967     CeedChk(ierr);
968   }
969   return CEED_ERROR_SUCCESS;
970 }
971 
972 /**
973   @brief Get the Ceed associated with a CeedQFunction
974 
975   @param qf              CeedQFunction
976   @param[out] ceed       Variable to store Ceed
977 
978   @return An error code: 0 - success, otherwise - failure
979 
980   @ref Advanced
981 **/
982 int CeedQFunctionGetCeed(CeedQFunction qf, Ceed *ceed) {
983   *ceed = qf->ceed;
984   return CEED_ERROR_SUCCESS;
985 }
986 
987 /**
988   @brief Apply the action of a CeedQFunction
989 
990   Note: Calling this function asserts that setup is complete
991           and sets the CeedQFunction as immutable.
992 
993   @param qf      CeedQFunction
994   @param Q       Number of quadrature points
995   @param[in] u   Array of input CeedVectors
996   @param[out] v  Array of output CeedVectors
997 
998   @return An error code: 0 - success, otherwise - failure
999 
1000   @ref User
1001 **/
1002 int CeedQFunctionApply(CeedQFunction qf, CeedInt Q,
1003                        CeedVector *u, CeedVector *v) {
1004   int ierr;
1005   if (!qf->Apply)
1006     // LCOV_EXCL_START
1007     return CeedError(qf->ceed, CEED_ERROR_UNSUPPORTED,
1008                      "Backend does not support QFunctionApply");
1009   // LCOV_EXCL_STOP
1010   if (Q % qf->vec_length)
1011     // LCOV_EXCL_START
1012     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
1013                      "Number of quadrature points %d must be a "
1014                      "multiple of %d", Q, qf->vec_length);
1015   // LCOV_EXCL_STOP
1016   qf->is_immutable = true;
1017   ierr = qf->Apply(qf, Q, u, v); CeedChk(ierr);
1018   return CEED_ERROR_SUCCESS;
1019 }
1020 
1021 /**
1022   @brief Destroy a CeedQFunction
1023 
1024   @param qf  CeedQFunction to destroy
1025 
1026   @return An error code: 0 - success, otherwise - failure
1027 
1028   @ref User
1029 **/
1030 int CeedQFunctionDestroy(CeedQFunction *qf) {
1031   int ierr;
1032 
1033   if (!*qf || --(*qf)->ref_count > 0) return CEED_ERROR_SUCCESS;
1034   // Backend destroy
1035   if ((*qf)->Destroy) {
1036     ierr = (*qf)->Destroy(*qf); CeedChk(ierr);
1037   }
1038   // Free fields
1039   for (int i=0; i<(*qf)->num_input_fields; i++) {
1040     ierr = CeedFree(&(*(*qf)->input_fields[i]).field_name); CeedChk(ierr);
1041     ierr = CeedFree(&(*qf)->input_fields[i]); CeedChk(ierr);
1042   }
1043   for (int i=0; i<(*qf)->num_output_fields; i++) {
1044     ierr = CeedFree(&(*(*qf)->output_fields[i]).field_name); CeedChk(ierr);
1045     ierr = CeedFree(&(*qf)->output_fields[i]); CeedChk(ierr);
1046   }
1047   ierr = CeedFree(&(*qf)->input_fields); CeedChk(ierr);
1048   ierr = CeedFree(&(*qf)->output_fields); CeedChk(ierr);
1049 
1050   // User context data object
1051   ierr = CeedQFunctionContextDestroy(&(*qf)->ctx); CeedChk(ierr);
1052 
1053   ierr = CeedFree(&(*qf)->source_path); CeedChk(ierr);
1054   ierr = CeedFree(&(*qf)->gallery_name); CeedChk(ierr);
1055   ierr = CeedFree(&(*qf)->kernel_name); CeedChk(ierr);
1056   ierr = CeedDestroy(&(*qf)->ceed); CeedChk(ierr);
1057   ierr = CeedFree(qf); CeedChk(ierr);
1058   return CEED_ERROR_SUCCESS;
1059 }
1060 
1061 /// @}
1062