xref: /libCEED/interface/ceed-qfunction.c (revision 81d4e52aee579b45d02648ba6e48525fe12fcd58)
1 // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
2 // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
3 // reserved. See files LICENSE and NOTICE for details.
4 //
5 // This file is part of CEED, a collection of benchmarks, miniapps, software
6 // libraries and APIs for efficient high-order finite element and spectral
7 // element discretizations for exascale applications. For more information and
8 // source code availability see http://github.com/ceed.
9 //
10 // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
11 // a collaborative effort of two U.S. Department of Energy organizations (Office
12 // of Science and the National Nuclear Security Administration) responsible for
13 // the planning and preparation of a capable exascale ecosystem, including
14 // software, applications, hardware, advanced system engineering and early
15 // testbed platforms, in support of the nation's exascale computing imperative.
16 
17 #include <ceed/ceed.h>
18 #include <ceed/backend.h>
19 #include <ceed-impl.h>
20 #include <limits.h>
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <string.h>
24 
25 /// @file
26 /// Implementation of public CeedQFunction interfaces
27 
28 /// @cond DOXYGEN_SKIP
29 static struct CeedQFunction_private ceed_qfunction_none;
30 /// @endcond
31 
32 /// @addtogroup CeedQFunctionUser
33 /// @{
34 
35 // Indicate that no QFunction is provided by the user
36 const CeedQFunction CEED_QFUNCTION_NONE = &ceed_qfunction_none;
37 
38 /// @}
39 
40 /// @cond DOXYGEN_SKIP
41 static struct {
42   char name[CEED_MAX_RESOURCE_LEN];
43   char source[CEED_MAX_RESOURCE_LEN];
44   CeedInt vec_length;
45   CeedQFunctionUser f;
46   int (*init)(Ceed ceed, const char *name, CeedQFunction qf);
47 } gallery_qfunctions[1024];
48 static size_t num_qfunctions;
49 /// @endcond
50 
51 /// ----------------------------------------------------------------------------
52 /// CeedQFunction Library Internal Functions
53 /// ----------------------------------------------------------------------------
54 /// @addtogroup CeedQFunctionDeveloper
55 /// @{
56 
57 /**
58   @brief Register a gallery QFunction
59 
60   @param name        Name for this backend to respond to
61   @param source      Absolute path to source of QFunction,
62                        "\path\CEED_DIR\gallery\folder\file.h:function_name"
63   @param vec_length  Vector length.  Caller must ensure that number of quadrature
64                        points is a multiple of vec_length.
65   @param f           Function pointer to evaluate action at quadrature points.
66                        See \ref CeedQFunctionUser.
67   @param init        Initialization function called by CeedQFunctionInit() when the
68                        QFunction is selected.
69 
70   @return An error code: 0 - success, otherwise - failure
71 
72   @ref Developer
73 **/
74 int CeedQFunctionRegister(const char *name, const char *source,
75                           CeedInt vec_length, CeedQFunctionUser f,
76                           int (*init)(Ceed, const char *, CeedQFunction)) {
77   if (num_qfunctions >= sizeof(gallery_qfunctions) / sizeof(
78         gallery_qfunctions[0]))
79     // LCOV_EXCL_START
80     return CeedError(NULL, CEED_ERROR_MAJOR, "Too many gallery QFunctions");
81   // LCOV_EXCL_STOP
82 
83   strncpy(gallery_qfunctions[num_qfunctions].name, name, CEED_MAX_RESOURCE_LEN);
84   gallery_qfunctions[num_qfunctions].name[CEED_MAX_RESOURCE_LEN-1] = 0;
85   strncpy(gallery_qfunctions[num_qfunctions].source, source,
86           CEED_MAX_RESOURCE_LEN);
87   gallery_qfunctions[num_qfunctions].source[CEED_MAX_RESOURCE_LEN-1] = 0;
88   gallery_qfunctions[num_qfunctions].vec_length = vec_length;
89   gallery_qfunctions[num_qfunctions].f = f;
90   gallery_qfunctions[num_qfunctions].init = init;
91   num_qfunctions++;
92   return CEED_ERROR_SUCCESS;
93 }
94 
95 /**
96   @brief Set a CeedQFunction field, used by CeedQFunctionAddInput/Output
97 
98   @param f           CeedQFunctionField
99   @param field_name  Name of QFunction field
100   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
101                        (num_comp * 1) for @ref CEED_EVAL_NONE, @ref CEED_EVAL_INTERP, and @ref CEED_EVAL_WEIGHT
102   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
103                        \ref CEED_EVAL_INTERP to use interpolated values,
104                        \ref CEED_EVAL_GRAD to use gradients,
105                        \ref CEED_EVAL_WEIGHT to use quadrature weights.
106 
107   @return An error code: 0 - success, otherwise - failure
108 
109   @ref Developer
110 **/
111 static int CeedQFunctionFieldSet(CeedQFunctionField *f,const char *field_name,
112                                  CeedInt size, CeedEvalMode eval_mode) {
113   size_t len = strlen(field_name);
114   char *tmp;
115   int ierr;
116 
117   ierr = CeedCalloc(1, f); CeedChk(ierr);
118   ierr = CeedCalloc(len+1, &tmp); CeedChk(ierr);
119   memcpy(tmp, field_name, len+1);
120   (*f)->field_name = tmp;
121   (*f)->size = size;
122   (*f)->eval_mode = eval_mode;
123   return CEED_ERROR_SUCCESS;
124 }
125 
126 /**
127   @brief View a field of a CeedQFunction
128 
129   @param[in] field         QFunction field to view
130   @param[in] field_number  Number of field being viewed
131   @param[in] in            true for input field, false for output
132   @param[in] stream        Stream to view to, e.g., stdout
133 
134   @return An error code: 0 - success, otherwise - failure
135 
136   @ref Utility
137 **/
138 static int CeedQFunctionFieldView(CeedQFunctionField field,
139                                   CeedInt field_number,
140                                   bool in, FILE *stream) {
141   const char *inout = in ? "Input" : "Output";
142   fprintf(stream, "    %s Field [%d]:\n"
143           "      Name: \"%s\"\n"
144           "      Size: %d\n"
145           "      EvalMode: \"%s\"\n",
146           inout, field_number, field->field_name, field->size,
147           CeedEvalModes[field->eval_mode]);
148   return CEED_ERROR_SUCCESS;
149 }
150 
151 /**
152   @brief Set flag to determine if Fortran interface is used
153 
154   @param qf      CeedQFunction
155   @param status  Boolean value to set as Fortran status
156 
157   @return An error code: 0 - success, otherwise - failure
158 
159   @ref Backend
160 **/
161 int CeedQFunctionSetFortranStatus(CeedQFunction qf, bool status) {
162   qf->fortran_status = status;
163   return CEED_ERROR_SUCCESS;
164 }
165 
166 /// @}
167 
168 /// ----------------------------------------------------------------------------
169 /// CeedQFunction Backend API
170 /// ----------------------------------------------------------------------------
171 /// @addtogroup CeedQFunctionBackend
172 /// @{
173 
174 /**
175   @brief Get the Ceed associated with a CeedQFunction
176 
177   @param qf              CeedQFunction
178   @param[out] ceed       Variable to store Ceed
179 
180   @return An error code: 0 - success, otherwise - failure
181 
182   @ref Backend
183 **/
184 int CeedQFunctionGetCeed(CeedQFunction qf, Ceed *ceed) {
185   *ceed = qf->ceed;
186   return CEED_ERROR_SUCCESS;
187 }
188 
189 /**
190   @brief Get the vector length of a CeedQFunction
191 
192   @param qf               CeedQFunction
193   @param[out] vec_length  Variable to store vector length
194 
195   @return An error code: 0 - success, otherwise - failure
196 
197   @ref Backend
198 **/
199 int CeedQFunctionGetVectorLength(CeedQFunction qf, CeedInt *vec_length) {
200   *vec_length = qf->vec_length;
201   return CEED_ERROR_SUCCESS;
202 }
203 
204 /**
205   @brief Get the number of inputs and outputs to a CeedQFunction
206 
207   @param qf               CeedQFunction
208   @param[out] num_input   Variable to store number of input fields
209   @param[out] num_output  Variable to store number of output fields
210 
211   @return An error code: 0 - success, otherwise - failure
212 
213   @ref Backend
214 **/
215 int CeedQFunctionGetNumArgs(CeedQFunction qf, CeedInt *num_input,
216                             CeedInt *num_output) {
217   if (num_input) *num_input = qf->num_input_fields;
218   if (num_output) *num_output = qf->num_output_fields;
219   return CEED_ERROR_SUCCESS;
220 }
221 
222 /**
223   @brief Get the source path string for a CeedQFunction
224 
225   @param qf           CeedQFunction
226   @param[out] source  Variable to store source path string
227 
228   @return An error code: 0 - success, otherwise - failure
229 
230   @ref Backend
231 **/
232 int CeedQFunctionGetSourcePath(CeedQFunction qf, char **source) {
233   *source = (char *) qf->source_path;
234   return CEED_ERROR_SUCCESS;
235 }
236 
237 /**
238   @brief Get the User Function for a CeedQFunction
239 
240   @param qf      CeedQFunction
241   @param[out] f  Variable to store user function
242 
243   @return An error code: 0 - success, otherwise - failure
244 
245   @ref Backend
246 **/
247 int CeedQFunctionGetUserFunction(CeedQFunction qf, CeedQFunctionUser *f) {
248   *f = qf->function;
249   return CEED_ERROR_SUCCESS;
250 }
251 
252 /**
253   @brief Get global context for a CeedQFunction.
254            Note: For QFunctions from the Fortran interface, this
255              function will return the Fortran context
256              CeedQFunctionContext.
257 
258   @param qf        CeedQFunction
259   @param[out] ctx  Variable to store CeedQFunctionContext
260 
261   @return An error code: 0 - success, otherwise - failure
262 
263   @ref Backend
264 **/
265 int CeedQFunctionGetContext(CeedQFunction qf, CeedQFunctionContext *ctx) {
266   *ctx = qf->ctx;
267   return CEED_ERROR_SUCCESS;
268 }
269 
270 /**
271   @brief Get true user context for a CeedQFunction
272            Note: For all QFunctions this function will return the user
273              CeedQFunctionContext and not interface context
274              CeedQFunctionContext, if any such object exists.
275 
276   @param qf        CeedQFunction
277   @param[out] ctx  Variable to store CeedQFunctionContext
278 
279   @return An error code: 0 - success, otherwise - failure
280   @ref Backend
281 **/
282 int CeedQFunctionGetInnerContext(CeedQFunction qf, CeedQFunctionContext *ctx) {
283   int ierr;
284   if (qf->fortran_status) {
285     CeedFortranContext fortran_ctx = NULL;
286     ierr = CeedQFunctionContextGetData(qf->ctx, CEED_MEM_HOST, &fortran_ctx);
287     CeedChk(ierr);
288     *ctx = fortran_ctx->innerctx;
289     ierr = CeedQFunctionContextRestoreData(qf->ctx, (void *)&fortran_ctx);
290     CeedChk(ierr);
291   } else {
292     *ctx = qf->ctx;
293   }
294   return CEED_ERROR_SUCCESS;
295 }
296 
297 /**
298   @brief Determine if QFunction is identity
299 
300   @param qf                CeedQFunction
301   @param[out] is_identity  Variable to store identity status
302 
303   @return An error code: 0 - success, otherwise - failure
304 
305   @ref Backend
306 **/
307 int CeedQFunctionIsIdentity(CeedQFunction qf, bool *is_identity) {
308   *is_identity = qf->identity;
309   return CEED_ERROR_SUCCESS;
310 }
311 
312 /**
313   @brief Get backend data of a CeedQFunction
314 
315   @param qf         CeedQFunction
316   @param[out] data  Variable to store data
317 
318   @return An error code: 0 - success, otherwise - failure
319 
320   @ref Backend
321 **/
322 int CeedQFunctionGetData(CeedQFunction qf, void *data) {
323   *(void **)data = qf->data;
324   return CEED_ERROR_SUCCESS;
325 }
326 
327 /**
328   @brief Set backend data of a CeedQFunction
329 
330   @param[out] qf  CeedQFunction
331   @param data     Data to set
332 
333   @return An error code: 0 - success, otherwise - failure
334 
335   @ref Backend
336 **/
337 int CeedQFunctionSetData(CeedQFunction qf, void *data) {
338   qf->data = data;
339   return CEED_ERROR_SUCCESS;
340 }
341 
342 /**
343   @brief Increment the reference counter for a CeedQFunction
344 
345   @param qf  CeedQFunction to increment the reference counter
346 
347   @return An error code: 0 - success, otherwise - failure
348 
349   @ref Backend
350 **/
351 int CeedQFunctionReference(CeedQFunction qf) {
352   qf->ref_count++;
353   return CEED_ERROR_SUCCESS;
354 }
355 
356 /**
357   @brief Get the CeedQFunctionFields of a CeedQFunction
358 
359   @param qf                  CeedQFunction
360   @param[out] input_fields   Variable to store input_fields
361   @param[out] output_fields  Variable to store output_fields
362 
363   @return An error code: 0 - success, otherwise - failure
364 
365   @ref Backend
366 **/
367 int CeedQFunctionGetFields(CeedQFunction qf, CeedQFunctionField **input_fields,
368                            CeedQFunctionField **output_fields) {
369   if (input_fields) *input_fields = qf->input_fields;
370   if (output_fields) *output_fields = qf->output_fields;
371   return CEED_ERROR_SUCCESS;
372 }
373 
374 /**
375   @brief Get the name of a CeedQFunctionField
376 
377   @param qf_field         CeedQFunctionField
378   @param[out] field_name  Variable to store the field name
379 
380   @return An error code: 0 - success, otherwise - failure
381 
382   @ref Backend
383 **/
384 int CeedQFunctionFieldGetName(CeedQFunctionField qf_field, char **field_name) {
385   *field_name = (char *)qf_field->field_name;
386   return CEED_ERROR_SUCCESS;
387 }
388 
389 /**
390   @brief Get the number of components of a CeedQFunctionField
391 
392   @param qf_field   CeedQFunctionField
393   @param[out] size  Variable to store the size of the field
394 
395   @return An error code: 0 - success, otherwise - failure
396 
397   @ref Backend
398 **/
399 int CeedQFunctionFieldGetSize(CeedQFunctionField qf_field, CeedInt *size) {
400   *size = qf_field->size;
401   return CEED_ERROR_SUCCESS;
402 }
403 
404 /**
405   @brief Get the CeedEvalMode of a CeedQFunctionField
406 
407   @param qf_field        CeedQFunctionField
408   @param[out] eval_mode  Variable to store the field evaluation mode
409 
410   @return An error code: 0 - success, otherwise - failure
411 
412   @ref Backend
413 **/
414 int CeedQFunctionFieldGetEvalMode(CeedQFunctionField qf_field,
415                                   CeedEvalMode *eval_mode) {
416   *eval_mode = qf_field->eval_mode;
417   return CEED_ERROR_SUCCESS;
418 }
419 
420 /// @}
421 
422 /// ----------------------------------------------------------------------------
423 /// CeedQFunction Public API
424 /// ----------------------------------------------------------------------------
425 /// @addtogroup CeedQFunctionUser
426 /// @{
427 
428 /**
429   @brief Create a CeedQFunction for evaluating interior (volumetric) terms.
430 
431   @param ceed        A Ceed object where the CeedQFunction will be created
432   @param vec_length  Vector length. Caller must ensure that number of quadrature
433                        points is a multiple of vec_length.
434   @param f           Function pointer to evaluate action at quadrature points.
435                        See \ref CeedQFunctionUser.
436   @param source      Absolute path to source of QFunction,
437                        "\abs_path\file.h:function_name".
438                        For support across all backends, this source must only
439                        contain constructs supported by C99, C++11, and CUDA.
440   @param[out] qf     Address of the variable where the newly created
441                        CeedQFunction will be stored
442 
443   @return An error code: 0 - success, otherwise - failure
444 
445   See \ref CeedQFunctionUser for details on the call-back function @a f's
446     arguments.
447 
448   @ref User
449 **/
450 int CeedQFunctionCreateInterior(Ceed ceed, CeedInt vec_length,
451                                 CeedQFunctionUser f,
452                                 const char *source, CeedQFunction *qf) {
453   int ierr;
454   char *source_copy;
455 
456   if (!ceed->QFunctionCreate) {
457     Ceed delegate;
458     ierr = CeedGetObjectDelegate(ceed, &delegate, "QFunction"); CeedChk(ierr);
459 
460     if (!delegate)
461       // LCOV_EXCL_START
462       return CeedError(ceed, CEED_ERROR_UNSUPPORTED,
463                        "Backend does not support QFunctionCreate");
464     // LCOV_EXCL_STOP
465 
466     ierr = CeedQFunctionCreateInterior(delegate, vec_length, f, source, qf);
467     CeedChk(ierr);
468     return CEED_ERROR_SUCCESS;
469   }
470 
471   ierr = CeedCalloc(1, qf); CeedChk(ierr);
472   (*qf)->ceed = ceed;
473   ierr = CeedReference(ceed); CeedChk(ierr);
474   (*qf)->ref_count = 1;
475   (*qf)->vec_length = vec_length;
476   (*qf)->identity = 0;
477   (*qf)->function = f;
478   size_t slen = strlen(source) + 1;
479   ierr = CeedMalloc(slen, &source_copy); CeedChk(ierr);
480   memcpy(source_copy, source, slen);
481   (*qf)->source_path = source_copy;
482   ierr = CeedCalloc(16, &(*qf)->input_fields); CeedChk(ierr);
483   ierr = CeedCalloc(16, &(*qf)->output_fields); CeedChk(ierr);
484   ierr = ceed->QFunctionCreate(*qf); CeedChk(ierr);
485   return CEED_ERROR_SUCCESS;
486 }
487 
488 /**
489   @brief Create a CeedQFunction for evaluating interior (volumetric) terms by name.
490 
491   @param ceed     A Ceed object where the CeedQFunction will be created
492   @param name     Name of QFunction to use from gallery
493   @param[out] qf  Address of the variable where the newly created
494                     CeedQFunction will be stored
495 
496   @return An error code: 0 - success, otherwise - failure
497 
498   @ref User
499 **/
500 int CeedQFunctionCreateInteriorByName(Ceed ceed,  const char *name,
501                                       CeedQFunction *qf) {
502   int ierr;
503   size_t match_len = 0, match_idx = UINT_MAX;
504   char *name_copy;
505 
506   ierr = CeedQFunctionRegisterAll(); CeedChk(ierr);
507   // Find matching backend
508   if (!name) return CeedError(ceed, CEED_ERROR_INCOMPLETE,
509                                 "No QFunction name provided");
510   for (size_t i=0; i<num_qfunctions; i++) {
511     size_t n;
512     const char *curr_name = gallery_qfunctions[i].name;
513     for (n = 0; curr_name[n] && curr_name[n] == name[n]; n++) {}
514     if (n > match_len) {
515       match_len = n;
516       match_idx = i;
517     }
518   }
519   if (!match_len)
520     // LCOV_EXCL_START
521     return CeedError(ceed, CEED_ERROR_UNSUPPORTED, "No suitable gallery QFunction");
522   // LCOV_EXCL_STOP
523 
524   // Create QFunction
525   ierr = CeedQFunctionCreateInterior(ceed,
526                                      gallery_qfunctions[match_idx].vec_length,
527                                      gallery_qfunctions[match_idx].f,
528                                      gallery_qfunctions[match_idx].source, qf);
529   CeedChk(ierr);
530 
531   // QFunction specific setup
532   ierr = gallery_qfunctions[match_idx].init(ceed, name, *qf); CeedChk(ierr);
533 
534   // Copy name
535   size_t slen = strlen(name) + 1;
536   ierr = CeedMalloc(slen, &name_copy); CeedChk(ierr);
537   memcpy(name_copy, name, slen);
538   (*qf)->qf_name = name_copy;
539   return CEED_ERROR_SUCCESS;
540 }
541 
542 /**
543   @brief Create an identity CeedQFunction. Inputs are written into outputs in
544            the order given. This is useful for CeedOperators that can be
545            represented with only the action of a CeedRestriction and CeedBasis,
546            such as restriction and prolongation operators for p-multigrid.
547            Backends may optimize CeedOperators with this CeedQFunction to avoid
548            the copy of input data to output fields by using the same memory
549            location for both.
550 
551   @param ceed          A Ceed object where the CeedQFunction will be created
552   @param[in] size      Size of the QFunction fields
553   @param[in] in_mode   CeedEvalMode for input to CeedQFunction
554   @param[in] out_mode  CeedEvalMode for output to CeedQFunction
555   @param[out] qf       Address of the variable where the newly created
556                          CeedQFunction will be stored
557 
558   @return An error code: 0 - success, otherwise - failure
559 
560   @ref User
561 **/
562 int CeedQFunctionCreateIdentity(Ceed ceed, CeedInt size, CeedEvalMode in_mode,
563                                 CeedEvalMode out_mode, CeedQFunction *qf) {
564   int ierr;
565 
566   ierr = CeedQFunctionCreateInteriorByName(ceed, "Identity", qf); CeedChk(ierr);
567   ierr = CeedQFunctionAddInput(*qf, "input", size, in_mode); CeedChk(ierr);
568   ierr = CeedQFunctionAddOutput(*qf, "output", size, out_mode); CeedChk(ierr);
569 
570   (*qf)->identity = 1;
571   CeedInt *size_data;
572   ierr = CeedCalloc(1, &size_data); CeedChk(ierr);
573   size_data[0] = size;
574   CeedQFunctionContext ctx;
575   ierr = CeedQFunctionContextCreate(ceed, &ctx); CeedChk(ierr);
576   ierr = CeedQFunctionContextSetData(ctx, CEED_MEM_HOST, CEED_OWN_POINTER,
577                                      sizeof(*size_data), (void *)size_data);
578   CeedChk(ierr);
579   ierr = CeedQFunctionSetContext(*qf, ctx); CeedChk(ierr);
580   ierr = CeedQFunctionContextDestroy(&ctx); CeedChk(ierr);
581   return CEED_ERROR_SUCCESS;
582 }
583 
584 /**
585   @brief Copy the pointer to a CeedQFunction. Both pointers should
586            be destroyed with `CeedQFunctionDestroy()`;
587            Note: If `*qf_copy` is non-NULL, then it is assumed that
588            `*qf_copy` is a pointer to a CeedQFunction. This
589            CeedQFunction will be destroyed if `*qf_copy` is the only
590            reference to this CeedQFunction.
591 
592   @param qf            CeedQFunction to copy reference to
593   @param[out] qf_copy  Variable to store copied reference
594 
595   @return An error code: 0 - success, otherwise - failure
596 
597   @ref User
598 **/
599 int CeedQFunctionReferenceCopy(CeedQFunction qf, CeedQFunction *qf_copy) {
600   int ierr;
601 
602   ierr = CeedQFunctionReference(qf); CeedChk(ierr);
603   ierr = CeedQFunctionDestroy(qf_copy); CeedChk(ierr);
604   *qf_copy = qf;
605   return CEED_ERROR_SUCCESS;
606 }
607 
608 /**
609   @brief Add a CeedQFunction input
610 
611   @param qf          CeedQFunction
612   @param field_name  Name of QFunction field
613   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
614                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
615   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
616                        \ref CEED_EVAL_INTERP to use interpolated values,
617                        \ref CEED_EVAL_GRAD to use gradients.
618 
619   @return An error code: 0 - success, otherwise - failure
620 
621   @ref User
622 **/
623 int CeedQFunctionAddInput(CeedQFunction qf, const char *field_name,
624                           CeedInt size,
625                           CeedEvalMode eval_mode) {
626   if (qf->operators_set)
627     // LCOV_EXCL_START
628     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
629                      "QFunction cannot be changed when in use by an operator");
630   // LCOV_EXCL_STOP
631   if ((eval_mode == CEED_EVAL_WEIGHT) && (size != 1))
632     // LCOV_EXCL_START
633     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
634                      "CEED_EVAL_WEIGHT should have size 1");
635   // LCOV_EXCL_STOP
636   int ierr = CeedQFunctionFieldSet(&qf->input_fields[qf->num_input_fields],
637                                    field_name, size, eval_mode);
638   CeedChk(ierr);
639   qf->num_input_fields++;
640   return CEED_ERROR_SUCCESS;
641 }
642 
643 /**
644   @brief Add a CeedQFunction output
645 
646   @param qf          CeedQFunction
647   @param field_name  Name of QFunction field
648   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
649                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
650   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
651                        \ref CEED_EVAL_INTERP to use interpolated values,
652                        \ref CEED_EVAL_GRAD to use gradients.
653 
654   @return An error code: 0 - success, otherwise - failure
655 
656   @ref User
657 **/
658 int CeedQFunctionAddOutput(CeedQFunction qf, const char *field_name,
659                            CeedInt size, CeedEvalMode eval_mode) {
660   if (qf->operators_set)
661     // LCOV_EXCL_START
662     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
663                      "QFunction cannot be changed when in use by an operator");
664   // LCOV_EXCL_STOP
665   if (eval_mode == CEED_EVAL_WEIGHT)
666     // LCOV_EXCL_START
667     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
668                      "Cannot create QFunction output with "
669                      "CEED_EVAL_WEIGHT");
670   // LCOV_EXCL_STOP
671   int ierr = CeedQFunctionFieldSet(&qf->output_fields[qf->num_output_fields],
672                                    field_name, size, eval_mode);
673   CeedChk(ierr);
674   qf->num_output_fields++;
675   return CEED_ERROR_SUCCESS;
676 }
677 
678 /**
679   @brief Set global context for a CeedQFunction
680 
681   @param qf   CeedQFunction
682   @param ctx  Context data to set
683 
684   @return An error code: 0 - success, otherwise - failure
685 
686   @ref User
687 **/
688 int CeedQFunctionSetContext(CeedQFunction qf, CeedQFunctionContext ctx) {
689   int ierr;
690   qf->ctx = ctx;
691   ierr = CeedQFunctionContextReference(ctx); CeedChk(ierr);
692   return CEED_ERROR_SUCCESS;
693 }
694 
695 /**
696   @brief View a CeedQFunction
697 
698   @param[in] qf      CeedQFunction to view
699   @param[in] stream  Stream to write; typically stdout/stderr or a file
700 
701   @return Error code: 0 - success, otherwise - failure
702 
703   @ref User
704 **/
705 int CeedQFunctionView(CeedQFunction qf, FILE *stream) {
706   int ierr;
707 
708   fprintf(stream, "%sCeedQFunction %s\n",
709           qf->qf_name ? "Gallery " : "User ", qf->qf_name ? qf->qf_name : "");
710 
711   fprintf(stream, "  %d Input Field%s:\n", qf->num_input_fields,
712           qf->num_input_fields>1 ? "s" : "");
713   for (CeedInt i=0; i<qf->num_input_fields; i++) {
714     ierr = CeedQFunctionFieldView(qf->input_fields[i], i, 1, stream);
715     CeedChk(ierr);
716   }
717 
718   fprintf(stream, "  %d Output Field%s:\n", qf->num_output_fields,
719           qf->num_output_fields>1 ? "s" : "");
720   for (CeedInt i=0; i<qf->num_output_fields; i++) {
721     ierr = CeedQFunctionFieldView(qf->output_fields[i], i, 0, stream);
722     CeedChk(ierr);
723   }
724   return CEED_ERROR_SUCCESS;
725 }
726 
727 /**
728   @brief Apply the action of a CeedQFunction
729 
730   @param qf      CeedQFunction
731   @param Q       Number of quadrature points
732   @param[in] u   Array of input CeedVectors
733   @param[out] v  Array of output CeedVectors
734 
735   @return An error code: 0 - success, otherwise - failure
736 
737   @ref User
738 **/
739 int CeedQFunctionApply(CeedQFunction qf, CeedInt Q,
740                        CeedVector *u, CeedVector *v) {
741   int ierr;
742   if (!qf->Apply)
743     // LCOV_EXCL_START
744     return CeedError(qf->ceed, CEED_ERROR_UNSUPPORTED,
745                      "Backend does not support QFunctionApply");
746   // LCOV_EXCL_STOP
747   if (Q % qf->vec_length)
748     // LCOV_EXCL_START
749     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
750                      "Number of quadrature points %d must be a "
751                      "multiple of %d", Q, qf->vec_length);
752   // LCOV_EXCL_STOP
753   ierr = qf->Apply(qf, Q, u, v); CeedChk(ierr);
754   return CEED_ERROR_SUCCESS;
755 }
756 
757 /**
758   @brief Destroy a CeedQFunction
759 
760   @param qf  CeedQFunction to destroy
761 
762   @return An error code: 0 - success, otherwise - failure
763 
764   @ref User
765 **/
766 int CeedQFunctionDestroy(CeedQFunction *qf) {
767   int ierr;
768 
769   if (!*qf || --(*qf)->ref_count > 0) return CEED_ERROR_SUCCESS;
770   // Backend destroy
771   if ((*qf)->Destroy) {
772     ierr = (*qf)->Destroy(*qf); CeedChk(ierr);
773   }
774   // Free fields
775   for (int i=0; i<(*qf)->num_input_fields; i++) {
776     ierr = CeedFree(&(*(*qf)->input_fields[i]).field_name); CeedChk(ierr);
777     ierr = CeedFree(&(*qf)->input_fields[i]); CeedChk(ierr);
778   }
779   for (int i=0; i<(*qf)->num_output_fields; i++) {
780     ierr = CeedFree(&(*(*qf)->output_fields[i]).field_name); CeedChk(ierr);
781     ierr = CeedFree(&(*qf)->output_fields[i]); CeedChk(ierr);
782   }
783   ierr = CeedFree(&(*qf)->input_fields); CeedChk(ierr);
784   ierr = CeedFree(&(*qf)->output_fields); CeedChk(ierr);
785 
786   // User context data object
787   ierr = CeedQFunctionContextDestroy(&(*qf)->ctx); CeedChk(ierr);
788 
789   ierr = CeedFree(&(*qf)->source_path); CeedChk(ierr);
790   ierr = CeedFree(&(*qf)->qf_name); CeedChk(ierr);
791   ierr = CeedDestroy(&(*qf)->ceed); CeedChk(ierr);
792   ierr = CeedFree(qf); CeedChk(ierr);
793   return CEED_ERROR_SUCCESS;
794 }
795 
796 /// @}
797