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