xref: /libCEED/interface/ceed-qfunction.c (revision dc7d240c1c3ecbc40e893ea38e37c8e19d48593c)
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 size       Size of the qfunction fields
187   @param[out] qf    Address of the variable where the newly created
188                       CeedQFunction will be stored
189 
190   @return An error code: 0 - success, otherwise - failure
191 
192   @ref Basic
193 **/
194 int CeedQFunctionCreateIdentity(Ceed ceed, CeedInt size, CeedQFunction *qf) {
195   int ierr;
196 
197   ierr = CeedQFunctionCreateInteriorByName(ceed, "Identity", qf); CeedChk(ierr);
198 
199   (*qf)->identity = 1;
200   if (size > 1) {
201     CeedInt *ctx;
202     ierr = CeedCalloc(1, &ctx); CeedChk(ierr);
203     ctx[0] = size;
204     ierr = CeedQFunctionSetContext(*qf, ctx, sizeof(ctx)); CeedChk(ierr);
205     (*qf)->inputfields[0]->size = size;
206     (*qf)->outputfields[0]->size = size;
207   }
208 
209   return 0;
210 }
211 
212 /**
213   @brief Set a CeedQFunction field, used by CeedQFunctionAddInput/Output
214 
215   @param f          CeedQFunctionField
216   @param fieldname  Name of QFunction field
217   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
218                       1 for CEED_EVAL_NONE, CEED_EVAL_INTERP, and CEED_EVAL_WEIGHT)
219   @param emode      \ref CEED_EVAL_NONE to use values directly,
220                       \ref CEED_EVAL_INTERP to use interpolated values,
221                       \ref CEED_EVAL_GRAD to use gradients,
222                       \ref CEED_EVAL_WEIGHT to use quadrature weights.
223 
224   @return An error code: 0 - success, otherwise - failure
225 
226   @ref Developer
227 **/
228 static int CeedQFunctionFieldSet(CeedQFunctionField *f,const char *fieldname,
229                                  CeedInt size, CeedEvalMode emode) {
230   size_t len = strlen(fieldname);
231   char *tmp;
232   int ierr;
233   ierr = CeedCalloc(1,f); CeedChk(ierr);
234 
235   ierr = CeedCalloc(len+1, &tmp); CeedChk(ierr);
236   memcpy(tmp, fieldname, len+1);
237   (*f)->fieldname = tmp;
238   (*f)->size = size;
239   (*f)->emode = emode;
240   return 0;
241 }
242 
243 /**
244   @brief Add a CeedQFunction input
245 
246   @param qf         CeedQFunction
247   @param fieldname  Name of QFunction field
248   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
249                       1 for CEED_EVAL_NONE and CEED_EVAL_INTERP)
250   @param emode      \ref CEED_EVAL_NONE to use values directly,
251                       \ref CEED_EVAL_INTERP to use interpolated values,
252                       \ref CEED_EVAL_GRAD to use gradients.
253 
254   @return An error code: 0 - success, otherwise - failure
255 
256   @ref Basic
257 **/
258 int CeedQFunctionAddInput(CeedQFunction qf, const char *fieldname, CeedInt size,
259                           CeedEvalMode emode) {
260   int ierr = CeedQFunctionFieldSet(&qf->inputfields[qf->numinputfields],
261                                    fieldname, size, emode);
262   CeedChk(ierr);
263   qf->numinputfields++;
264   return 0;
265 }
266 
267 /**
268   @brief Add a CeedQFunction output
269 
270   @param qf         CeedQFunction
271   @param fieldname  Name of QFunction field
272   @param size       Size of QFunction field, ncomp * (dim for CEED_EVAL_GRAD or
273                       1 for CEED_EVAL_NONE and CEED_EVAL_INTERP)
274   @param emode      \ref CEED_EVAL_NONE to use values directly,
275                       \ref CEED_EVAL_INTERP to use interpolated values,
276                       \ref CEED_EVAL_GRAD to use gradients.
277 
278   @return An error code: 0 - success, otherwise - failure
279 
280   @ref Basic
281 **/
282 int CeedQFunctionAddOutput(CeedQFunction qf, const char *fieldname,
283                            CeedInt size, CeedEvalMode emode) {
284   if (emode == CEED_EVAL_WEIGHT)
285     // LCOV_EXCL_START
286     return CeedError(qf->ceed, 1, "Cannot create QFunction output with "
287                      "CEED_EVAL_WEIGHT");
288   // LCOV_EXCL_STOP
289   int ierr = CeedQFunctionFieldSet(&qf->outputfields[qf->numoutputfields],
290                                    fieldname, size, emode);
291   CeedChk(ierr);
292   qf->numoutputfields++;
293   return 0;
294 }
295 
296 /**
297   @brief Get the Ceed associated with a CeedQFunction
298 
299   @param qf              CeedQFunction
300   @param[out] ceed       Variable to store Ceed
301 
302   @return An error code: 0 - success, otherwise - failure
303 
304   @ref Advanced
305 **/
306 
307 int CeedQFunctionGetCeed(CeedQFunction qf, Ceed *ceed) {
308   *ceed = qf->ceed;
309   return 0;
310 }
311 
312 /**
313   @brief Get the vector length of a CeedQFunction
314 
315   @param qf            CeedQFunction
316   @param[out] vlength  Variable to store vector length
317 
318   @return An error code: 0 - success, otherwise - failure
319 
320   @ref Advanced
321 **/
322 
323 int CeedQFunctionGetVectorLength(CeedQFunction qf, CeedInt *vlength) {
324   *vlength = qf->vlength;
325   return 0;
326 }
327 
328 /**
329   @brief Get the number of inputs and outputs to a CeedQFunction
330 
331   @param qf              CeedQFunction
332   @param[out] numinput   Variable to store number of input fields
333   @param[out] numoutput  Variable to store number of output fields
334 
335   @return An error code: 0 - success, otherwise - failure
336 
337   @ref Advanced
338 **/
339 
340 int CeedQFunctionGetNumArgs(CeedQFunction qf, CeedInt *numinput,
341                             CeedInt *numoutput) {
342   if (numinput) *numinput = qf->numinputfields;
343   if (numoutput) *numoutput = qf->numoutputfields;
344   return 0;
345 }
346 
347 /**
348   @brief Get the source path string for a CeedQFunction
349 
350   @param qf              CeedQFunction
351   @param[out] source     Variable to store source path string
352 
353   @return An error code: 0 - success, otherwise - failure
354 
355   @ref Advanced
356 **/
357 
358 int CeedQFunctionGetSourcePath(CeedQFunction qf, char **source) {
359   *source = (char *) qf->sourcepath;
360   return 0;
361 }
362 
363 /**
364   @brief Get the User Function for a CeedQFunction
365 
366   @param qf              CeedQFunction
367   @param[out] f          Variable to store user function
368 
369   @return An error code: 0 - success, otherwise - failure
370 
371   @ref Advanced
372 **/
373 
374 int CeedQFunctionGetUserFunction(CeedQFunction qf, int (**f)()) {
375   *f = (int (*)())qf->function;
376   return 0;
377 }
378 
379 /**
380   @brief Get global context size for a CeedQFunction
381 
382   @param qf              CeedQFunction
383   @param[out] ctxsize    Variable to store size of context data values
384 
385   @return An error code: 0 - success, otherwise - failure
386 
387   @ref Advanced
388 **/
389 
390 int CeedQFunctionGetContextSize(CeedQFunction qf, size_t *ctxsize) {
391   if (qf->fortranstatus) {
392     fContext *fctx = qf->ctx;
393     *ctxsize = fctx->innerctxsize;
394   } else {
395     *ctxsize = qf->ctxsize;
396   }
397   return 0;
398 }
399 
400 /**
401   @brief Get global context for a CeedQFunction
402 
403   @param qf              CeedQFunction
404   @param[out] ctx        Variable to store context data values
405 
406   @return An error code: 0 - success, otherwise - failure
407 
408   @ref Advanced
409 **/
410 
411 int CeedQFunctionGetContext(CeedQFunction qf, void **ctx) {
412   *ctx = qf->ctx;
413   return 0;
414 }
415 
416 /**
417   @brief Determine if Fortran interface was used
418 
419   @param qf                  CeedQFunction
420   @param[out] fortranstatus  Variable to store Fortran status
421 
422   @return An error code: 0 - success, otherwise - failure
423 
424   @ref Advanced
425 **/
426 
427 int CeedQFunctionGetFortranStatus(CeedQFunction qf, bool *fortranstatus) {
428   *fortranstatus = qf->fortranstatus;
429   return 0;
430 }
431 
432 /**
433   @brief Determine if QFunction is identity
434 
435   @param qf               CeedQFunction
436   @param[out] identity    Variable to store identity status
437 
438   @return An error code: 0 - success, otherwise - failure
439 
440   @ref Advanced
441 **/
442 
443 int CeedQFunctionGetIdentityStatus(CeedQFunction qf, bool *identity) {
444   *identity = qf->identity;
445   return 0;
446 }
447 
448 /**
449   @brief Get true user context for a CeedQFunction
450 
451   @param qf              CeedQFunction
452   @param[out] ctx        Variable to store context data values
453 
454   @return An error code: 0 - success, otherwise - failure
455 
456   @ref Advanced
457 **/
458 
459 int CeedQFunctionGetInnerContext(CeedQFunction qf, void **ctx) {
460   if (qf->fortranstatus) {
461     fContext *fctx = qf->ctx;
462     *ctx = fctx->innerctx;
463   } else {
464     *ctx = qf->ctx;
465   }
466 
467 
468   return 0;
469 }
470 
471 /**
472   @brief Get backend data of a CeedQFunction
473 
474   @param qf              CeedQFunction
475   @param[out] data       Variable to store data
476 
477   @return An error code: 0 - success, otherwise - failure
478 
479   @ref Advanced
480 **/
481 
482 int CeedQFunctionGetData(CeedQFunction qf, void **data) {
483   *data = qf->data;
484   return 0;
485 }
486 
487 /**
488   @brief Set backend data of a CeedQFunction
489 
490   @param[out] qf         CeedQFunction
491   @param data            Data to set
492 
493   @return An error code: 0 - success, otherwise - failure
494 
495   @ref Advanced
496 **/
497 
498 int CeedQFunctionSetData(CeedQFunction qf, void **data) {
499   qf->data = *data;
500   return 0;
501 }
502 
503 /**
504   @brief Set global context for a CeedQFunction
505 
506   @param qf       CeedQFunction
507   @param ctx      Context data to set
508   @param ctxsize  Size of context data values
509 
510   @return An error code: 0 - success, otherwise - failure
511 
512   @ref Basic
513 **/
514 int CeedQFunctionSetContext(CeedQFunction qf, void *ctx, size_t ctxsize) {
515   qf->ctx = ctx;
516   qf->ctxsize = ctxsize;
517   return 0;
518 }
519 
520 /**
521   @brief Apply the action of a CeedQFunction
522 
523   @param qf      CeedQFunction
524   @param Q       Number of quadrature points
525   @param[in] u   Array of input data arrays
526   @param[out] v  Array of output data arrays
527 
528   @return An error code: 0 - success, otherwise - failure
529 
530   @ref Advanced
531 **/
532 int CeedQFunctionApply(CeedQFunction qf, CeedInt Q,
533                        CeedVector *u, CeedVector *v) {
534   int ierr;
535   if (!qf->Apply)
536     // LCOV_EXCL_START
537     return CeedError(qf->ceed, 1, "Backend does not support QFunctionApply");
538   // LCOV_EXCL_STOP
539   if (Q % qf->vlength)
540     // LCOV_EXCL_START
541     return CeedError(qf->ceed, 2, "Number of quadrature points %d must be a "
542                      "multiple of %d", Q, qf->vlength);
543   // LCOV_EXCL_STOP
544   ierr = qf->Apply(qf, Q, u, v); CeedChk(ierr);
545   return 0;
546 }
547 
548 /**
549   @brief Get the CeedQFunctionFields of a CeedQFunction
550 
551   @param qf                 CeedQFunction
552   @param[out] inputfields   Variable to store inputfields
553   @param[out] outputfields  Variable to store outputfields
554 
555   @return An error code: 0 - success, otherwise - failure
556 
557   @ref Advanced
558 **/
559 
560 int CeedQFunctionGetFields(CeedQFunction qf, CeedQFunctionField **inputfields,
561                            CeedQFunctionField **outputfields) {
562   if (inputfields)
563     *inputfields = qf->inputfields;
564   if (outputfields)
565     *outputfields = qf->outputfields;
566   return 0;
567 }
568 
569 /**
570   @brief Get the name of a CeedQFunctionField
571 
572   @param qffield         CeedQFunctionField
573   @param[out] fieldname  Variable to store the field name
574 
575   @return An error code: 0 - success, otherwise - failure
576 
577   @ref Advanced
578 **/
579 
580 int CeedQFunctionFieldGetName(CeedQFunctionField qffield, char **fieldname) {
581   *fieldname = (char *)qffield->fieldname;
582   return 0;
583 }
584 
585 /**
586   @brief Get the number of components of a CeedQFunctionField
587 
588   @param qffield    CeedQFunctionField
589   @param[out] size  Variable to store the size of the field
590 
591   @return An error code: 0 - success, otherwise - failure
592 
593   @ref Advanced
594 **/
595 
596 int CeedQFunctionFieldGetSize(CeedQFunctionField qffield, CeedInt *size) {
597   *size = qffield->size;
598   return 0;
599 }
600 
601 /**
602   @brief Get the CeedEvalMode of a CeedQFunctionField
603 
604   @param qffield         CeedQFunctionField
605   @param[out] emode      Variable to store the field evaluation mode
606 
607   @return An error code: 0 - success, otherwise - failure
608 
609   @ref Advanced
610 **/
611 
612 int CeedQFunctionFieldGetEvalMode(CeedQFunctionField qffield,
613                                   CeedEvalMode *emode) {
614   *emode = qffield->emode;
615   return 0;
616 }
617 
618 /**
619   @brief Destroy a CeedQFunction
620 
621   @param qf CeedQFunction to destroy
622 
623   @return An error code: 0 - success, otherwise - failure
624 
625   @ref Basic
626 **/
627 int CeedQFunctionDestroy(CeedQFunction *qf) {
628   int ierr;
629 
630   if (!*qf || --(*qf)->refcount > 0)
631     return 0;
632   // Backend destroy
633   if ((*qf)->Destroy) {
634     ierr = (*qf)->Destroy(*qf); CeedChk(ierr);
635   }
636   // Free fields
637   for (int i=0; i<(*qf)->numinputfields; i++) {
638     ierr = CeedFree(&(*(*qf)->inputfields[i]).fieldname); CeedChk(ierr);
639     ierr = CeedFree(&(*qf)->inputfields[i]); CeedChk(ierr);
640   }
641   for (int i=0; i<(*qf)->numoutputfields; i++) {
642     ierr = CeedFree(&(*(*qf)->outputfields[i]).fieldname); CeedChk(ierr);
643     ierr = CeedFree(&(*qf)->outputfields[i]); CeedChk(ierr);
644   }
645   ierr = CeedFree(&(*qf)->inputfields); CeedChk(ierr);
646   ierr = CeedFree(&(*qf)->outputfields); CeedChk(ierr);
647   // Free ctx if identity
648   if ((*qf)->identity) {
649     ierr = CeedFree(&(*qf)->ctx); CeedChk(ierr);
650   }
651 
652   ierr = CeedFree(&(*qf)->sourcepath); CeedChk(ierr);
653   ierr = CeedDestroy(&(*qf)->ceed); CeedChk(ierr);
654   ierr = CeedFree(qf); CeedChk(ierr);
655   return 0;
656 }
657 
658 /// @}
659