xref: /libCEED/interface/ceed-qfunction.c (revision 60f77c51b5a8877aa3ab66b685cde4f5f7c967bb)
1 // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
2 // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
3 // reserved. See files LICENSE and NOTICE for details.
4 //
5 // This file is part of CEED, a collection of benchmarks, miniapps, software
6 // libraries and APIs for efficient high-order finite element and spectral
7 // element discretizations for exascale applications. For more information and
8 // source code availability see http://github.com/ceed.
9 //
10 // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
11 // a collaborative effort of two U.S. Department of Energy organizations (Office
12 // of Science and the National Nuclear Security Administration) responsible for
13 // the planning and preparation of a capable exascale ecosystem, including
14 // software, applications, hardware, advanced system engineering and early
15 // testbed platforms, in support of the nation's exascale computing imperative.
16 
17 #include <ceed-impl.h>
18 #include <ceed-backend.h>
19 #include <string.h>
20 #include <limits.h>
21 
22 /// @cond DOXYGEN_SKIP
23 static struct {
24   char name[CEED_MAX_RESOURCE_LEN];
25   char source[CEED_MAX_RESOURCE_LEN];
26   CeedInt vlength;
27   CeedQFunctionUser f;
28   int (*init)(Ceed ceed, const char *name, CeedQFunction qf);
29 } qfunctions[1024];
30 static size_t num_qfunctions;
31 /// @endcond
32 
33 /// @file
34 /// Implementation of public CeedQFunction interfaces
35 ///
36 /// @addtogroup CeedQFunction
37 /// @{
38 
39 /**
40   @brief Create a CeedQFunction for evaluating interior (volumetric) terms.
41 
42   @param ceed       A Ceed object where the CeedQFunction will be created
43   @param vlength    Vector length.  Caller must ensure that number of quadrature
44                     points is a multiple of vlength.
45   @param f          Function pointer to evaluate action at quadrature points.
46                     See \ref CeedQFunctionUser.
47   @param source     Absolute path to source of QFunction,
48                       "\abs_path\file.h:function_name"
49   @param[out] qf    Address of the variable where the newly created
50                       CeedQFunction will be stored
51 
52   @return An error code: 0 - success, otherwise - failure
53 
54   See \ref CeedQFunctionUser for details on the call-back function @a f's
55     arguments.
56 
57   @ref Basic
58 **/
59 int CeedQFunctionCreateInterior(Ceed ceed, CeedInt vlength, CeedQFunctionUser f,
60                                 const char *source, CeedQFunction *qf) {
61   int ierr;
62   char *source_copy;
63 
64   if (!ceed->QFunctionCreate) {
65     Ceed delegate;
66     ierr = CeedGetObjectDelegate(ceed, &delegate, "QFunction"); CeedChk(ierr);
67 
68     if (!delegate)
69       // LCOV_EXCL_START
70       return CeedError(ceed, 1, "Backend does not support QFunctionCreate");
71     // LCOV_EXCL_STOP
72 
73     ierr = CeedQFunctionCreateInterior(delegate, vlength, f, source, qf);
74     CeedChk(ierr);
75     return 0;
76   }
77 
78   ierr = CeedCalloc(1,qf); CeedChk(ierr);
79   (*qf)->ceed = ceed;
80   ceed->refcount++;
81   (*qf)->refcount = 1;
82   (*qf)->vlength = vlength;
83   (*qf)->identity = 0;
84   (*qf)->function = f;
85   size_t slen = strlen(source) + 1;
86   ierr = CeedMalloc(slen, &source_copy); CeedChk(ierr);
87   memcpy(source_copy, source, slen);
88   (*qf)->sourcepath = source_copy;
89   ierr = CeedCalloc(16, &(*qf)->inputfields); CeedChk(ierr);
90   ierr = CeedCalloc(16, &(*qf)->outputfields); CeedChk(ierr);
91   ierr = ceed->QFunctionCreate(*qf); CeedChk(ierr);
92   return 0;
93 }
94 
95 /**
96   @brief Register a gallery QFunction
97 
98   @param name    Name for this backend to respond to
99   @param source  Absolute path to source of QFunction,
100                    "\path\CEED_DIR\gallery\folder\file.h:function_name"
101   @param vlength Vector length.  Caller must ensure that number of quadrature
102                    points is a multiple of vlength.
103   @param f       Function pointer to evaluate action at quadrature points.
104                    See \ref CeedQFunctionUser.
105   @param init    Initialization function called by CeedQFunctionInit() when the
106                    QFunction is selected.
107 
108   @return An error code: 0 - success, otherwise - failure
109 
110   @ref Advanced
111 **/
112 int CeedQFunctionRegister(const char *name, const char *source,
113                           CeedInt vlength, CeedQFunctionUser f,
114                           int (*init)(Ceed, const char *, CeedQFunction)) {
115   if (num_qfunctions >= sizeof(qfunctions) / sizeof(qfunctions[0]))
116     // LCOV_EXCL_START
117     return CeedError(NULL, 1, "Too many gallery QFunctions");
118   // LCOV_EXCL_STOP
119 
120   strncpy(qfunctions[num_qfunctions].name, name, CEED_MAX_RESOURCE_LEN);
121   qfunctions[num_qfunctions].name[CEED_MAX_RESOURCE_LEN-1] = 0;
122   strncpy(qfunctions[num_qfunctions].source, source, CEED_MAX_RESOURCE_LEN);
123   qfunctions[num_qfunctions].source[CEED_MAX_RESOURCE_LEN-1] = 0;
124   qfunctions[num_qfunctions].vlength = vlength;
125   qfunctions[num_qfunctions].f = f;
126   qfunctions[num_qfunctions].init = init;
127   num_qfunctions++;
128   return 0;
129 }
130 
131 /**
132   @brief Create a CeedQFunction for evaluating interior (volumetric) terms by name.
133 
134   @param ceed       A Ceed object where the CeedQFunction will be created
135   @param name       Name of QFunction to use from gallery
136   @param[out] qf    Address of the variable where the newly created
137                       CeedQFunction will be stored
138 
139   @return An error code: 0 - success, otherwise - failure
140 
141   @ref Basic
142 **/
143 int CeedQFunctionCreateInteriorByName(Ceed ceed,  const char *name,
144                                       CeedQFunction *qf) {
145   int ierr;
146   size_t matchlen = 0, matchidx = UINT_MAX;
147 
148   // Find matching backend
149   if (!name) return CeedError(NULL, 1, "No QFunction name provided");
150   for (size_t i=0; i<num_qfunctions; i++) {
151     size_t n;
152     const char *currname = qfunctions[i].name;
153     for (n = 0; currname[n] && currname[n] == name[n]; n++) {}
154     if (n > matchlen) {
155       matchlen = n;
156       matchidx = i;
157     }
158   }
159   if (!matchlen)
160     // LCOV_EXCL_START
161     return CeedError(NULL, 1, "No suitable gallery QFunction");
162   // LCOV_EXCL_STOP
163 
164   // Create QFunction
165   ierr = CeedQFunctionCreateInterior(ceed, qfunctions[matchidx].vlength,
166                                      qfunctions[matchidx].f,
167                                      qfunctions[matchidx].source, qf);
168   CeedChk(ierr);
169 
170   // QFunction specific setup
171   ierr = qfunctions[matchidx].init(ceed, name, *qf); CeedChk(ierr);
172 
173   return 0;
174 }
175 
176 /**
177   @brief Create an identity CeedQFunction. Inputs are written into outputs in
178            the order given. This is useful for CeedOperators that can be
179            represented with only the action of a CeedRestriction and CeedBasis,
180            such as restriction and prolongation operators for p-multigrid.
181            Backends may optimize CeedOperators with this CeedQFunction to avoid
182            the copy of input data to output fields by using the same memory
183            location for both.
184 
185   @param ceed        A Ceed object where the CeedQFunction will be created
186   @param[in] size    Size of the qfunction fields
187   @param[in] inmode  CeedEvalMode for input to CeedQFunction
188   @param[in] outmode CeedEvalMode for output to CeedQFunction
189   @param[out] qf     Address of the variable where the newly created
190                        CeedQFunction will be stored
191 
192   @return An error code: 0 - success, otherwise - failure
193 
194   @ref Basic
195 **/
196 int CeedQFunctionCreateIdentity(Ceed ceed, CeedInt size, CeedEvalMode inmode,
197                                 CeedEvalMode outmode, CeedQFunction *qf) {
198   int ierr;
199 
200   if (inmode == CEED_EVAL_NONE && outmode == CEED_EVAL_NONE)
201     // LCOV_EXCL_START
202     return CeedError(ceed, 1, "CEED_EVAL_NONE for a both the input and "
203                      "output does not make sense with an identity QFunction");
204   // LCOV_EXCL_STOP
205 
206   ierr = CeedQFunctionCreateInteriorByName(ceed, "Identity", qf); CeedChk(ierr);
207   ierr = CeedQFunctionAddInput(*qf, "input", 1, inmode); CeedChk(ierr);
208   ierr = CeedQFunctionAddOutput(*qf, "output", 1, outmode); CeedChk(ierr);
209 
210   (*qf)->identity = 1;
211   if (size > 1) {
212     CeedInt *ctx;
213     ierr = CeedCalloc(1, &ctx); CeedChk(ierr);
214     ctx[0] = size;
215     ierr = CeedQFunctionSetContext(*qf, ctx, sizeof(ctx)); CeedChk(ierr);
216     (*qf)->inputfields[0]->size = size;
217     (*qf)->outputfields[0]->size = size;
218   }
219 
220   return 0;
221 }
222 
223 /**
224   @brief Set a CeedQFunction field, used by CeedQFunctionAddInput/Output
225 
226   @param f          CeedQFunctionField
227   @param fieldname  Name of QFunction field
228   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
229                       1 for CEED_EVAL_NONE, CEED_EVAL_INTERP, and CEED_EVAL_WEIGHT)
230   @param emode      \ref CEED_EVAL_NONE to use values directly,
231                       \ref CEED_EVAL_INTERP to use interpolated values,
232                       \ref CEED_EVAL_GRAD to use gradients,
233                       \ref CEED_EVAL_WEIGHT to use quadrature weights.
234 
235   @return An error code: 0 - success, otherwise - failure
236 
237   @ref Developer
238 **/
239 static int CeedQFunctionFieldSet(CeedQFunctionField *f,const char *fieldname,
240                                  CeedInt size, CeedEvalMode emode) {
241   size_t len = strlen(fieldname);
242   char *tmp;
243   int ierr;
244   ierr = CeedCalloc(1,f); CeedChk(ierr);
245 
246   ierr = CeedCalloc(len+1, &tmp); CeedChk(ierr);
247   memcpy(tmp, fieldname, len+1);
248   (*f)->fieldname = tmp;
249   (*f)->size = size;
250   (*f)->emode = emode;
251   return 0;
252 }
253 
254 /**
255   @brief Add a CeedQFunction input
256 
257   @param qf         CeedQFunction
258   @param fieldname  Name of QFunction field
259   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
260                       1 for CEED_EVAL_NONE and CEED_EVAL_INTERP)
261   @param emode      \ref CEED_EVAL_NONE to use values directly,
262                       \ref CEED_EVAL_INTERP to use interpolated values,
263                       \ref CEED_EVAL_GRAD to use gradients.
264 
265   @return An error code: 0 - success, otherwise - failure
266 
267   @ref Basic
268 **/
269 int CeedQFunctionAddInput(CeedQFunction qf, const char *fieldname, CeedInt size,
270                           CeedEvalMode emode) {
271   int ierr = CeedQFunctionFieldSet(&qf->inputfields[qf->numinputfields],
272                                    fieldname, size, emode);
273   CeedChk(ierr);
274   qf->numinputfields++;
275   return 0;
276 }
277 
278 /**
279   @brief Add a CeedQFunction output
280 
281   @param qf         CeedQFunction
282   @param fieldname  Name of QFunction field
283   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
284                       1 for CEED_EVAL_NONE and CEED_EVAL_INTERP)
285   @param emode      \ref CEED_EVAL_NONE to use values directly,
286                       \ref CEED_EVAL_INTERP to use interpolated values,
287                       \ref CEED_EVAL_GRAD to use gradients.
288 
289   @return An error code: 0 - success, otherwise - failure
290 
291   @ref Basic
292 **/
293 int CeedQFunctionAddOutput(CeedQFunction qf, const char *fieldname,
294                            CeedInt size, CeedEvalMode emode) {
295   if (emode == CEED_EVAL_WEIGHT)
296     // LCOV_EXCL_START
297     return CeedError(qf->ceed, 1, "Cannot create QFunction output with "
298                      "CEED_EVAL_WEIGHT");
299   // LCOV_EXCL_STOP
300   int ierr = CeedQFunctionFieldSet(&qf->outputfields[qf->numoutputfields],
301                                    fieldname, size, emode);
302   CeedChk(ierr);
303   qf->numoutputfields++;
304   return 0;
305 }
306 
307 /**
308   @brief Get the Ceed associated with a CeedQFunction
309 
310   @param qf              CeedQFunction
311   @param[out] ceed       Variable to store Ceed
312 
313   @return An error code: 0 - success, otherwise - failure
314 
315   @ref Advanced
316 **/
317 
318 int CeedQFunctionGetCeed(CeedQFunction qf, Ceed *ceed) {
319   *ceed = qf->ceed;
320   return 0;
321 }
322 
323 /**
324   @brief Get the vector length of a CeedQFunction
325 
326   @param qf            CeedQFunction
327   @param[out] vlength  Variable to store vector length
328 
329   @return An error code: 0 - success, otherwise - failure
330 
331   @ref Advanced
332 **/
333 
334 int CeedQFunctionGetVectorLength(CeedQFunction qf, CeedInt *vlength) {
335   *vlength = qf->vlength;
336   return 0;
337 }
338 
339 /**
340   @brief Get the number of inputs and outputs to a CeedQFunction
341 
342   @param qf              CeedQFunction
343   @param[out] numinput   Variable to store number of input fields
344   @param[out] numoutput  Variable to store number of output fields
345 
346   @return An error code: 0 - success, otherwise - failure
347 
348   @ref Advanced
349 **/
350 
351 int CeedQFunctionGetNumArgs(CeedQFunction qf, CeedInt *numinput,
352                             CeedInt *numoutput) {
353   if (numinput) *numinput = qf->numinputfields;
354   if (numoutput) *numoutput = qf->numoutputfields;
355   return 0;
356 }
357 
358 /**
359   @brief Get the source path string for a CeedQFunction
360 
361   @param qf              CeedQFunction
362   @param[out] source     Variable to store source path string
363 
364   @return An error code: 0 - success, otherwise - failure
365 
366   @ref Advanced
367 **/
368 
369 int CeedQFunctionGetSourcePath(CeedQFunction qf, char **source) {
370   *source = (char *) qf->sourcepath;
371   return 0;
372 }
373 
374 /**
375   @brief Get the User Function for a CeedQFunction
376 
377   @param qf              CeedQFunction
378   @param[out] f          Variable to store user function
379 
380   @return An error code: 0 - success, otherwise - failure
381 
382   @ref Advanced
383 **/
384 
385 int CeedQFunctionGetUserFunction(CeedQFunction qf, CeedQFunctionUser *f) {
386   *f = qf->function;
387   return 0;
388 }
389 
390 /**
391   @brief Get global context size for a CeedQFunction
392 
393   @param qf              CeedQFunction
394   @param[out] ctxsize    Variable to store size of context data values
395 
396   @return An error code: 0 - success, otherwise - failure
397 
398   @ref Advanced
399 **/
400 
401 int CeedQFunctionGetContextSize(CeedQFunction qf, size_t *ctxsize) {
402   if (qf->fortranstatus) {
403     fContext *fctx = qf->ctx;
404     *ctxsize = fctx->innerctxsize;
405   } else {
406     *ctxsize = qf->ctxsize;
407   }
408   return 0;
409 }
410 
411 /**
412   @brief Get global context for a CeedQFunction
413 
414   @param qf              CeedQFunction
415   @param[out] ctx        Variable to store context data values
416 
417   @return An error code: 0 - success, otherwise - failure
418 
419   @ref Advanced
420 **/
421 
422 int CeedQFunctionGetContext(CeedQFunction qf, void **ctx) {
423   *ctx = qf->ctx;
424   return 0;
425 }
426 
427 /**
428   @brief Determine if Fortran interface was used
429 
430   @param qf                  CeedQFunction
431   @param[out] fortranstatus  Variable to store Fortran status
432 
433   @return An error code: 0 - success, otherwise - failure
434 
435   @ref Advanced
436 **/
437 
438 int CeedQFunctionGetFortranStatus(CeedQFunction qf, bool *fortranstatus) {
439   *fortranstatus = qf->fortranstatus;
440   return 0;
441 }
442 
443 /**
444   @brief Determine if QFunction is identity
445 
446   @param qf               CeedQFunction
447   @param[out] identity    Variable to store identity status
448 
449   @return An error code: 0 - success, otherwise - failure
450 
451   @ref Advanced
452 **/
453 
454 int CeedQFunctionGetIdentityStatus(CeedQFunction qf, bool *identity) {
455   *identity = qf->identity;
456   return 0;
457 }
458 
459 /**
460   @brief Get true user context for a CeedQFunction
461 
462   @param qf              CeedQFunction
463   @param[out] ctx        Variable to store context data values
464 
465   @return An error code: 0 - success, otherwise - failure
466 
467   @ref Advanced
468 **/
469 
470 int CeedQFunctionGetInnerContext(CeedQFunction qf, void **ctx) {
471   if (qf->fortranstatus) {
472     fContext *fctx = qf->ctx;
473     *ctx = fctx->innerctx;
474   } else {
475     *ctx = qf->ctx;
476   }
477 
478 
479   return 0;
480 }
481 
482 /**
483   @brief Get backend data of a CeedQFunction
484 
485   @param qf              CeedQFunction
486   @param[out] data       Variable to store data
487 
488   @return An error code: 0 - success, otherwise - failure
489 
490   @ref Advanced
491 **/
492 
493 int CeedQFunctionGetData(CeedQFunction qf, void **data) {
494   *data = qf->data;
495   return 0;
496 }
497 
498 /**
499   @brief Set backend data of a CeedQFunction
500 
501   @param[out] qf         CeedQFunction
502   @param data            Data to set
503 
504   @return An error code: 0 - success, otherwise - failure
505 
506   @ref Advanced
507 **/
508 
509 int CeedQFunctionSetData(CeedQFunction qf, void **data) {
510   qf->data = *data;
511   return 0;
512 }
513 
514 /**
515   @brief Set global context for a CeedQFunction
516 
517   @param qf       CeedQFunction
518   @param ctx      Context data to set
519   @param ctxsize  Size of context data values
520 
521   @return An error code: 0 - success, otherwise - failure
522 
523   @ref Basic
524 **/
525 int CeedQFunctionSetContext(CeedQFunction qf, void *ctx, size_t ctxsize) {
526   qf->ctx = ctx;
527   qf->ctxsize = ctxsize;
528   return 0;
529 }
530 
531 /**
532   @brief Apply the action of a CeedQFunction
533 
534   @param qf      CeedQFunction
535   @param Q       Number of quadrature points
536   @param[in] u   Array of input data arrays
537   @param[out] v  Array of output data arrays
538 
539   @return An error code: 0 - success, otherwise - failure
540 
541   @ref Advanced
542 **/
543 int CeedQFunctionApply(CeedQFunction qf, CeedInt Q,
544                        CeedVector *u, CeedVector *v) {
545   int ierr;
546   if (!qf->Apply)
547     // LCOV_EXCL_START
548     return CeedError(qf->ceed, 1, "Backend does not support QFunctionApply");
549   // LCOV_EXCL_STOP
550   if (Q % qf->vlength)
551     // LCOV_EXCL_START
552     return CeedError(qf->ceed, 2, "Number of quadrature points %d must be a "
553                      "multiple of %d", Q, qf->vlength);
554   // LCOV_EXCL_STOP
555   ierr = qf->Apply(qf, Q, u, v); CeedChk(ierr);
556   return 0;
557 }
558 
559 /**
560   @brief Get the CeedQFunctionFields of a CeedQFunction
561 
562   @param qf                 CeedQFunction
563   @param[out] inputfields   Variable to store inputfields
564   @param[out] outputfields  Variable to store outputfields
565 
566   @return An error code: 0 - success, otherwise - failure
567 
568   @ref Advanced
569 **/
570 
571 int CeedQFunctionGetFields(CeedQFunction qf, CeedQFunctionField **inputfields,
572                            CeedQFunctionField **outputfields) {
573   if (inputfields)
574     *inputfields = qf->inputfields;
575   if (outputfields)
576     *outputfields = qf->outputfields;
577   return 0;
578 }
579 
580 /**
581   @brief Get the name of a CeedQFunctionField
582 
583   @param qffield         CeedQFunctionField
584   @param[out] fieldname  Variable to store the field name
585 
586   @return An error code: 0 - success, otherwise - failure
587 
588   @ref Advanced
589 **/
590 
591 int CeedQFunctionFieldGetName(CeedQFunctionField qffield, char **fieldname) {
592   *fieldname = (char *)qffield->fieldname;
593   return 0;
594 }
595 
596 /**
597   @brief Get the number of components of a CeedQFunctionField
598 
599   @param qffield    CeedQFunctionField
600   @param[out] size  Variable to store the size of the field
601 
602   @return An error code: 0 - success, otherwise - failure
603 
604   @ref Advanced
605 **/
606 
607 int CeedQFunctionFieldGetSize(CeedQFunctionField qffield, CeedInt *size) {
608   *size = qffield->size;
609   return 0;
610 }
611 
612 /**
613   @brief Get the CeedEvalMode of a CeedQFunctionField
614 
615   @param qffield         CeedQFunctionField
616   @param[out] emode      Variable to store the field evaluation mode
617 
618   @return An error code: 0 - success, otherwise - failure
619 
620   @ref Advanced
621 **/
622 
623 int CeedQFunctionFieldGetEvalMode(CeedQFunctionField qffield,
624                                   CeedEvalMode *emode) {
625   *emode = qffield->emode;
626   return 0;
627 }
628 
629 /**
630   @brief Destroy a CeedQFunction
631 
632   @param qf CeedQFunction to destroy
633 
634   @return An error code: 0 - success, otherwise - failure
635 
636   @ref Basic
637 **/
638 int CeedQFunctionDestroy(CeedQFunction *qf) {
639   int ierr;
640 
641   if (!*qf || --(*qf)->refcount > 0)
642     return 0;
643   // Backend destroy
644   if ((*qf)->Destroy) {
645     ierr = (*qf)->Destroy(*qf); CeedChk(ierr);
646   }
647   // Free fields
648   for (int i=0; i<(*qf)->numinputfields; i++) {
649     ierr = CeedFree(&(*(*qf)->inputfields[i]).fieldname); CeedChk(ierr);
650     ierr = CeedFree(&(*qf)->inputfields[i]); CeedChk(ierr);
651   }
652   for (int i=0; i<(*qf)->numoutputfields; i++) {
653     ierr = CeedFree(&(*(*qf)->outputfields[i]).fieldname); CeedChk(ierr);
654     ierr = CeedFree(&(*qf)->outputfields[i]); CeedChk(ierr);
655   }
656   ierr = CeedFree(&(*qf)->inputfields); CeedChk(ierr);
657   ierr = CeedFree(&(*qf)->outputfields); CeedChk(ierr);
658   // Free ctx if identity
659   if ((*qf)->identity) {
660     ierr = CeedFree(&(*qf)->ctx); CeedChk(ierr);
661   }
662 
663   ierr = CeedFree(&(*qf)->sourcepath); CeedChk(ierr);
664   ierr = CeedDestroy(&(*qf)->ceed); CeedChk(ierr);
665   ierr = CeedFree(qf); CeedChk(ierr);
666   return 0;
667 }
668 
669 /// @}
670