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