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