xref: /libCEED/interface/ceed-qfunction.c (revision dada6cc03e18f0f18a02732451145fd10701e640)
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 %" CeedInt_FMT ":\n"
147           "      Name: \"%s\"\n"
148           "      Size: %" CeedInt_FMT "\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     bool is_absolute_path;
607     char *absolute_path;
608 
609     ierr = CeedCheckFilePath(ceed, source, &is_absolute_path); CeedChk(ierr);
610     if (is_absolute_path) {
611       absolute_path = (char *)source;
612     } else {
613       ierr = CeedGetJitAbsolutePath(ceed, source, &absolute_path); CeedChk(ierr);
614     }
615 
616     const char *kernel_name = strrchr(absolute_path, ':') + 1;
617     size_t kernel_name_len = strlen(kernel_name);
618     ierr = CeedCalloc(kernel_name_len + 1, &kernel_name_copy); CeedChk(ierr);
619     memcpy(kernel_name_copy, kernel_name, kernel_name_len);
620     (*qf)->kernel_name = kernel_name_copy;
621 
622     size_t source_len = strlen(absolute_path) - kernel_name_len - 1;
623     ierr = CeedCalloc(source_len + 1, &source_copy); CeedChk(ierr);
624     memcpy(source_copy, absolute_path, source_len);
625     (*qf)->source_path = source_copy;
626 
627     if (!is_absolute_path) {
628       ierr = CeedFree(&absolute_path); CeedChk(ierr);
629     }
630   }
631   ierr = CeedCalloc(CEED_FIELD_MAX, &(*qf)->input_fields); CeedChk(ierr);
632   ierr = CeedCalloc(CEED_FIELD_MAX, &(*qf)->output_fields); CeedChk(ierr);
633   ierr = ceed->QFunctionCreate(*qf); CeedChk(ierr);
634   return CEED_ERROR_SUCCESS;
635 }
636 
637 /**
638   @brief Create a CeedQFunction for evaluating interior (volumetric) terms by name.
639 
640   @param ceed     A Ceed object where the CeedQFunction will be created
641   @param name     Name of QFunction to use from gallery
642   @param[out] qf  Address of the variable where the newly created
643                     CeedQFunction will be stored
644 
645   @return An error code: 0 - success, otherwise - failure
646 
647   @ref User
648 **/
649 int CeedQFunctionCreateInteriorByName(Ceed ceed,  const char *name,
650                                       CeedQFunction *qf) {
651   int ierr;
652   size_t match_len = 0, match_index = UINT_MAX;
653 
654   ierr = CeedQFunctionRegisterAll(); CeedChk(ierr);
655   // Find matching backend
656   if (!name) return CeedError(ceed, CEED_ERROR_INCOMPLETE,
657                                 "No QFunction name provided");
658   for (size_t i=0; i<num_qfunctions; i++) {
659     size_t n;
660     const char *curr_name = gallery_qfunctions[i].name;
661     for (n = 0; curr_name[n] && curr_name[n] == name[n]; n++) {}
662     if (n > match_len) {
663       match_len = n;
664       match_index = i;
665     }
666   }
667   if (!match_len)
668     // LCOV_EXCL_START
669     return CeedError(ceed, CEED_ERROR_UNSUPPORTED, "No suitable gallery QFunction");
670   // LCOV_EXCL_STOP
671 
672   // Create QFunction
673   ierr = CeedQFunctionCreateInterior(ceed,
674                                      gallery_qfunctions[match_index].vec_length,
675                                      gallery_qfunctions[match_index].f,
676                                      gallery_qfunctions[match_index].source, qf);
677   CeedChk(ierr);
678 
679   // QFunction specific setup
680   ierr = gallery_qfunctions[match_index].init(ceed, name, *qf); CeedChk(ierr);
681 
682   // Copy name
683   ierr = CeedStringAllocCopy(name, (char **)&(*qf)->gallery_name); CeedChk(ierr);
684   (*qf)->is_gallery = true;
685   return CEED_ERROR_SUCCESS;
686 }
687 
688 /**
689   @brief Create an identity CeedQFunction. Inputs are written into outputs in
690            the order given. This is useful for CeedOperators that can be
691            represented with only the action of a CeedRestriction and CeedBasis,
692            such as restriction and prolongation operators for p-multigrid.
693            Backends may optimize CeedOperators with this CeedQFunction to avoid
694            the copy of input data to output fields by using the same memory
695            location for both.
696 
697   @param ceed          A Ceed object where the CeedQFunction will be created
698   @param[in] size      Size of the QFunction fields
699   @param[in] in_mode   CeedEvalMode for input to CeedQFunction
700   @param[in] out_mode  CeedEvalMode for output to CeedQFunction
701   @param[out] qf       Address of the variable where the newly created
702                          CeedQFunction will be stored
703 
704   @return An error code: 0 - success, otherwise - failure
705 
706   @ref User
707 **/
708 int CeedQFunctionCreateIdentity(Ceed ceed, CeedInt size, CeedEvalMode in_mode,
709                                 CeedEvalMode out_mode, CeedQFunction *qf) {
710   int ierr;
711 
712   ierr = CeedQFunctionCreateInteriorByName(ceed, "Identity", qf); CeedChk(ierr);
713   ierr = CeedQFunctionAddInput(*qf, "input", size, in_mode); CeedChk(ierr);
714   ierr = CeedQFunctionAddOutput(*qf, "output", size, out_mode); CeedChk(ierr);
715 
716   (*qf)->is_identity = true;
717 
718   CeedQFunctionContext ctx;
719   CeedContextFieldLabel size_label;
720   ierr = CeedQFunctionGetContext(*qf, &ctx); CeedChk(ierr);
721   ierr = CeedQFunctionContextGetFieldLabel(ctx, "size", &size_label);
722   CeedChk(ierr);
723   ierr = CeedQFunctionContextSetInt32(ctx, size_label, &size); CeedChk(ierr);
724 
725   return CEED_ERROR_SUCCESS;
726 }
727 
728 /**
729   @brief Copy the pointer to a CeedQFunction. Both pointers should
730            be destroyed with `CeedQFunctionDestroy()`;
731            Note: If `*qf_copy` is non-NULL, then it is assumed that
732            `*qf_copy` is a pointer to a CeedQFunction. This
733            CeedQFunction will be destroyed if `*qf_copy` is the only
734            reference to this CeedQFunction.
735 
736   @param qf            CeedQFunction to copy reference to
737   @param[out] qf_copy  Variable to store copied reference
738 
739   @return An error code: 0 - success, otherwise - failure
740 
741   @ref User
742 **/
743 int CeedQFunctionReferenceCopy(CeedQFunction qf, CeedQFunction *qf_copy) {
744   int ierr;
745 
746   ierr = CeedQFunctionReference(qf); CeedChk(ierr);
747   ierr = CeedQFunctionDestroy(qf_copy); CeedChk(ierr);
748   *qf_copy = qf;
749   return CEED_ERROR_SUCCESS;
750 }
751 
752 /**
753   @brief Add a CeedQFunction input
754 
755   @param qf          CeedQFunction
756   @param field_name  Name of QFunction field
757   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
758                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
759   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
760                        \ref CEED_EVAL_INTERP to use interpolated values,
761                        \ref CEED_EVAL_GRAD to use gradients.
762 
763   @return An error code: 0 - success, otherwise - failure
764 
765   @ref User
766 **/
767 int CeedQFunctionAddInput(CeedQFunction qf, const char *field_name,
768                           CeedInt size,
769                           CeedEvalMode eval_mode) {
770   if (qf->is_immutable)
771     // LCOV_EXCL_START
772     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
773                      "QFunction cannot be changed after set as immutable");
774   // LCOV_EXCL_STOP
775   if ((eval_mode == CEED_EVAL_WEIGHT) && (size != 1))
776     // LCOV_EXCL_START
777     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
778                      "CEED_EVAL_WEIGHT should have size 1");
779   // LCOV_EXCL_STOP
780   int ierr = CeedQFunctionFieldSet(&qf->input_fields[qf->num_input_fields],
781                                    field_name, size, eval_mode);
782   CeedChk(ierr);
783   qf->num_input_fields++;
784   return CEED_ERROR_SUCCESS;
785 }
786 
787 /**
788   @brief Add a CeedQFunction output
789 
790   @param qf          CeedQFunction
791   @param field_name  Name of QFunction field
792   @param size        Size of QFunction field, (num_comp * dim) for @ref CEED_EVAL_GRAD or
793                        (num_comp * 1) for @ref CEED_EVAL_NONE and @ref CEED_EVAL_INTERP
794   @param eval_mode   \ref CEED_EVAL_NONE to use values directly,
795                        \ref CEED_EVAL_INTERP to use interpolated values,
796                        \ref CEED_EVAL_GRAD to use gradients.
797 
798   @return An error code: 0 - success, otherwise - failure
799 
800   @ref User
801 **/
802 int CeedQFunctionAddOutput(CeedQFunction qf, const char *field_name,
803                            CeedInt size, CeedEvalMode eval_mode) {
804   if (qf->is_immutable)
805     // LCOV_EXCL_START
806     return CeedError(qf->ceed, CEED_ERROR_MAJOR,
807                      "QFunction cannot be changed after set as immutable");
808   // LCOV_EXCL_STOP
809   if (eval_mode == CEED_EVAL_WEIGHT)
810     // LCOV_EXCL_START
811     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
812                      "Cannot create QFunction output with "
813                      "CEED_EVAL_WEIGHT");
814   // LCOV_EXCL_STOP
815   int ierr = CeedQFunctionFieldSet(&qf->output_fields[qf->num_output_fields],
816                                    field_name, size, eval_mode);
817   CeedChk(ierr);
818   qf->num_output_fields++;
819   return CEED_ERROR_SUCCESS;
820 }
821 
822 /**
823   @brief Get the CeedQFunctionFields of a CeedQFunction
824 
825   Note: Calling this function asserts that setup is complete
826           and sets the CeedQFunction as immutable.
827 
828   @param qf                      CeedQFunction
829   @param[out] num_input_fields   Variable to store number of input fields
830   @param[out] input_fields       Variable to store input fields
831   @param[out] num_output_fields  Variable to store number of output fields
832   @param[out] output_fields      Variable to store output fields
833 
834   @return An error code: 0 - success, otherwise - failure
835 
836   @ref Advanced
837 **/
838 int CeedQFunctionGetFields(CeedQFunction qf, CeedInt *num_input_fields,
839                            CeedQFunctionField **input_fields,
840                            CeedInt *num_output_fields,
841                            CeedQFunctionField **output_fields) {
842   qf->is_immutable = true;
843   if (num_input_fields) *num_input_fields = qf->num_input_fields;
844   if (input_fields) *input_fields = qf->input_fields;
845   if (num_output_fields) *num_output_fields = qf->num_output_fields;
846   if (output_fields) *output_fields = qf->output_fields;
847   return CEED_ERROR_SUCCESS;
848 }
849 
850 /**
851   @brief Get the name of a CeedQFunctionField
852 
853   @param qf_field         CeedQFunctionField
854   @param[out] field_name  Variable to store the field name
855 
856   @return An error code: 0 - success, otherwise - failure
857 
858   @ref Advanced
859 **/
860 int CeedQFunctionFieldGetName(CeedQFunctionField qf_field, char **field_name) {
861   *field_name = (char *)qf_field->field_name;
862   return CEED_ERROR_SUCCESS;
863 }
864 
865 /**
866   @brief Get the number of components of a CeedQFunctionField
867 
868   @param qf_field   CeedQFunctionField
869   @param[out] size  Variable to store the size of the field
870 
871   @return An error code: 0 - success, otherwise - failure
872 
873   @ref Advanced
874 **/
875 int CeedQFunctionFieldGetSize(CeedQFunctionField qf_field, CeedInt *size) {
876   *size = qf_field->size;
877   return CEED_ERROR_SUCCESS;
878 }
879 
880 /**
881   @brief Get the CeedEvalMode of a CeedQFunctionField
882 
883   @param qf_field        CeedQFunctionField
884   @param[out] eval_mode  Variable to store the field evaluation mode
885 
886   @return An error code: 0 - success, otherwise - failure
887 
888   @ref Advanced
889 **/
890 int CeedQFunctionFieldGetEvalMode(CeedQFunctionField qf_field,
891                                   CeedEvalMode *eval_mode) {
892   *eval_mode = qf_field->eval_mode;
893   return CEED_ERROR_SUCCESS;
894 }
895 
896 /**
897   @brief Set global context for a CeedQFunction
898 
899   @param qf   CeedQFunction
900   @param ctx  Context data to set
901 
902   @return An error code: 0 - success, otherwise - failure
903 
904   @ref User
905 **/
906 int CeedQFunctionSetContext(CeedQFunction qf, CeedQFunctionContext ctx) {
907   int ierr;
908   ierr = CeedQFunctionContextDestroy(&qf->ctx); CeedChk(ierr);
909   qf->ctx = ctx;
910   if (ctx) {
911     ierr = CeedQFunctionContextReference(ctx); CeedChk(ierr);
912   }
913   return CEED_ERROR_SUCCESS;
914 }
915 
916 /**
917   @brief Set writability of CeedQFunctionContext when calling the `CeedQFunctionUser`.
918            The default value is 'is_writable == true'.
919 
920            Setting `is_writable == true` indicates the `CeedQFunctionUser` writes
921            into the CeedQFunctionContextData and requires memory syncronization
922            after calling `CeedQFunctionApply()`.
923 
924            Setting 'is_writable == false' asserts that `CeedQFunctionUser` does not
925            modify the CeedQFunctionContextData. Violating this assertion may lead
926            to inconsistent data.
927 
928            Setting `is_writable == false` may offer a performance improvement on GPU backends.
929 
930   @param qf           CeedQFunction
931   @param is_writable  Writability status
932 
933   @return An error code: 0 - success, otherwise - failure
934 
935   @ref User
936 **/
937 int CeedQFunctionSetContextWritable(CeedQFunction qf, bool is_writable) {
938   qf->is_context_writable = is_writable;
939   return CEED_ERROR_SUCCESS;
940 }
941 
942 /**
943   @brief Set estimated number of FLOPs per quadrature required to apply QFunction
944 
945   @param qf    QFunction to estimate FLOPs for
946   @param flops FLOPs per quadrature point estimate
947 
948   @ref Backend
949 **/
950 int CeedQFunctionSetUserFlopsEstimate(CeedQFunction qf, CeedSize flops) {
951   if (flops < 0)
952     // LCOV_EXCL_START
953     return CeedError(qf->ceed, CEED_ERROR_INCOMPATIBLE,
954                      "Must set non-negative FLOPs estimate");
955   // LCOV_EXCL_STOP
956   qf->user_flop_estimate = flops;
957   return CEED_ERROR_SUCCESS;
958 }
959 
960 /**
961   @brief View a CeedQFunction
962 
963   @param[in] qf      CeedQFunction to view
964   @param[in] stream  Stream to write; typically stdout/stderr or a file
965 
966   @return Error code: 0 - success, otherwise - failure
967 
968   @ref User
969 **/
970 int CeedQFunctionView(CeedQFunction qf, FILE *stream) {
971   int ierr;
972 
973   fprintf(stream, "%sCeedQFunction - %s\n",
974           qf->is_gallery ? "Gallery " : "User ",
975           qf->is_gallery ? qf->gallery_name : qf->kernel_name);
976 
977   fprintf(stream, "  %" CeedInt_FMT " input field%s:\n", qf->num_input_fields,
978           qf->num_input_fields>1 ? "s" : "");
979   for (CeedInt i=0; i<qf->num_input_fields; i++) {
980     ierr = CeedQFunctionFieldView(qf->input_fields[i], i, 1, stream);
981     CeedChk(ierr);
982   }
983 
984   fprintf(stream, "  %" CeedInt_FMT " output field%s:\n", qf->num_output_fields,
985           qf->num_output_fields>1 ? "s" : "");
986   for (CeedInt i=0; i<qf->num_output_fields; i++) {
987     ierr = CeedQFunctionFieldView(qf->output_fields[i], i, 0, stream);
988     CeedChk(ierr);
989   }
990   return CEED_ERROR_SUCCESS;
991 }
992 
993 /**
994   @brief Get the Ceed associated with a CeedQFunction
995 
996   @param qf              CeedQFunction
997   @param[out] ceed       Variable to store Ceed
998 
999   @return An error code: 0 - success, otherwise - failure
1000 
1001   @ref Advanced
1002 **/
1003 int CeedQFunctionGetCeed(CeedQFunction qf, Ceed *ceed) {
1004   *ceed = qf->ceed;
1005   return CEED_ERROR_SUCCESS;
1006 }
1007 
1008 /**
1009   @brief Apply the action of a CeedQFunction
1010 
1011   Note: Calling this function asserts that setup is complete
1012           and sets the CeedQFunction as immutable.
1013 
1014   @param qf      CeedQFunction
1015   @param Q       Number of quadrature points
1016   @param[in] u   Array of input CeedVectors
1017   @param[out] v  Array of output CeedVectors
1018 
1019   @return An error code: 0 - success, otherwise - failure
1020 
1021   @ref User
1022 **/
1023 int CeedQFunctionApply(CeedQFunction qf, CeedInt Q,
1024                        CeedVector *u, CeedVector *v) {
1025   int ierr;
1026   if (!qf->Apply)
1027     // LCOV_EXCL_START
1028     return CeedError(qf->ceed, CEED_ERROR_UNSUPPORTED,
1029                      "Backend does not support QFunctionApply");
1030   // LCOV_EXCL_STOP
1031   if (Q % qf->vec_length)
1032     // LCOV_EXCL_START
1033     return CeedError(qf->ceed, CEED_ERROR_DIMENSION,
1034                      "Number of quadrature points %" CeedInt_FMT " must be a "
1035                      "multiple of %" CeedInt_FMT, Q, qf->vec_length);
1036   // LCOV_EXCL_STOP
1037   qf->is_immutable = true;
1038   ierr = qf->Apply(qf, Q, u, v); CeedChk(ierr);
1039   return CEED_ERROR_SUCCESS;
1040 }
1041 
1042 /**
1043   @brief Destroy a CeedQFunction
1044 
1045   @param qf  CeedQFunction to destroy
1046 
1047   @return An error code: 0 - success, otherwise - failure
1048 
1049   @ref User
1050 **/
1051 int CeedQFunctionDestroy(CeedQFunction *qf) {
1052   int ierr;
1053 
1054   if (!*qf || --(*qf)->ref_count > 0) return CEED_ERROR_SUCCESS;
1055   // Backend destroy
1056   if ((*qf)->Destroy) {
1057     ierr = (*qf)->Destroy(*qf); CeedChk(ierr);
1058   }
1059   // Free fields
1060   for (CeedInt i=0; i<(*qf)->num_input_fields; i++) {
1061     ierr = CeedFree(&(*(*qf)->input_fields[i]).field_name); CeedChk(ierr);
1062     ierr = CeedFree(&(*qf)->input_fields[i]); CeedChk(ierr);
1063   }
1064   for (CeedInt i=0; i<(*qf)->num_output_fields; i++) {
1065     ierr = CeedFree(&(*(*qf)->output_fields[i]).field_name); CeedChk(ierr);
1066     ierr = CeedFree(&(*qf)->output_fields[i]); CeedChk(ierr);
1067   }
1068   ierr = CeedFree(&(*qf)->input_fields); CeedChk(ierr);
1069   ierr = CeedFree(&(*qf)->output_fields); CeedChk(ierr);
1070 
1071   // User context data object
1072   ierr = CeedQFunctionContextDestroy(&(*qf)->ctx); CeedChk(ierr);
1073 
1074   ierr = CeedFree(&(*qf)->source_path); CeedChk(ierr);
1075   ierr = CeedFree(&(*qf)->gallery_name); CeedChk(ierr);
1076   ierr = CeedFree(&(*qf)->kernel_name); CeedChk(ierr);
1077   ierr = CeedDestroy(&(*qf)->ceed); CeedChk(ierr);
1078   ierr = CeedFree(qf); CeedChk(ierr);
1079   return CEED_ERROR_SUCCESS;
1080 }
1081 
1082 /// @}
1083