Actual source code: dtfe.c

petsc-master 2016-02-13
Report Typos and Errors
  1: /* Basis Jet Tabulation

  3: We would like to tabulate the nodal basis functions and derivatives at a set of points, usually quadrature points. We
  4: follow here the derviation in http://www.math.ttu.edu/~kirby/papers/fiat-toms-2004.pdf. The nodal basis $\psi_i$ can
  5: be expressed in terms of a prime basis $\phi_i$ which can be stably evaluated. In PETSc, we will use the Legendre basis
  6: as a prime basis.

  8:   \psi_i = \sum_k \alpha_{ki} \phi_k

 10: Our nodal basis is defined in terms of the dual basis $n_j$

 12:   n_j \cdot \psi_i = \delta_{ji}

 14: and we may act on the first equation to obtain

 16:   n_j \cdot \psi_i = \sum_k \alpha_{ki} n_j \cdot \phi_k
 17:        \delta_{ji} = \sum_k \alpha_{ki} V_{jk}
 18:                  I = V \alpha

 20: so the coefficients of the nodal basis in the prime basis are

 22:    \alpha = V^{-1}

 24: We will define the dual basis vectors $n_j$ using a quadrature rule.

 26: Right now, we will just use the polynomial spaces P^k. I know some elements use the space of symmetric polynomials
 27: (I think Nedelec), but we will neglect this for now. Constraints in the space, e.g. Arnold-Winther elements, can
 28: be implemented exactly as in FIAT using functionals $L_j$.

 30: I will have to count the degrees correctly for the Legendre product when we are on simplices.

 32: We will have three objects:
 33:  - Space, P: this just need point evaluation I think
 34:  - Dual Space, P'+K: This looks like a set of functionals that can act on members of P, each n is defined by a Q
 35:  - FEM: This keeps {P, P', Q}
 36: */
 37: #include <petsc/private/petscfeimpl.h> /*I "petscfe.h" I*/
 38: #include <petsc/private/dtimpl.h>
 39: #include <petsc/private/dmpleximpl.h> /* For CellRefiner */
 40: #include <petscdmshell.h>
 41: #include <petscdmplex.h>
 42: #include <petscblaslapack.h>

 44: PetscBool FEcite = PETSC_FALSE;
 45: const char FECitation[] = "@article{kirby2004,\n"
 46:                           "  title   = {Algorithm 839: FIAT, a New Paradigm for Computing Finite Element Basis Functions},\n"
 47:                           "  journal = {ACM Transactions on Mathematical Software},\n"
 48:                           "  author  = {Robert C. Kirby},\n"
 49:                           "  volume  = {30},\n"
 50:                           "  number  = {4},\n"
 51:                           "  pages   = {502--516},\n"
 52:                           "  doi     = {10.1145/1039813.1039820},\n"
 53:                           "  year    = {2004}\n}\n";

 55: PetscClassId PETSCSPACE_CLASSID = 0;

 57: PetscFunctionList PetscSpaceList              = NULL;
 58: PetscBool         PetscSpaceRegisterAllCalled = PETSC_FALSE;

 62: /*@C
 63:   PetscSpaceRegister - Adds a new PetscSpace implementation

 65:   Not Collective

 67:   Input Parameters:
 68: + name        - The name of a new user-defined creation routine
 69: - create_func - The creation routine itself

 71:   Notes:
 72:   PetscSpaceRegister() may be called multiple times to add several user-defined PetscSpaces

 74:   Sample usage:
 75: .vb
 76:     PetscSpaceRegister("my_space", MyPetscSpaceCreate);
 77: .ve

 79:   Then, your PetscSpace type can be chosen with the procedural interface via
 80: .vb
 81:     PetscSpaceCreate(MPI_Comm, PetscSpace *);
 82:     PetscSpaceSetType(PetscSpace, "my_space");
 83: .ve
 84:    or at runtime via the option
 85: .vb
 86:     -petscspace_type my_space
 87: .ve

 89:   Level: advanced

 91: .keywords: PetscSpace, register
 92: .seealso: PetscSpaceRegisterAll(), PetscSpaceRegisterDestroy()

 94: @*/
 95: PetscErrorCode PetscSpaceRegister(const char sname[], PetscErrorCode (*function)(PetscSpace))
 96: {

100:   PetscFunctionListAdd(&PetscSpaceList, sname, function);
101:   return(0);
102: }

106: /*@C
107:   PetscSpaceSetType - Builds a particular PetscSpace

109:   Collective on PetscSpace

111:   Input Parameters:
112: + sp   - The PetscSpace object
113: - name - The kind of space

115:   Options Database Key:
116: . -petscspace_type <type> - Sets the PetscSpace type; use -help for a list of available types

118:   Level: intermediate

120: .keywords: PetscSpace, set, type
121: .seealso: PetscSpaceGetType(), PetscSpaceCreate()
122: @*/
123: PetscErrorCode PetscSpaceSetType(PetscSpace sp, PetscSpaceType name)
124: {
125:   PetscErrorCode (*r)(PetscSpace);
126:   PetscBool      match;

131:   PetscObjectTypeCompare((PetscObject) sp, name, &match);
132:   if (match) return(0);

134:   PetscSpaceRegisterAll();
135:   PetscFunctionListFind(PetscSpaceList, name, &r);
136:   if (!r) SETERRQ1(PetscObjectComm((PetscObject) sp), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown PetscSpace type: %s", name);

138:   if (sp->ops->destroy) {
139:     (*sp->ops->destroy)(sp);
140:     sp->ops->destroy = NULL;
141:   }
142:   (*r)(sp);
143:   PetscObjectChangeTypeName((PetscObject) sp, name);
144:   return(0);
145: }

149: /*@C
150:   PetscSpaceGetType - Gets the PetscSpace type name (as a string) from the object.

152:   Not Collective

154:   Input Parameter:
155: . sp  - The PetscSpace

157:   Output Parameter:
158: . name - The PetscSpace type name

160:   Level: intermediate

162: .keywords: PetscSpace, get, type, name
163: .seealso: PetscSpaceSetType(), PetscSpaceCreate()
164: @*/
165: PetscErrorCode PetscSpaceGetType(PetscSpace sp, PetscSpaceType *name)
166: {

172:   if (!PetscSpaceRegisterAllCalled) {
173:     PetscSpaceRegisterAll();
174:   }
175:   *name = ((PetscObject) sp)->type_name;
176:   return(0);
177: }

181: /*@C
182:   PetscSpaceView - Views a PetscSpace

184:   Collective on PetscSpace

186:   Input Parameter:
187: + sp - the PetscSpace object to view
188: - v  - the viewer

190:   Level: developer

192: .seealso PetscSpaceDestroy()
193: @*/
194: PetscErrorCode PetscSpaceView(PetscSpace sp, PetscViewer v)
195: {

200:   if (!v) {
201:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject) sp), &v);
202:   }
203:   if (sp->ops->view) {
204:     (*sp->ops->view)(sp, v);
205:   }
206:   return(0);
207: }

211: /*@
212:   PetscSpaceSetFromOptions - sets parameters in a PetscSpace from the options database

214:   Collective on PetscSpace

216:   Input Parameter:
217: . sp - the PetscSpace object to set options for

219:   Options Database:
220: . -petscspace_order the approximation order of the space

222:   Level: developer

224: .seealso PetscSpaceView()
225: @*/
226: PetscErrorCode PetscSpaceSetFromOptions(PetscSpace sp)
227: {
228:   const char    *defaultType;
229:   char           name[256];
230:   PetscBool      flg;

235:   if (!((PetscObject) sp)->type_name) {
236:     defaultType = PETSCSPACEPOLYNOMIAL;
237:   } else {
238:     defaultType = ((PetscObject) sp)->type_name;
239:   }
240:   if (!PetscSpaceRegisterAllCalled) {PetscSpaceRegisterAll();}

242:   PetscObjectOptionsBegin((PetscObject) sp);
243:   PetscOptionsFList("-petscspace_type", "Linear space", "PetscSpaceSetType", PetscSpaceList, defaultType, name, 256, &flg);
244:   if (flg) {
245:     PetscSpaceSetType(sp, name);
246:   } else if (!((PetscObject) sp)->type_name) {
247:     PetscSpaceSetType(sp, defaultType);
248:   }
249:   PetscOptionsInt("-petscspace_order", "The approximation order", "PetscSpaceSetOrder", sp->order, &sp->order, NULL);
250:   if (sp->ops->setfromoptions) {
251:     (*sp->ops->setfromoptions)(PetscOptionsObject,sp);
252:   }
253:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
254:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject) sp);
255:   PetscOptionsEnd();
256:   PetscSpaceViewFromOptions(sp, NULL, "-petscspace_view");
257:   return(0);
258: }

262: /*@C
263:   PetscSpaceSetUp - Construct data structures for the PetscSpace

265:   Collective on PetscSpace

267:   Input Parameter:
268: . sp - the PetscSpace object to setup

270:   Level: developer

272: .seealso PetscSpaceView(), PetscSpaceDestroy()
273: @*/
274: PetscErrorCode PetscSpaceSetUp(PetscSpace sp)
275: {

280:   if (sp->ops->setup) {(*sp->ops->setup)(sp);}
281:   return(0);
282: }

286: /*@
287:   PetscSpaceDestroy - Destroys a PetscSpace object

289:   Collective on PetscSpace

291:   Input Parameter:
292: . sp - the PetscSpace object to destroy

294:   Level: developer

296: .seealso PetscSpaceView()
297: @*/
298: PetscErrorCode PetscSpaceDestroy(PetscSpace *sp)
299: {

303:   if (!*sp) return(0);

306:   if (--((PetscObject)(*sp))->refct > 0) {*sp = 0; return(0);}
307:   ((PetscObject) (*sp))->refct = 0;
308:   DMDestroy(&(*sp)->dm);

310:   (*(*sp)->ops->destroy)(*sp);
311:   PetscHeaderDestroy(sp);
312:   return(0);
313: }

317: /*@
318:   PetscSpaceCreate - Creates an empty PetscSpace object. The type can then be set with PetscSpaceSetType().

320:   Collective on MPI_Comm

322:   Input Parameter:
323: . comm - The communicator for the PetscSpace object

325:   Output Parameter:
326: . sp - The PetscSpace object

328:   Level: beginner

330: .seealso: PetscSpaceSetType(), PETSCSPACEPOLYNOMIAL
331: @*/
332: PetscErrorCode PetscSpaceCreate(MPI_Comm comm, PetscSpace *sp)
333: {
334:   PetscSpace     s;

339:   PetscCitationsRegister(FECitation,&FEcite);
340:   *sp  = NULL;
341:   PetscFEInitializePackage();

343:   PetscHeaderCreate(s, PETSCSPACE_CLASSID, "PetscSpace", "Linear Space", "PetscSpace", comm, PetscSpaceDestroy, PetscSpaceView);

345:   s->order = 0;
346:   DMShellCreate(comm, &s->dm);

348:   *sp = s;
349:   return(0);
350: }

354: /* Dimension of the space, i.e. number of basis vectors */
355: PetscErrorCode PetscSpaceGetDimension(PetscSpace sp, PetscInt *dim)
356: {

362:   *dim = 0;
363:   if (sp->ops->getdimension) {(*sp->ops->getdimension)(sp, dim);}
364:   return(0);
365: }

369: /*@
370:   PetscSpaceGetOrder - Return the order of approximation for this space

372:   Input Parameter:
373: . sp - The PetscSpace

375:   Output Parameter:
376: . order - The approximation order

378:   Level: intermediate

380: .seealso: PetscSpaceSetOrder(), PetscSpaceCreate(), PetscSpace
381: @*/
382: PetscErrorCode PetscSpaceGetOrder(PetscSpace sp, PetscInt *order)
383: {
387:   *order = sp->order;
388:   return(0);
389: }

393: /*@
394:   PetscSpaceSetOrder - Set the order of approximation for this space

396:   Input Parameters:
397: + sp - The PetscSpace
398: - order - The approximation order

400:   Level: intermediate

402: .seealso: PetscSpaceGetOrder(), PetscSpaceCreate(), PetscSpace
403: @*/
404: PetscErrorCode PetscSpaceSetOrder(PetscSpace sp, PetscInt order)
405: {
408:   sp->order = order;
409:   return(0);
410: }

414: /*@C
415:   PetscSpaceEvaluate - Evaluate the basis functions and their derivatives (jet) at each point

417:   Input Parameters:
418: + sp      - The PetscSpace
419: . npoints - The number of evaluation points
420: - points  - The point coordinates

422:   Output Parameters:
423: + B - The function evaluations in a npoints x nfuncs array
424: . D - The derivative evaluations in a npoints x nfuncs x dim array
425: - H - The second derivative evaluations in a npoints x nfuncs x dim x dim array

427:   Level: advanced

429: .seealso: PetscFEGetTabulation(), PetscFEGetDefaultTabulation(), PetscSpaceCreate()
430: @*/
431: PetscErrorCode PetscSpaceEvaluate(PetscSpace sp, PetscInt npoints, const PetscReal points[], PetscReal B[], PetscReal D[], PetscReal H[])
432: {

441:   if (sp->ops->evaluate) {(*sp->ops->evaluate)(sp, npoints, points, B, D, H);}
442:   return(0);
443: }

447: PetscErrorCode PetscSpaceSetFromOptions_Polynomial(PetscOptionItems *PetscOptionsObject,PetscSpace sp)
448: {
449:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;
450:   PetscErrorCode   ierr;

453:   PetscOptionsHead(PetscOptionsObject,"PetscSpace polynomial options");
454:   PetscOptionsInt("-petscspace_poly_num_variables", "The number of different variables, e.g. x and y", "PetscSpacePolynomialSetNumVariables", poly->numVariables, &poly->numVariables, NULL);
455:   PetscOptionsBool("-petscspace_poly_sym", "Use only symmetric polynomials", "PetscSpacePolynomialSetSymmetric", poly->symmetric, &poly->symmetric, NULL);
456:   PetscOptionsBool("-petscspace_poly_tensor", "Use the tensor product polynomials", "PetscSpacePolynomialSetTensor", poly->tensor, &poly->tensor, NULL);
457:   PetscOptionsTail();
458:   return(0);
459: }

463: static PetscErrorCode PetscSpacePolynomialView_Ascii(PetscSpace sp, PetscViewer viewer)
464: {
465:   PetscSpace_Poly  *poly = (PetscSpace_Poly *) sp->data;
466:   PetscViewerFormat format;
467:   PetscErrorCode    ierr;

470:   PetscViewerGetFormat(viewer, &format);
471:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
472:     if (poly->tensor) {PetscViewerASCIIPrintf(viewer, "Tensor polynomial space in %d variables of order %d\n", poly->numVariables, sp->order);}
473:     else              {PetscViewerASCIIPrintf(viewer, "Polynomial space in %d variables of order %d\n", poly->numVariables, sp->order);}
474:   } else {
475:     if (poly->tensor) {PetscViewerASCIIPrintf(viewer, "Tensor polynomial space in %d variables of order %d\n", poly->numVariables, sp->order);}
476:     else              {PetscViewerASCIIPrintf(viewer, "Polynomial space in %d variables of order %d\n", poly->numVariables, sp->order);}
477:   }
478:   return(0);
479: }

483: PetscErrorCode PetscSpaceView_Polynomial(PetscSpace sp, PetscViewer viewer)
484: {
485:   PetscBool      iascii;

491:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &iascii);
492:   if (iascii) {PetscSpacePolynomialView_Ascii(sp, viewer);}
493:   return(0);
494: }

498: PetscErrorCode PetscSpaceSetUp_Polynomial(PetscSpace sp)
499: {
500:   PetscSpace_Poly *poly    = (PetscSpace_Poly *) sp->data;
501:   PetscInt         ndegree = sp->order+1;
502:   PetscInt         deg;
503:   PetscErrorCode   ierr;

506:   PetscMalloc1(ndegree, &poly->degrees);
507:   for (deg = 0; deg < ndegree; ++deg) poly->degrees[deg] = deg;
508:   return(0);
509: }

513: PetscErrorCode PetscSpaceDestroy_Polynomial(PetscSpace sp)
514: {
515:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;
516:   PetscErrorCode   ierr;

519:   PetscFree(poly->degrees);
520:   PetscFree(poly);
521:   return(0);
522: }

526: PetscErrorCode PetscSpaceGetDimension_Polynomial(PetscSpace sp, PetscInt *dim)
527: {
528:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;
529:   PetscInt         deg  = sp->order;
530:   PetscInt         n    = poly->numVariables, i;
531:   PetscReal        D    = 1.0;

534:   if (poly->tensor) {
535:     *dim = 1;
536:     for (i = 0; i < n; ++i) *dim *= (deg+1);
537:   } else {
538:     for (i = 1; i <= n; ++i) {
539:       D *= ((PetscReal) (deg+i))/i;
540:     }
541:     *dim = (PetscInt) (D + 0.5);
542:   }
543:   return(0);
544: }

548: /*
549:   LatticePoint_Internal - Returns all tuples of size 'len' with nonnegative integers that sum up to 'sum'.

551:   Input Parameters:
552: + len - The length of the tuple
553: . sum - The sum of all entries in the tuple
554: - ind - The current multi-index of the tuple, initialized to the 0 tuple

556:   Output Parameter:
557: + ind - The multi-index of the tuple, -1 indicates the iteration has terminated
558: . tup - A tuple of len integers addig to sum

560:   Level: developer

562: .seealso: 
563: */
564: static PetscErrorCode LatticePoint_Internal(PetscInt len, PetscInt sum, PetscInt ind[], PetscInt tup[])
565: {
566:   PetscInt       i;

570:   if (len == 1) {
571:     ind[0] = -1;
572:     tup[0] = sum;
573:   } else if (sum == 0) {
574:     for (i = 0; i < len; ++i) {ind[0] = -1; tup[i] = 0;}
575:   } else {
576:     tup[0] = sum - ind[0];
577:     LatticePoint_Internal(len-1, ind[0], &ind[1], &tup[1]);
578:     if (ind[1] < 0) {
579:       if (ind[0] == sum) {ind[0] = -1;}
580:       else               {ind[1] = 0; ++ind[0];}
581:     }
582:   }
583:   return(0);
584: }

588: /*
589:   TensorPoint_Internal - Returns all tuples of size 'len' with nonnegative integers that are less than 'max'.

591:   Input Parameters:
592: + len - The length of the tuple
593: . max - The max for all entries in the tuple
594: - ind - The current multi-index of the tuple, initialized to the 0 tuple

596:   Output Parameter:
597: + ind - The multi-index of the tuple, -1 indicates the iteration has terminated
598: . tup - A tuple of len integers less than max

600:   Level: developer

602: .seealso: 
603: */
604: static PetscErrorCode TensorPoint_Internal(PetscInt len, PetscInt max, PetscInt ind[], PetscInt tup[])
605: {
606:   PetscInt       i;

610:   if (len == 1) {
611:     tup[0] = ind[0]++;
612:     ind[0] = ind[0] >= max ? -1 : ind[0];
613:   } else if (max == 0) {
614:     for (i = 0; i < len; ++i) {ind[0] = -1; tup[i] = 0;}
615:   } else {
616:     tup[0] = ind[0];
617:     TensorPoint_Internal(len-1, max, &ind[1], &tup[1]);
618:     if (ind[1] < 0) {
619:       ind[1] = 0;
620:       if (ind[0] == max-1) {ind[0] = -1;}
621:       else                 {++ind[0];}
622:     }
623:   }
624:   return(0);
625: }

629: PetscErrorCode PetscSpaceEvaluate_Polynomial(PetscSpace sp, PetscInt npoints, const PetscReal points[], PetscReal B[], PetscReal D[], PetscReal H[])
630: {
631:   PetscSpace_Poly *poly    = (PetscSpace_Poly *) sp->data;
632:   DM               dm      = sp->dm;
633:   PetscInt         ndegree = sp->order+1;
634:   PetscInt        *degrees = poly->degrees;
635:   PetscInt         dim     = poly->numVariables;
636:   PetscReal       *lpoints, *tmp, *LB, *LD, *LH;
637:   PetscInt        *ind, *tup;
638:   PetscInt         pdim, d, der, i, p, deg, o;
639:   PetscErrorCode   ierr;

642:   PetscSpaceGetDimension(sp, &pdim);
643:   DMGetWorkArray(dm, npoints, PETSC_REAL, &lpoints);
644:   DMGetWorkArray(dm, npoints*ndegree*3, PETSC_REAL, &tmp);
645:   if (B) {DMGetWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LB);}
646:   if (D) {DMGetWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LD);}
647:   if (H) {DMGetWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LH);}
648:   for (d = 0; d < dim; ++d) {
649:     for (p = 0; p < npoints; ++p) {
650:       lpoints[p] = points[p*dim+d];
651:     }
652:     PetscDTLegendreEval(npoints, lpoints, ndegree, degrees, tmp, &tmp[1*npoints*ndegree], &tmp[2*npoints*ndegree]);
653:     /* LB, LD, LH (ndegree * dim x npoints) */
654:     for (deg = 0; deg < ndegree; ++deg) {
655:       for (p = 0; p < npoints; ++p) {
656:         if (B) LB[(deg*dim + d)*npoints + p] = tmp[(0*npoints + p)*ndegree+deg];
657:         if (D) LD[(deg*dim + d)*npoints + p] = tmp[(1*npoints + p)*ndegree+deg];
658:         if (H) LH[(deg*dim + d)*npoints + p] = tmp[(2*npoints + p)*ndegree+deg];
659:       }
660:     }
661:   }
662:   /* Multiply by A (pdim x ndegree * dim) */
663:   PetscMalloc2(dim,&ind,dim,&tup);
664:   if (B) {
665:     /* B (npoints x pdim) */
666:     if (poly->tensor) {
667:       i = 0;
668:       PetscMemzero(ind, dim * sizeof(PetscInt));
669:       while (ind[0] >= 0) {
670:         TensorPoint_Internal(dim, sp->order+1, ind, tup);
671:         for (p = 0; p < npoints; ++p) {
672:           B[p*pdim + i] = 1.0;
673:           for (d = 0; d < dim; ++d) {
674:             B[p*pdim + i] *= LB[(tup[d]*dim + d)*npoints + p];
675:           }
676:         }
677:         ++i;
678:       }
679:     } else {
680:       i = 0;
681:       for (o = 0; o <= sp->order; ++o) {
682:         PetscMemzero(ind, dim * sizeof(PetscInt));
683:         while (ind[0] >= 0) {
684:           LatticePoint_Internal(dim, o, ind, tup);
685:           for (p = 0; p < npoints; ++p) {
686:             B[p*pdim + i] = 1.0;
687:             for (d = 0; d < dim; ++d) {
688:               B[p*pdim + i] *= LB[(tup[d]*dim + d)*npoints + p];
689:             }
690:           }
691:           ++i;
692:         }
693:       }
694:     }
695:   }
696:   if (D) {
697:     /* D (npoints x pdim x dim) */
698:     if (poly->tensor) {
699:       i = 0;
700:       PetscMemzero(ind, dim * sizeof(PetscInt));
701:       while (ind[0] >= 0) {
702:         TensorPoint_Internal(dim, sp->order+1, ind, tup);
703:         for (p = 0; p < npoints; ++p) {
704:           for (der = 0; der < dim; ++der) {
705:             D[(p*pdim + i)*dim + der] = 1.0;
706:             for (d = 0; d < dim; ++d) {
707:               if (d == der) {
708:                 D[(p*pdim + i)*dim + der] *= LD[(tup[d]*dim + d)*npoints + p];
709:               } else {
710:                 D[(p*pdim + i)*dim + der] *= LB[(tup[d]*dim + d)*npoints + p];
711:               }
712:             }
713:           }
714:         }
715:         ++i;
716:       }
717:     } else {
718:       i = 0;
719:       for (o = 0; o <= sp->order; ++o) {
720:         PetscMemzero(ind, dim * sizeof(PetscInt));
721:         while (ind[0] >= 0) {
722:           LatticePoint_Internal(dim, o, ind, tup);
723:           for (p = 0; p < npoints; ++p) {
724:             for (der = 0; der < dim; ++der) {
725:               D[(p*pdim + i)*dim + der] = 1.0;
726:               for (d = 0; d < dim; ++d) {
727:                 if (d == der) {
728:                   D[(p*pdim + i)*dim + der] *= LD[(tup[d]*dim + d)*npoints + p];
729:                 } else {
730:                   D[(p*pdim + i)*dim + der] *= LB[(tup[d]*dim + d)*npoints + p];
731:                 }
732:               }
733:             }
734:           }
735:           ++i;
736:         }
737:       }
738:     }
739:   }
740:   if (H) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Too lazy to code second derivatives");
741:   PetscFree2(ind,tup);
742:   if (B) {DMRestoreWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LB);}
743:   if (D) {DMRestoreWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LD);}
744:   if (H) {DMRestoreWorkArray(dm, npoints*dim*ndegree, PETSC_REAL, &LH);}
745:   DMRestoreWorkArray(dm, npoints*ndegree*3, PETSC_REAL, &tmp);
746:   DMRestoreWorkArray(dm, npoints, PETSC_REAL, &lpoints);
747:   return(0);
748: }

752: PetscErrorCode PetscSpaceInitialize_Polynomial(PetscSpace sp)
753: {
755:   sp->ops->setfromoptions = PetscSpaceSetFromOptions_Polynomial;
756:   sp->ops->setup          = PetscSpaceSetUp_Polynomial;
757:   sp->ops->view           = PetscSpaceView_Polynomial;
758:   sp->ops->destroy        = PetscSpaceDestroy_Polynomial;
759:   sp->ops->getdimension   = PetscSpaceGetDimension_Polynomial;
760:   sp->ops->evaluate       = PetscSpaceEvaluate_Polynomial;
761:   return(0);
762: }

764: /*MC
765:   PETSCSPACEPOLYNOMIAL = "poly" - A PetscSpace object that encapsulates a polynomial space, e.g. P1 is the space of linear polynomials.

767:   Level: intermediate

769: .seealso: PetscSpaceType, PetscSpaceCreate(), PetscSpaceSetType()
770: M*/

774: PETSC_EXTERN PetscErrorCode PetscSpaceCreate_Polynomial(PetscSpace sp)
775: {
776:   PetscSpace_Poly *poly;
777:   PetscErrorCode   ierr;

781:   PetscNewLog(sp,&poly);
782:   sp->data = poly;

784:   poly->numVariables = 0;
785:   poly->symmetric    = PETSC_FALSE;
786:   poly->tensor       = PETSC_FALSE;
787:   poly->degrees      = NULL;

789:   PetscSpaceInitialize_Polynomial(sp);
790:   return(0);
791: }

795: PetscErrorCode PetscSpacePolynomialSetSymmetric(PetscSpace sp, PetscBool sym)
796: {
797:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

801:   poly->symmetric = sym;
802:   return(0);
803: }

807: PetscErrorCode PetscSpacePolynomialGetSymmetric(PetscSpace sp, PetscBool *sym)
808: {
809:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

814:   *sym = poly->symmetric;
815:   return(0);
816: }

820: /*@
821:   PetscSpacePolynomialSetTensor - Set whether a function space is a space of tensor polynomials (the space is spanned
822:   by polynomials whose degree in each variabl is bounded by the given order), as opposed to polynomials (the space is
823:   spanned by polynomials whose total degree---summing over all variables---is bounded by the given order).

825:   Input Parameters:
826: + sp     - the function space object
827: - tensor - PETSC_TRUE for a tensor polynomial space, PETSC_FALSE for a polynomial space

829:   Level: beginner

831: .seealso: PetscSpacePolynomialGetTensor(), PetscSpaceSetOrder(), PetscSpacePolynomialSetNumVariables()
832: @*/
833: PetscErrorCode PetscSpacePolynomialSetTensor(PetscSpace sp, PetscBool tensor)
834: {
835:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

839:   poly->tensor = tensor;
840:   return(0);
841: }

845: /*@
846:   PetscSpacePolynomialGetTensor - Get whether a function space is a space of tensor polynomials (the space is spanned
847:   by polynomials whose degree in each variabl is bounded by the given order), as opposed to polynomials (the space is
848:   spanned by polynomials whose total degree---summing over all variables---is bounded by the given order).

850:   Input Parameters:
851: . sp     - the function space object

853:   Output Parameters:
854: . tensor - PETSC_TRUE for a tensor polynomial space, PETSC_FALSE for a polynomial space

856:   Level: beginner

858: .seealso: PetscSpacePolynomialSetTensor(), PetscSpaceSetOrder(), PetscSpacePolynomialSetNumVariables()
859: @*/
860: PetscErrorCode PetscSpacePolynomialGetTensor(PetscSpace sp, PetscBool *tensor)
861: {
862:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

867:   *tensor = poly->tensor;
868:   return(0);
869: }

873: PetscErrorCode PetscSpacePolynomialSetNumVariables(PetscSpace sp, PetscInt n)
874: {
875:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

879:   poly->numVariables = n;
880:   return(0);
881: }

885: PetscErrorCode PetscSpacePolynomialGetNumVariables(PetscSpace sp, PetscInt *n)
886: {
887:   PetscSpace_Poly *poly = (PetscSpace_Poly *) sp->data;

892:   *n = poly->numVariables;
893:   return(0);
894: }

898: PetscErrorCode PetscSpaceSetFromOptions_DG(PetscOptionItems *PetscOptionsObject,PetscSpace sp)
899: {
900:   PetscSpace_DG *dg = (PetscSpace_DG *) sp->data;

904:   PetscOptionsHead(PetscOptionsObject,"PetscSpace DG options");
905:   PetscOptionsInt("-petscspace_dg_num_variables", "The number of different variables, e.g. x and y", "PetscSpaceDGSetNumVariables", dg->numVariables, &dg->numVariables, NULL);
906:   PetscOptionsTail();
907:   return(0);
908: }

912: PetscErrorCode PetscSpaceDGView_Ascii(PetscSpace sp, PetscViewer viewer)
913: {
914:   PetscSpace_DG    *dg = (PetscSpace_DG *) sp->data;
915:   PetscViewerFormat format;
916:   PetscErrorCode    ierr;

919:   PetscViewerGetFormat(viewer, &format);
920:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
921:     PetscViewerASCIIPrintf(viewer, "DG space in dimension %d:\n", dg->numVariables);
922:     PetscViewerASCIIPushTab(viewer);
923:     PetscQuadratureView(dg->quad, viewer);
924:     PetscViewerASCIIPopTab(viewer);
925:   } else {
926:     PetscViewerASCIIPrintf(viewer, "DG space in dimension %d on %d points\n", dg->numVariables, dg->quad->numPoints);
927:   }
928:   return(0);
929: }

933: PetscErrorCode PetscSpaceView_DG(PetscSpace sp, PetscViewer viewer)
934: {
935:   PetscBool      iascii;

941:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &iascii);
942:   if (iascii) {PetscSpaceDGView_Ascii(sp, viewer);}
943:   return(0);
944: }

948: PetscErrorCode PetscSpaceSetUp_DG(PetscSpace sp)
949: {
950:   PetscSpace_DG *dg = (PetscSpace_DG *) sp->data;

954:   if (!dg->quad->points && sp->order) {
955:     PetscDTGaussJacobiQuadrature(dg->numVariables, sp->order, -1.0, 1.0, &dg->quad);
956:   }
957:   return(0);
958: }

962: PetscErrorCode PetscSpaceDestroy_DG(PetscSpace sp)
963: {
964:   PetscSpace_DG *dg = (PetscSpace_DG *) sp->data;

968:   PetscQuadratureDestroy(&dg->quad);
969:   return(0);
970: }

974: PetscErrorCode PetscSpaceGetDimension_DG(PetscSpace sp, PetscInt *dim)
975: {
976:   PetscSpace_DG *dg = (PetscSpace_DG *) sp->data;

979:   *dim = dg->quad->numPoints;
980:   return(0);
981: }

985: PetscErrorCode PetscSpaceEvaluate_DG(PetscSpace sp, PetscInt npoints, const PetscReal points[], PetscReal B[], PetscReal D[], PetscReal H[])
986: {
987:   PetscSpace_DG *dg  = (PetscSpace_DG *) sp->data;
988:   PetscInt       dim = dg->numVariables, d, p;

992:   if (D || H) SETERRQ(PetscObjectComm((PetscObject) sp), PETSC_ERR_SUP, "Cannot calculate derivatives for a DG space");
993:   if (npoints != dg->quad->numPoints) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot evaluate DG space on %d points != %d size", npoints, dg->quad->numPoints);
994:   PetscMemzero(B, npoints*npoints * sizeof(PetscReal));
995:   for (p = 0; p < npoints; ++p) {
996:     for (d = 0; d < dim; ++d) {
997:       if (PetscAbsReal(points[p*dim+d] - dg->quad->points[p*dim+d]) > 1.0e-10) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot evaluate DG point (%d, %d) %g != %g", p, d, points[p*dim+d], dg->quad->points[p*dim+d]);
998:     }
999:     B[p*npoints+p] = 1.0;
1000:   }
1001:   return(0);
1002: }

1006: PetscErrorCode PetscSpaceInitialize_DG(PetscSpace sp)
1007: {
1009:   sp->ops->setfromoptions = PetscSpaceSetFromOptions_DG;
1010:   sp->ops->setup          = PetscSpaceSetUp_DG;
1011:   sp->ops->view           = PetscSpaceView_DG;
1012:   sp->ops->destroy        = PetscSpaceDestroy_DG;
1013:   sp->ops->getdimension   = PetscSpaceGetDimension_DG;
1014:   sp->ops->evaluate       = PetscSpaceEvaluate_DG;
1015:   return(0);
1016: }

1018: /*MC
1019:   PETSCSPACEDG = "dg" - A PetscSpace object that encapsulates functions defined on a set of quadrature points.

1021:   Level: intermediate

1023: .seealso: PetscSpaceType, PetscSpaceCreate(), PetscSpaceSetType()
1024: M*/

1028: PETSC_EXTERN PetscErrorCode PetscSpaceCreate_DG(PetscSpace sp)
1029: {
1030:   PetscSpace_DG *dg;

1035:   PetscNewLog(sp,&dg);
1036:   sp->data = dg;

1038:   dg->numVariables    = 0;
1039:   dg->quad->dim       = 0;
1040:   dg->quad->numPoints = 0;
1041:   dg->quad->points    = NULL;
1042:   dg->quad->weights   = NULL;

1044:   PetscSpaceInitialize_DG(sp);
1045:   return(0);
1046: }


1049: PetscClassId PETSCDUALSPACE_CLASSID = 0;

1051: PetscFunctionList PetscDualSpaceList              = NULL;
1052: PetscBool         PetscDualSpaceRegisterAllCalled = PETSC_FALSE;

1056: /*@C
1057:   PetscDualSpaceRegister - Adds a new PetscDualSpace implementation

1059:   Not Collective

1061:   Input Parameters:
1062: + name        - The name of a new user-defined creation routine
1063: - create_func - The creation routine itself

1065:   Notes:
1066:   PetscDualSpaceRegister() may be called multiple times to add several user-defined PetscDualSpaces

1068:   Sample usage:
1069: .vb
1070:     PetscDualSpaceRegister("my_space", MyPetscDualSpaceCreate);
1071: .ve

1073:   Then, your PetscDualSpace type can be chosen with the procedural interface via
1074: .vb
1075:     PetscDualSpaceCreate(MPI_Comm, PetscDualSpace *);
1076:     PetscDualSpaceSetType(PetscDualSpace, "my_dual_space");
1077: .ve
1078:    or at runtime via the option
1079: .vb
1080:     -petscdualspace_type my_dual_space
1081: .ve

1083:   Level: advanced

1085: .keywords: PetscDualSpace, register
1086: .seealso: PetscDualSpaceRegisterAll(), PetscDualSpaceRegisterDestroy()

1088: @*/
1089: PetscErrorCode PetscDualSpaceRegister(const char sname[], PetscErrorCode (*function)(PetscDualSpace))
1090: {

1094:   PetscFunctionListAdd(&PetscDualSpaceList, sname, function);
1095:   return(0);
1096: }

1100: /*@C
1101:   PetscDualSpaceSetType - Builds a particular PetscDualSpace

1103:   Collective on PetscDualSpace

1105:   Input Parameters:
1106: + sp   - The PetscDualSpace object
1107: - name - The kind of space

1109:   Options Database Key:
1110: . -petscdualspace_type <type> - Sets the PetscDualSpace type; use -help for a list of available types

1112:   Level: intermediate

1114: .keywords: PetscDualSpace, set, type
1115: .seealso: PetscDualSpaceGetType(), PetscDualSpaceCreate()
1116: @*/
1117: PetscErrorCode PetscDualSpaceSetType(PetscDualSpace sp, PetscDualSpaceType name)
1118: {
1119:   PetscErrorCode (*r)(PetscDualSpace);
1120:   PetscBool      match;

1125:   PetscObjectTypeCompare((PetscObject) sp, name, &match);
1126:   if (match) return(0);

1128:   if (!PetscDualSpaceRegisterAllCalled) {PetscDualSpaceRegisterAll();}
1129:   PetscFunctionListFind(PetscDualSpaceList, name, &r);
1130:   if (!r) SETERRQ1(PetscObjectComm((PetscObject) sp), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown PetscDualSpace type: %s", name);

1132:   if (sp->ops->destroy) {
1133:     (*sp->ops->destroy)(sp);
1134:     sp->ops->destroy = NULL;
1135:   }
1136:   (*r)(sp);
1137:   PetscObjectChangeTypeName((PetscObject) sp, name);
1138:   return(0);
1139: }

1143: /*@C
1144:   PetscDualSpaceGetType - Gets the PetscDualSpace type name (as a string) from the object.

1146:   Not Collective

1148:   Input Parameter:
1149: . sp  - The PetscDualSpace

1151:   Output Parameter:
1152: . name - The PetscDualSpace type name

1154:   Level: intermediate

1156: .keywords: PetscDualSpace, get, type, name
1157: .seealso: PetscDualSpaceSetType(), PetscDualSpaceCreate()
1158: @*/
1159: PetscErrorCode PetscDualSpaceGetType(PetscDualSpace sp, PetscDualSpaceType *name)
1160: {

1166:   if (!PetscDualSpaceRegisterAllCalled) {
1167:     PetscDualSpaceRegisterAll();
1168:   }
1169:   *name = ((PetscObject) sp)->type_name;
1170:   return(0);
1171: }

1175: /*@
1176:   PetscDualSpaceView - Views a PetscDualSpace

1178:   Collective on PetscDualSpace

1180:   Input Parameter:
1181: + sp - the PetscDualSpace object to view
1182: - v  - the viewer

1184:   Level: developer

1186: .seealso PetscDualSpaceDestroy()
1187: @*/
1188: PetscErrorCode PetscDualSpaceView(PetscDualSpace sp, PetscViewer v)
1189: {

1194:   if (!v) {
1195:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject) sp), &v);
1196:   }
1197:   if (sp->ops->view) {
1198:     (*sp->ops->view)(sp, v);
1199:   }
1200:   return(0);
1201: }

1205: /*@
1206:   PetscDualSpaceSetFromOptions - sets parameters in a PetscDualSpace from the options database

1208:   Collective on PetscDualSpace

1210:   Input Parameter:
1211: . sp - the PetscDualSpace object to set options for

1213:   Options Database:
1214: . -petscspace_order the approximation order of the space

1216:   Level: developer

1218: .seealso PetscDualSpaceView()
1219: @*/
1220: PetscErrorCode PetscDualSpaceSetFromOptions(PetscDualSpace sp)
1221: {
1222:   const char    *defaultType;
1223:   char           name[256];
1224:   PetscBool      flg;

1229:   if (!((PetscObject) sp)->type_name) {
1230:     defaultType = PETSCDUALSPACELAGRANGE;
1231:   } else {
1232:     defaultType = ((PetscObject) sp)->type_name;
1233:   }
1234:   if (!PetscSpaceRegisterAllCalled) {PetscSpaceRegisterAll();}

1236:   PetscObjectOptionsBegin((PetscObject) sp);
1237:   PetscOptionsFList("-petscdualspace_type", "Dual space", "PetscDualSpaceSetType", PetscDualSpaceList, defaultType, name, 256, &flg);
1238:   if (flg) {
1239:     PetscDualSpaceSetType(sp, name);
1240:   } else if (!((PetscObject) sp)->type_name) {
1241:     PetscDualSpaceSetType(sp, defaultType);
1242:   }
1243:   PetscOptionsInt("-petscdualspace_order", "The approximation order", "PetscDualSpaceSetOrder", sp->order, &sp->order, NULL);
1244:   if (sp->ops->setfromoptions) {
1245:     (*sp->ops->setfromoptions)(PetscOptionsObject,sp);
1246:   }
1247:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1248:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject) sp);
1249:   PetscOptionsEnd();
1250:   PetscDualSpaceViewFromOptions(sp, NULL, "-petscdualspace_view");
1251:   return(0);
1252: }

1256: /*@
1257:   PetscDualSpaceSetUp - Construct a basis for the PetscDualSpace

1259:   Collective on PetscDualSpace

1261:   Input Parameter:
1262: . sp - the PetscDualSpace object to setup

1264:   Level: developer

1266: .seealso PetscDualSpaceView(), PetscDualSpaceDestroy()
1267: @*/
1268: PetscErrorCode PetscDualSpaceSetUp(PetscDualSpace sp)
1269: {

1274:   if (sp->ops->setup) {(*sp->ops->setup)(sp);}
1275:   return(0);
1276: }

1280: /*@
1281:   PetscDualSpaceDestroy - Destroys a PetscDualSpace object

1283:   Collective on PetscDualSpace

1285:   Input Parameter:
1286: . sp - the PetscDualSpace object to destroy

1288:   Level: developer

1290: .seealso PetscDualSpaceView()
1291: @*/
1292: PetscErrorCode PetscDualSpaceDestroy(PetscDualSpace *sp)
1293: {
1294:   PetscInt       dim, f;

1298:   if (!*sp) return(0);

1301:   if (--((PetscObject)(*sp))->refct > 0) {*sp = 0; return(0);}
1302:   ((PetscObject) (*sp))->refct = 0;

1304:   PetscDualSpaceGetDimension(*sp, &dim);
1305:   for (f = 0; f < dim; ++f) {
1306:     PetscQuadratureDestroy(&(*sp)->functional[f]);
1307:   }
1308:   PetscFree((*sp)->functional);
1309:   DMDestroy(&(*sp)->dm);

1311:   if ((*sp)->ops->destroy) {(*(*sp)->ops->destroy)(*sp);}
1312:   PetscHeaderDestroy(sp);
1313:   return(0);
1314: }

1318: /*@
1319:   PetscDualSpaceCreate - Creates an empty PetscDualSpace object. The type can then be set with PetscDualSpaceSetType().

1321:   Collective on MPI_Comm

1323:   Input Parameter:
1324: . comm - The communicator for the PetscDualSpace object

1326:   Output Parameter:
1327: . sp - The PetscDualSpace object

1329:   Level: beginner

1331: .seealso: PetscDualSpaceSetType(), PETSCDUALSPACELAGRANGE
1332: @*/
1333: PetscErrorCode PetscDualSpaceCreate(MPI_Comm comm, PetscDualSpace *sp)
1334: {
1335:   PetscDualSpace s;

1340:   PetscCitationsRegister(FECitation,&FEcite);
1341:   *sp  = NULL;
1342:   PetscFEInitializePackage();

1344:   PetscHeaderCreate(s, PETSCDUALSPACE_CLASSID, "PetscDualSpace", "Dual Space", "PetscDualSpace", comm, PetscDualSpaceDestroy, PetscDualSpaceView);

1346:   s->order = 0;

1348:   *sp = s;
1349:   return(0);
1350: }

1354: /*@
1355:   PetscDualSpaceDuplicate - Creates a duplicate PetscDualSpace object, however it is not setup.

1357:   Collective on PetscDualSpace

1359:   Input Parameter:
1360: . sp - The original PetscDualSpace

1362:   Output Parameter:
1363: . spNew - The duplicate PetscDualSpace

1365:   Level: beginner

1367: .seealso: PetscDualSpaceCreate(), PetscDualSpaceSetType()
1368: @*/
1369: PetscErrorCode PetscDualSpaceDuplicate(PetscDualSpace sp, PetscDualSpace *spNew)
1370: {

1376:   (*sp->ops->duplicate)(sp, spNew);
1377:   return(0);
1378: }

1382: /*@
1383:   PetscDualSpaceGetDM - Get the DM representing the reference cell

1385:   Not collective

1387:   Input Parameter:
1388: . sp - The PetscDualSpace

1390:   Output Parameter:
1391: . dm - The reference cell

1393:   Level: intermediate

1395: .seealso: PetscDualSpaceSetDM(), PetscDualSpaceCreate()
1396: @*/
1397: PetscErrorCode PetscDualSpaceGetDM(PetscDualSpace sp, DM *dm)
1398: {
1402:   *dm = sp->dm;
1403:   return(0);
1404: }

1408: /*@
1409:   PetscDualSpaceSetDM - Get the DM representing the reference cell

1411:   Not collective

1413:   Input Parameters:
1414: + sp - The PetscDualSpace
1415: - dm - The reference cell

1417:   Level: intermediate

1419: .seealso: PetscDualSpaceGetDM(), PetscDualSpaceCreate()
1420: @*/
1421: PetscErrorCode PetscDualSpaceSetDM(PetscDualSpace sp, DM dm)
1422: {

1428:   DMDestroy(&sp->dm);
1429:   PetscObjectReference((PetscObject) dm);
1430:   sp->dm = dm;
1431:   return(0);
1432: }

1436: /*@
1437:   PetscDualSpaceGetOrder - Get the order of the dual space

1439:   Not collective

1441:   Input Parameter:
1442: . sp - The PetscDualSpace

1444:   Output Parameter:
1445: . order - The order

1447:   Level: intermediate

1449: .seealso: PetscDualSpaceSetOrder(), PetscDualSpaceCreate()
1450: @*/
1451: PetscErrorCode PetscDualSpaceGetOrder(PetscDualSpace sp, PetscInt *order)
1452: {
1456:   *order = sp->order;
1457:   return(0);
1458: }

1462: /*@
1463:   PetscDualSpaceSetOrder - Set the order of the dual space

1465:   Not collective

1467:   Input Parameters:
1468: + sp - The PetscDualSpace
1469: - order - The order

1471:   Level: intermediate

1473: .seealso: PetscDualSpaceGetOrder(), PetscDualSpaceCreate()
1474: @*/
1475: PetscErrorCode PetscDualSpaceSetOrder(PetscDualSpace sp, PetscInt order)
1476: {
1479:   sp->order = order;
1480:   return(0);
1481: }

1485: /*@
1486:   PetscDualSpaceGetFunctional - Get the i-th basis functional in the dual space

1488:   Not collective

1490:   Input Parameters:
1491: + sp - The PetscDualSpace
1492: - i  - The basis number

1494:   Output Parameter:
1495: . functional - The basis functional

1497:   Level: intermediate

1499: .seealso: PetscDualSpaceGetDimension(), PetscDualSpaceCreate()
1500: @*/
1501: PetscErrorCode PetscDualSpaceGetFunctional(PetscDualSpace sp, PetscInt i, PetscQuadrature *functional)
1502: {
1503:   PetscInt       dim;

1509:   PetscDualSpaceGetDimension(sp, &dim);
1510:   if ((i < 0) || (i >= dim)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Functional index %d must be in [0, %d)", i, dim);
1511:   *functional = sp->functional[i];
1512:   return(0);
1513: }

1517: /*@
1518:   PetscDualSpaceGetDimension - Get the dimension of the dual space, i.e. the number of basis functionals

1520:   Not collective

1522:   Input Parameter:
1523: . sp - The PetscDualSpace

1525:   Output Parameter:
1526: . dim - The dimension

1528:   Level: intermediate

1530: .seealso: PetscDualSpaceGetFunctional(), PetscDualSpaceCreate()
1531: @*/
1532: PetscErrorCode PetscDualSpaceGetDimension(PetscDualSpace sp, PetscInt *dim)
1533: {

1539:   *dim = 0;
1540:   if (sp->ops->getdimension) {(*sp->ops->getdimension)(sp, dim);}
1541:   return(0);
1542: }

1546: /*@C
1547:   PetscDualSpaceGetNumDof - Get the number of degrees of freedom for each spatial (topological) dimension

1549:   Not collective

1551:   Input Parameter:
1552: . sp - The PetscDualSpace

1554:   Output Parameter:
1555: . numDof - An array of length dim+1 which holds the number of dofs for each dimension

1557:   Level: intermediate

1559: .seealso: PetscDualSpaceGetFunctional(), PetscDualSpaceCreate()
1560: @*/
1561: PetscErrorCode PetscDualSpaceGetNumDof(PetscDualSpace sp, const PetscInt **numDof)
1562: {

1568:   *numDof = NULL;
1569:   if (sp->ops->getnumdof) {(*sp->ops->getnumdof)(sp, numDof);}
1570:   return(0);
1571: }

1575: /*@
1576:   PetscDualSpaceCreateReferenceCell - Create a DMPLEX with the appropriate FEM reference cell

1578:   Collective on PetscDualSpace

1580:   Input Parameters:
1581: + sp      - The PetscDualSpace
1582: . dim     - The spatial dimension
1583: - simplex - Flag for simplex, otherwise use a tensor-product cell

1585:   Output Parameter:
1586: . refdm - The reference cell

1588:   Level: advanced

1590: .keywords: PetscDualSpace, reference cell
1591: .seealso: PetscDualSpaceCreate(), DMPLEX
1592: @*/
1593: PetscErrorCode PetscDualSpaceCreateReferenceCell(PetscDualSpace sp, PetscInt dim, PetscBool simplex, DM *refdm)
1594: {

1598:   DMPlexCreateReferenceCell(PetscObjectComm((PetscObject) sp), dim, simplex, refdm);
1599:   return(0);
1600: }

1604: /*@C
1605:   PetscDualSpaceApply - Apply a functional from the dual space basis to an input function

1607:   Input Parameters:
1608: + sp      - The PetscDualSpace object
1609: . f       - The basis functional index
1610: . time    - The time
1611: . geom    - A context with geometric information for this cell, we use v0 (the initial vertex) and J (the Jacobian)
1612: . numComp - The number of components for the function
1613: . func    - The input function
1614: - ctx     - A context for the function

1616:   Output Parameter:
1617: . value   - numComp output values

1619:   Note: The calling sequence for the callback func is given by:

1621: $ func(PetscInt dim, PetscReal time, const PetscReal x[],
1622: $      PetscInt numComponents, PetscScalar values[], void *ctx)

1624:   Level: developer

1626: .seealso: PetscDualSpaceCreate()
1627: @*/
1628: PetscErrorCode PetscDualSpaceApply(PetscDualSpace sp, PetscInt f, PetscReal time, PetscFECellGeom *geom, PetscInt numComp, PetscErrorCode (*func)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void *ctx, PetscScalar *value)
1629: {
1630:   DM               dm;
1631:   PetscQuadrature  quad;
1632:   PetscReal        x[3];
1633:   PetscScalar     *val;
1634:   PetscInt         dim, q, c;
1635:   PetscErrorCode   ierr;

1640:   dim  = geom->dim;
1641:   PetscDualSpaceGetDM(sp, &dm);
1642:   PetscDualSpaceGetFunctional(sp, f, &quad);
1643:   DMGetWorkArray(dm, numComp, PETSC_SCALAR, &val);
1644:   for (c = 0; c < numComp; ++c) value[c] = 0.0;
1645:   for (q = 0; q < quad->numPoints; ++q) {
1646:     CoordinatesRefToReal(geom->dimEmbed, dim, geom->v0, geom->J, &quad->points[q*dim], x);
1647:     (*func)(geom->dimEmbed, time, x, numComp, val, ctx);
1648:     for (c = 0; c < numComp; ++c) {
1649:       value[c] += val[c]*quad->weights[q];
1650:     }
1651:   }
1652:   DMRestoreWorkArray(dm, numComp, PETSC_SCALAR, &val);
1653:   return(0);
1654: }

1658: /*@
1659:   PetscDualSpaceGetHeightSubspace - Get the subset of the dual space basis that is supported on a mesh point of a given height.

1661:   If the dual space is not defined on mesh points of the given height (e.g. if the space is discontinuous and
1662:   pointwise values are not defined on the element boundaries), or if the implementation of PetscDualSpace does not
1663:   support extracting subspaces, then NULL is returned.

1665:   Input Parameters:
1666: + sp - the PetscDualSpace object
1667: - height - the height of the mesh point for which the subspace is desired

1669:   Output Parameters:
1670:   bdsp - the subspace: must be destroyed by the user

1672:   Level: advanced

1674: .seealso: PetscDualSpace
1675: @*/
1676: PetscErrorCode PetscDualSpaceGetHeightSubspace(PetscDualSpace sp, PetscInt height, PetscDualSpace *bdsp)
1677: {

1683:   *bdsp = NULL;
1684:   if (sp->ops->getheightsubspace) {
1685:     (*sp->ops->getheightsubspace)(sp,height,bdsp);
1686:   }
1687:   return(0);
1688: }

1692: static PetscErrorCode PetscDualSpaceGetDimension_SingleCell_Lagrange(PetscDualSpace sp, PetscInt order, PetscInt *dim)
1693: {
1694:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;
1695:   PetscReal           D   = 1.0;
1696:   PetscInt            n, i;
1697:   PetscErrorCode      ierr;

1700:   *dim = -1;                    /* Ensure that the compiler knows *dim is set. */
1701:   DMGetDimension(sp->dm, &n);
1702:   if (lag->simplex || !lag->continuous) {
1703:     for (i = 1; i <= n; ++i) {
1704:       D *= ((PetscReal) (order+i))/i;
1705:     }
1706:     *dim = (PetscInt) (D + 0.5);
1707:   } else {
1708:     *dim = 1;
1709:     for (i = 0; i < n; ++i) *dim *= (order+1);
1710:   }
1711:   return(0);
1712: }

1716: PetscErrorCode PetscDualSpaceSetUp_Lagrange(PetscDualSpace sp)
1717: {
1718:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;
1719:   DM                  dm    = sp->dm;
1720:   PetscInt            order = sp->order;
1721:   PetscBool           disc  = lag->continuous ? PETSC_FALSE : PETSC_TRUE;
1722:   PetscSection        csection;
1723:   Vec                 coordinates;
1724:   PetscReal          *qpoints, *qweights;
1725:   PetscInt           *closure = NULL, closureSize, c;
1726:   PetscInt            depth, dim, pdimMax, pMax = 0, *pStart, *pEnd, cell, coneSize, d, n, f = 0;
1727:   PetscBool           simplex;
1728:   PetscErrorCode      ierr;

1731:   /* Classify element type */
1732:   DMGetDimension(dm, &dim);
1733:   DMPlexGetDepth(dm, &depth);
1734:   PetscCalloc1(dim+1, &lag->numDof);
1735:   PetscMalloc2(depth+1,&pStart,depth+1,&pEnd);
1736:   for (d = 0; d <= depth; ++d) {DMPlexGetDepthStratum(dm, d, &pStart[d], &pEnd[d]);}
1737:   DMPlexGetConeSize(dm, pStart[depth], &coneSize);
1738:   DMGetCoordinateSection(dm, &csection);
1739:   DMGetCoordinatesLocal(dm, &coordinates);
1740:   if (depth == 1) {
1741:     if      (coneSize == dim+1)    simplex = PETSC_TRUE;
1742:     else if (coneSize == 1 << dim) simplex = PETSC_FALSE;
1743:     else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Only support simplices and tensor product cells");
1744:   }
1745:   else if (depth == dim) {
1746:     if      (coneSize == dim+1)   simplex = PETSC_TRUE;
1747:     else if (coneSize == 2 * dim) simplex = PETSC_FALSE;
1748:     else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Only support simplices and tensor product cells");
1749:   }
1750:   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Only support cell-vertex meshes or interpolated meshes");
1751:   lag->simplex = simplex;
1752:   PetscDualSpaceGetDimension_SingleCell_Lagrange(sp, sp->order, &pdimMax);
1753:   pdimMax *= (pEnd[dim] - pStart[dim]);
1754:   PetscMalloc1(pdimMax, &sp->functional);
1755:   for (d = 0; d <= depth; d++) {
1756:     pMax = PetscMax(pMax,pEnd[d]);
1757:   }
1758:   if (!dim) {
1759:     PetscQuadratureCreate(PETSC_COMM_SELF, &sp->functional[f]);
1760:     PetscMalloc1(1, &qpoints);
1761:     PetscMalloc1(1, &qweights);
1762:     PetscQuadratureSetOrder(sp->functional[f], 0);
1763:     PetscQuadratureSetData(sp->functional[f], PETSC_DETERMINE, 1, qpoints, qweights);
1764:     qpoints[0]  = 0.0;
1765:     qweights[0] = 1.0;
1766:     ++f;
1767:     lag->numDof[0] = 1;
1768:   } else {
1769:     PetscBT seen;

1771:     PetscBTCreate(pMax, &seen);
1772:     PetscBTMemzero(pMax, seen);
1773:     for (cell = pStart[depth]; cell < pEnd[depth]; ++cell) {
1774:       DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure);
1775:       for (c = 0; c < closureSize*2; c += 2) {
1776:         const PetscInt p = closure[c];

1778:         if (PetscBTLookup(seen, p)) continue;
1779:         PetscBTSet(seen, p);
1780:         if ((p >= pStart[0]) && (p < pEnd[0])) {
1781:           /* Vertices */
1782:           const PetscScalar *coords;
1783:           PetscInt           dof, off, d;

1785:           if (order < 1 || disc) continue;
1786:           PetscQuadratureCreate(PETSC_COMM_SELF, &sp->functional[f]);
1787:           PetscMalloc1(dim, &qpoints);
1788:           PetscMalloc1(1, &qweights);
1789:           PetscQuadratureSetOrder(sp->functional[f], 0);
1790:           PetscQuadratureSetData(sp->functional[f], dim, 1, qpoints, qweights);
1791:           VecGetArrayRead(coordinates, &coords);
1792:           PetscSectionGetDof(csection, p, &dof);
1793:           PetscSectionGetOffset(csection, p, &off);
1794:           if (dof != dim) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of coordinates %d does not match spatial dimension %d", dof, dim);
1795:           for (d = 0; d < dof; ++d) {qpoints[d] = PetscRealPart(coords[off+d]);}
1796:           qweights[0] = 1.0;
1797:           ++f;
1798:           VecRestoreArrayRead(coordinates, &coords);
1799:           lag->numDof[0] = 1;
1800:         } else if ((p >= pStart[1]) && (p < pEnd[1])) {
1801:           /* Edges */
1802:           PetscScalar *coords;
1803:           PetscInt     num = ((dim == 1) && !order) ? 1 : order-1, k;

1805:           if (num < 1 || disc) continue;
1806:           coords = NULL;
1807:           DMPlexVecGetClosure(dm, csection, coordinates, p, &n, &coords);
1808:           if (n != dim*2) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %d has %d coordinate values instead of %d", p, n, dim*2);
1809:           for (k = 1; k <= num; ++k) {
1810:             PetscQuadratureCreate(PETSC_COMM_SELF, &sp->functional[f]);
1811:             PetscMalloc1(dim, &qpoints);
1812:             PetscMalloc1(1, &qweights);
1813:             PetscQuadratureSetOrder(sp->functional[f], 0);
1814:             PetscQuadratureSetData(sp->functional[f], dim, 1, qpoints, qweights);
1815:             for (d = 0; d < dim; ++d) {qpoints[d] = k*PetscRealPart(coords[1*dim+d] - coords[0*dim+d])/order + PetscRealPart(coords[0*dim+d]);}
1816:             qweights[0] = 1.0;
1817:             ++f;
1818:           }
1819:           DMPlexVecRestoreClosure(dm, csection, coordinates, p, &n, &coords);
1820:           lag->numDof[1] = num;
1821:         } else if ((p >= pStart[depth-1]) && (p < pEnd[depth-1])) {
1822:           /* Faces */

1824:           if (disc) continue;
1825:           if ( simplex && (order < 3)) continue;
1826:           if (!simplex && (order < 2)) continue;
1827:           lag->numDof[depth-1] = 0;
1828:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Too lazy to implement faces");
1829:         } else if ((p >= pStart[depth]) && (p < pEnd[depth])) {
1830:           /* Cells */
1831:           PetscInt     orderEff = lag->continuous && order ? (simplex ? order-3 : order-2) : order;
1832:           PetscReal    denom    = order ? (lag->continuous ? order : (simplex ? order+3 : order+2)) : (simplex ? 3 : 2);
1833:           PetscScalar *coords   = NULL;
1834:           PetscReal    dx = 2.0/denom, *v0, *J, *invJ, detJ;
1835:           PetscInt    *ind, *tup;
1836:           PetscInt     cdim, csize, d, d2, o;

1838:           lag->numDof[depth] = 0;
1839:           if (orderEff < 0) continue;
1840:           PetscDualSpaceGetDimension_SingleCell_Lagrange(sp, orderEff, &cdim);
1841:           DMPlexVecGetClosure(dm, csection, coordinates, p, &csize, &coords);
1842:           if (csize%dim) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Coordinate size %d is not divisible by spatial dimension %d", csize, dim);

1844:           PetscCalloc5(dim,&ind,dim,&tup,dim,&v0,dim*dim,&J,dim*dim,&invJ);
1845:           DMPlexComputeCellGeometryFEM(dm, p, NULL, v0, J, invJ, &detJ);
1846:           if (simplex || disc) {
1847:             for (o = 0; o <= orderEff; ++o) {
1848:               PetscMemzero(ind, dim*sizeof(PetscInt));
1849:               while (ind[0] >= 0) {
1850:                 PetscQuadratureCreate(PETSC_COMM_SELF, &sp->functional[f]);
1851:                 PetscMalloc1(dim, &qpoints);
1852:                 PetscMalloc1(1,   &qweights);
1853:                 PetscQuadratureSetOrder(sp->functional[f], 0);
1854:                 PetscQuadratureSetData(sp->functional[f], dim, 1, qpoints, qweights);
1855:                 LatticePoint_Internal(dim, o, ind, tup);
1856:                 for (d = 0; d < dim; ++d) {
1857:                   qpoints[d] = v0[d];
1858:                   for (d2 = 0; d2 < dim; ++d2) qpoints[d] += J[d*dim+d2]*((tup[d2]+1)*dx);
1859:                 }
1860:                 qweights[0] = 1.0;
1861:                 ++f;
1862:               }
1863:             }
1864:           } else {
1865:             while (ind[0] >= 0) {
1866:               PetscQuadratureCreate(PETSC_COMM_SELF, &sp->functional[f]);
1867:               PetscMalloc1(dim, &qpoints);
1868:               PetscMalloc1(1,   &qweights);
1869:               PetscQuadratureSetOrder(sp->functional[f], 0);
1870:               PetscQuadratureSetData(sp->functional[f], dim, 1, qpoints, qweights);
1871:               TensorPoint_Internal(dim, orderEff+1, ind, tup);
1872:               for (d = 0; d < dim; ++d) {
1873:                 qpoints[d] = v0[d];
1874:                 for (d2 = 0; d2 < dim; ++d2) qpoints[d] += J[d*dim+d2]*((tup[d]+1)*dx);
1875:               }
1876:               qweights[0] = 1.0;
1877:               ++f;
1878:             }
1879:           }
1880:           PetscFree5(ind,tup,v0,J,invJ);
1881:           DMPlexVecRestoreClosure(dm, csection, coordinates, p, &csize, &coords);
1882:           lag->numDof[depth] = cdim;
1883:         }
1884:       }
1885:       DMPlexRestoreTransitiveClosure(dm, pStart[depth], PETSC_TRUE, &closureSize, &closure);
1886:     }
1887:     PetscBTDestroy(&seen);
1888:   }
1889:   if (pEnd[dim] == 1 && f != pdimMax) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of dual basis vectors %d not equal to dimension %d", f, pdimMax);
1890:   PetscFree2(pStart,pEnd);
1891:   if (f > pdimMax) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of dual basis vectors %d is greater than dimension %d", f, pdimMax);
1892:   return(0);
1893: }

1897: PetscErrorCode PetscDualSpaceDestroy_Lagrange(PetscDualSpace sp)
1898: {
1899:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;
1900:   PetscErrorCode      ierr;

1903:   PetscFree(lag->numDof);
1904:   PetscFree(lag);
1905:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceLagrangeGetContinuity_C", NULL);
1906:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceLagrangeSetContinuity_C", NULL);
1907:   return(0);
1908: }

1912: PetscErrorCode PetscDualSpaceDuplicate_Lagrange(PetscDualSpace sp, PetscDualSpace *spNew)
1913: {
1914:   PetscInt       order;
1915:   PetscBool      cont;

1919:   PetscDualSpaceCreate(PetscObjectComm((PetscObject) sp), spNew);
1920:   PetscDualSpaceSetType(*spNew, PETSCDUALSPACELAGRANGE);
1921:   PetscDualSpaceGetOrder(sp, &order);
1922:   PetscDualSpaceSetOrder(*spNew, order);
1923:   PetscDualSpaceLagrangeGetContinuity(sp, &cont);
1924:   PetscDualSpaceLagrangeSetContinuity(*spNew, cont);
1925:   return(0);
1926: }

1930: PetscErrorCode PetscDualSpaceSetFromOptions_Lagrange(PetscOptionItems *PetscOptionsObject,PetscDualSpace sp)
1931: {
1932:   PetscBool      continuous, flg;

1936:   PetscDualSpaceLagrangeGetContinuity(sp, &continuous);
1937:   PetscOptionsHead(PetscOptionsObject,"PetscDualSpace Lagrange Options");
1938:   PetscOptionsBool("-petscdualspace_lagrange_continuity", "Flag for continuous element", "PetscDualSpaceLagrangeSetContinuity", continuous, &continuous, &flg);
1939:   if (flg) {PetscDualSpaceLagrangeSetContinuity(sp, continuous);}
1940:   PetscOptionsTail();
1941:   return(0);
1942: }

1946: PetscErrorCode PetscDualSpaceGetDimension_Lagrange(PetscDualSpace sp, PetscInt *dim)
1947: {
1948:   DM              K;
1949:   const PetscInt *numDof;
1950:   PetscInt        spatialDim, Nc, size = 0, d;
1951:   PetscErrorCode  ierr;

1954:   PetscDualSpaceGetDM(sp, &K);
1955:   PetscDualSpaceGetNumDof(sp, &numDof);
1956:   DMGetDimension(K, &spatialDim);
1957:   DMPlexGetHeightStratum(K, 0, NULL, &Nc);
1958:   if (Nc == 1) {PetscDualSpaceGetDimension_SingleCell_Lagrange(sp, sp->order, dim); return(0);}
1959:   for (d = 0; d <= spatialDim; ++d) {
1960:     PetscInt pStart, pEnd;

1962:     DMPlexGetDepthStratum(K, d, &pStart, &pEnd);
1963:     size += (pEnd-pStart)*numDof[d];
1964:   }
1965:   *dim = size;
1966:   return(0);
1967: }

1971: PetscErrorCode PetscDualSpaceGetNumDof_Lagrange(PetscDualSpace sp, const PetscInt **numDof)
1972: {
1973:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;

1976:   *numDof = lag->numDof;
1977:   return(0);
1978: }

1982: static PetscErrorCode PetscDualSpaceLagrangeGetContinuity_Lagrange(PetscDualSpace sp, PetscBool *continuous)
1983: {
1984:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;

1989:   *continuous = lag->continuous;
1990:   return(0);
1991: }

1995: static PetscErrorCode PetscDualSpaceLagrangeSetContinuity_Lagrange(PetscDualSpace sp, PetscBool continuous)
1996: {
1997:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;

2001:   lag->continuous = continuous;
2002:   return(0);
2003: }

2007: /*@
2008:   PetscDualSpaceLagrangeGetContinuity - Retrieves the flag for element continuity

2010:   Not Collective

2012:   Input Parameter:
2013: . sp         - the PetscDualSpace

2015:   Output Parameter:
2016: . continuous - flag for element continuity

2018:   Level: intermediate

2020: .keywords: PetscDualSpace, Lagrange, continuous, discontinuous
2021: .seealso: PetscDualSpaceLagrangeSetContinuity()
2022: @*/
2023: PetscErrorCode PetscDualSpaceLagrangeGetContinuity(PetscDualSpace sp, PetscBool *continuous)
2024: {

2030:   PetscTryMethod(sp, "PetscDualSpaceLagrangeGetContinuity_C", (PetscDualSpace,PetscBool*),(sp,continuous));
2031:   return(0);
2032: }

2036: /*@
2037:   PetscDualSpaceLagrangeSetContinuity - Indicate whether the element is continuous

2039:   Logically Collective on PetscDualSpace

2041:   Input Parameters:
2042: + sp         - the PetscDualSpace
2043: - continuous - flag for element continuity

2045:   Options Database:
2046: . -petscdualspace_lagrange_continuity <bool>

2048:   Level: intermediate

2050: .keywords: PetscDualSpace, Lagrange, continuous, discontinuous
2051: .seealso: PetscDualSpaceLagrangeGetContinuity()
2052: @*/
2053: PetscErrorCode PetscDualSpaceLagrangeSetContinuity(PetscDualSpace sp, PetscBool continuous)
2054: {

2060:   PetscTryMethod(sp, "PetscDualSpaceLagrangeSetContinuity_C", (PetscDualSpace,PetscBool),(sp,continuous));
2061:   return(0);
2062: }

2066: PetscErrorCode PetscDualSpaceGetHeightSubspace_Lagrange(PetscDualSpace sp, PetscInt height, PetscDualSpace *bdsp)
2067: {
2068:   PetscDualSpace_Lag *lag = (PetscDualSpace_Lag *) sp->data;
2069:   PetscBool          continuous;
2070:   PetscInt           order;
2071:   PetscErrorCode     ierr;

2076:   PetscDualSpaceLagrangeGetContinuity(sp,&continuous);
2077:   PetscDualSpaceGetOrder(sp,&order);
2078:   if (height == 0) {
2079:     PetscObjectReference((PetscObject)sp);
2080:     *bdsp = sp;
2081:   }
2082:   else if (continuous == PETSC_FALSE || !order) {
2083:     *bdsp = NULL;
2084:   }
2085:   else {
2086:     DM dm, K;
2087:     PetscInt dim;

2089:     PetscDualSpaceGetDM(sp,&dm);
2090:     DMGetDimension(dm,&dim);
2091:     if (height > dim || height < 0) {SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Asked for dual space at height %d for dimension %d reference element\n",height,dim);}
2092:     PetscDualSpaceDuplicate(sp,bdsp);
2093:     PetscDualSpaceCreateReferenceCell(*bdsp, dim-height, lag->simplex, &K);
2094:     PetscDualSpaceSetDM(*bdsp, K);
2095:     DMDestroy(&K);
2096:     PetscDualSpaceSetUp(*bdsp);
2097:   }
2098:   return(0);
2099: }

2103: PetscErrorCode PetscDualSpaceInitialize_Lagrange(PetscDualSpace sp)
2104: {
2106:   sp->ops->setfromoptions    = PetscDualSpaceSetFromOptions_Lagrange;
2107:   sp->ops->setup             = PetscDualSpaceSetUp_Lagrange;
2108:   sp->ops->view              = NULL;
2109:   sp->ops->destroy           = PetscDualSpaceDestroy_Lagrange;
2110:   sp->ops->duplicate         = PetscDualSpaceDuplicate_Lagrange;
2111:   sp->ops->getdimension      = PetscDualSpaceGetDimension_Lagrange;
2112:   sp->ops->getnumdof         = PetscDualSpaceGetNumDof_Lagrange;
2113:   sp->ops->getheightsubspace = PetscDualSpaceGetHeightSubspace_Lagrange;
2114:   return(0);
2115: }

2117: /*MC
2118:   PETSCDUALSPACELAGRANGE = "lagrange" - A PetscDualSpace object that encapsulates a dual space of pointwise evaluation functionals

2120:   Level: intermediate

2122: .seealso: PetscDualSpaceType, PetscDualSpaceCreate(), PetscDualSpaceSetType()
2123: M*/

2127: PETSC_EXTERN PetscErrorCode PetscDualSpaceCreate_Lagrange(PetscDualSpace sp)
2128: {
2129:   PetscDualSpace_Lag *lag;
2130:   PetscErrorCode      ierr;

2134:   PetscNewLog(sp,&lag);
2135:   sp->data = lag;

2137:   lag->numDof     = NULL;
2138:   lag->simplex    = PETSC_TRUE;
2139:   lag->continuous = PETSC_TRUE;

2141:   PetscDualSpaceInitialize_Lagrange(sp);
2142:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceLagrangeGetContinuity_C", PetscDualSpaceLagrangeGetContinuity_Lagrange);
2143:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceLagrangeSetContinuity_C", PetscDualSpaceLagrangeSetContinuity_Lagrange);
2144:   return(0);
2145: }

2149: PetscErrorCode PetscDualSpaceSetUp_Simple(PetscDualSpace sp)
2150: {
2152:   return(0);
2153: }

2157: PetscErrorCode PetscDualSpaceDestroy_Simple(PetscDualSpace sp)
2158: {
2159:   PetscDualSpace_Simple *s = (PetscDualSpace_Simple *) sp->data;
2160:   PetscErrorCode         ierr;

2163:   PetscFree(s);
2164:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceSimpleSetDimension_C", NULL);
2165:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceSimpleSetFunctional_C", NULL);
2166:   return(0);
2167: }

2171: PetscErrorCode PetscDualSpaceDuplicate_Simple(PetscDualSpace sp, PetscDualSpace *spNew)
2172: {
2173:   PetscInt       dim, d;

2177:   PetscDualSpaceCreate(PetscObjectComm((PetscObject) sp), spNew);
2178:   PetscDualSpaceSetType(*spNew, PETSCDUALSPACESIMPLE);
2179:   PetscDualSpaceGetDimension(sp, &dim);
2180:   PetscDualSpaceSimpleSetDimension(*spNew, dim);
2181:   for (d = 0; d < dim; ++d) {
2182:     PetscQuadrature q;

2184:     PetscDualSpaceGetFunctional(sp, d, &q);
2185:     PetscDualSpaceSimpleSetFunctional(*spNew, d, q);
2186:   }
2187:   return(0);
2188: }

2192: PetscErrorCode PetscDualSpaceSetFromOptions_Simple(PetscOptionItems *PetscOptionsObject,PetscDualSpace sp)
2193: {
2195:   return(0);
2196: }

2200: PetscErrorCode PetscDualSpaceGetDimension_Simple(PetscDualSpace sp, PetscInt *dim)
2201: {
2202:   PetscDualSpace_Simple *s = (PetscDualSpace_Simple *) sp->data;

2205:   *dim = s->dim;
2206:   return(0);
2207: }

2211: PetscErrorCode PetscDualSpaceSimpleSetDimension_Simple(PetscDualSpace sp, const PetscInt dim)
2212: {
2213:   PetscDualSpace_Simple *s = (PetscDualSpace_Simple *) sp->data;
2214:   PetscInt               f;
2215:   PetscErrorCode         ierr;

2218:   for (f = 0; f < s->dim; ++f) {PetscQuadratureDestroy(&sp->functional[f]);}
2219:   PetscFree(sp->functional);
2220:   s->dim = dim;
2221:   PetscCalloc1(s->dim, &sp->functional);
2222:   return(0);
2223: }

2227: PetscErrorCode PetscDualSpaceSimpleSetFunctional_Simple(PetscDualSpace sp, PetscInt f, PetscQuadrature q)
2228: {
2229:   PetscDualSpace_Simple *s   = (PetscDualSpace_Simple *) sp->data;
2230:   PetscReal              vol = 0.0;
2231:   PetscReal             *weights;
2232:   PetscInt               Nq, p;
2233:   PetscErrorCode         ierr;

2236:   if ((f < 0) || (f >= s->dim)) SETERRQ2(PetscObjectComm((PetscObject) sp), PETSC_ERR_ARG_OUTOFRANGE, "Basis index %d not in [0, %d)", f, s->dim);
2237:   PetscQuadratureDuplicate(q, &sp->functional[f]);
2238:   /* Reweight so that it has unit volume */
2239:   PetscQuadratureGetData(sp->functional[f], NULL, &Nq, NULL, (const PetscReal **) &weights);
2240:   for (p = 0; p < Nq; ++p) vol += weights[p];
2241:   for (p = 0; p < Nq; ++p) weights[p] /= vol;
2242:   return(0);
2243: }

2247: /*@
2248:   PetscDualSpaceSimpleSetDimension - Set the number of functionals in the dual space basis

2250:   Logically Collective on PetscDualSpace

2252:   Input Parameters:
2253: + sp  - the PetscDualSpace
2254: - dim - the basis dimension

2256:   Level: intermediate

2258: .keywords: PetscDualSpace, dimension
2259: .seealso: PetscDualSpaceSimpleSetFunctional()
2260: @*/
2261: PetscErrorCode PetscDualSpaceSimpleSetDimension(PetscDualSpace sp, PetscInt dim)
2262: {

2268:   PetscTryMethod(sp, "PetscDualSpaceSimpleSetDimension_C", (PetscDualSpace,PetscInt),(sp,dim));
2269:   return(0);
2270: }

2274: /*@
2275:   PetscDualSpaceSimpleSetFunctional - Set the given basis element for this dual space

2277:   Not Collective

2279:   Input Parameters:
2280: + sp  - the PetscDualSpace
2281: . f - the basis index
2282: - q - the basis functional

2284:   Level: intermediate

2286:   Note: The quadrature will be reweighted so that it has unit volume.

2288: .keywords: PetscDualSpace, functional
2289: .seealso: PetscDualSpaceSimpleSetDimension()
2290: @*/
2291: PetscErrorCode PetscDualSpaceSimpleSetFunctional(PetscDualSpace sp, PetscInt func, PetscQuadrature q)
2292: {

2297:   PetscTryMethod(sp, "PetscDualSpaceSimpleSetFunctional_C", (PetscDualSpace,PetscInt,PetscQuadrature),(sp,func,q));
2298:   return(0);
2299: }

2303: PetscErrorCode PetscDualSpaceInitialize_Simple(PetscDualSpace sp)
2304: {
2306:   sp->ops->setfromoptions = PetscDualSpaceSetFromOptions_Simple;
2307:   sp->ops->setup          = PetscDualSpaceSetUp_Simple;
2308:   sp->ops->view           = NULL;
2309:   sp->ops->destroy        = PetscDualSpaceDestroy_Simple;
2310:   sp->ops->duplicate      = PetscDualSpaceDuplicate_Simple;
2311:   sp->ops->getdimension   = PetscDualSpaceGetDimension_Simple;
2312:   sp->ops->getnumdof      = NULL;
2313:   return(0);
2314: }

2316: /*MC
2317:   PETSCDUALSPACESIMPLE = "simple" - A PetscDualSpace object that encapsulates a dual space of arbitrary functionals

2319:   Level: intermediate

2321: .seealso: PetscDualSpaceType, PetscDualSpaceCreate(), PetscDualSpaceSetType()
2322: M*/

2326: PETSC_EXTERN PetscErrorCode PetscDualSpaceCreate_Simple(PetscDualSpace sp)
2327: {
2328:   PetscDualSpace_Simple *s;
2329:   PetscErrorCode         ierr;

2333:   PetscNewLog(sp,&s);
2334:   sp->data = s;

2336:   s->dim = 0;

2338:   PetscDualSpaceInitialize_Simple(sp);
2339:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceSimpleSetDimension_C", PetscDualSpaceSimpleSetDimension_Simple);
2340:   PetscObjectComposeFunction((PetscObject) sp, "PetscDualSpaceSimpleSetFunctional_C", PetscDualSpaceSimpleSetFunctional_Simple);
2341:   return(0);
2342: }


2345: PetscClassId PETSCFE_CLASSID = 0;

2347: PetscFunctionList PetscFEList              = NULL;
2348: PetscBool         PetscFERegisterAllCalled = PETSC_FALSE;

2352: /*@C
2353:   PetscFERegister - Adds a new PetscFE implementation

2355:   Not Collective

2357:   Input Parameters:
2358: + name        - The name of a new user-defined creation routine
2359: - create_func - The creation routine itself

2361:   Notes:
2362:   PetscFERegister() may be called multiple times to add several user-defined PetscFEs

2364:   Sample usage:
2365: .vb
2366:     PetscFERegister("my_fe", MyPetscFECreate);
2367: .ve

2369:   Then, your PetscFE type can be chosen with the procedural interface via
2370: .vb
2371:     PetscFECreate(MPI_Comm, PetscFE *);
2372:     PetscFESetType(PetscFE, "my_fe");
2373: .ve
2374:    or at runtime via the option
2375: .vb
2376:     -petscfe_type my_fe
2377: .ve

2379:   Level: advanced

2381: .keywords: PetscFE, register
2382: .seealso: PetscFERegisterAll(), PetscFERegisterDestroy()

2384: @*/
2385: PetscErrorCode PetscFERegister(const char sname[], PetscErrorCode (*function)(PetscFE))
2386: {

2390:   PetscFunctionListAdd(&PetscFEList, sname, function);
2391:   return(0);
2392: }

2396: /*@C
2397:   PetscFESetType - Builds a particular PetscFE

2399:   Collective on PetscFE

2401:   Input Parameters:
2402: + fem  - The PetscFE object
2403: - name - The kind of FEM space

2405:   Options Database Key:
2406: . -petscfe_type <type> - Sets the PetscFE type; use -help for a list of available types

2408:   Level: intermediate

2410: .keywords: PetscFE, set, type
2411: .seealso: PetscFEGetType(), PetscFECreate()
2412: @*/
2413: PetscErrorCode PetscFESetType(PetscFE fem, PetscFEType name)
2414: {
2415:   PetscErrorCode (*r)(PetscFE);
2416:   PetscBool      match;

2421:   PetscObjectTypeCompare((PetscObject) fem, name, &match);
2422:   if (match) return(0);

2424:   if (!PetscFERegisterAllCalled) {PetscFERegisterAll();}
2425:   PetscFunctionListFind(PetscFEList, name, &r);
2426:   if (!r) SETERRQ1(PetscObjectComm((PetscObject) fem), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown PetscFE type: %s", name);

2428:   if (fem->ops->destroy) {
2429:     (*fem->ops->destroy)(fem);
2430:     fem->ops->destroy = NULL;
2431:   }
2432:   (*r)(fem);
2433:   PetscObjectChangeTypeName((PetscObject) fem, name);
2434:   return(0);
2435: }

2439: /*@C
2440:   PetscFEGetType - Gets the PetscFE type name (as a string) from the object.

2442:   Not Collective

2444:   Input Parameter:
2445: . fem  - The PetscFE

2447:   Output Parameter:
2448: . name - The PetscFE type name

2450:   Level: intermediate

2452: .keywords: PetscFE, get, type, name
2453: .seealso: PetscFESetType(), PetscFECreate()
2454: @*/
2455: PetscErrorCode PetscFEGetType(PetscFE fem, PetscFEType *name)
2456: {

2462:   if (!PetscFERegisterAllCalled) {
2463:     PetscFERegisterAll();
2464:   }
2465:   *name = ((PetscObject) fem)->type_name;
2466:   return(0);
2467: }

2471: /*@C
2472:   PetscFEView - Views a PetscFE

2474:   Collective on PetscFE

2476:   Input Parameter:
2477: + fem - the PetscFE object to view
2478: - v   - the viewer

2480:   Level: developer

2482: .seealso PetscFEDestroy()
2483: @*/
2484: PetscErrorCode PetscFEView(PetscFE fem, PetscViewer v)
2485: {

2490:   if (!v) {
2491:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject) fem), &v);
2492:   }
2493:   if (fem->ops->view) {
2494:     (*fem->ops->view)(fem, v);
2495:   }
2496:   return(0);
2497: }

2501: /*@
2502:   PetscFESetFromOptions - sets parameters in a PetscFE from the options database

2504:   Collective on PetscFE

2506:   Input Parameter:
2507: . fem - the PetscFE object to set options for

2509:   Options Database:
2510: . -petscfe_num_blocks  the number of cell blocks to integrate concurrently
2511: . -petscfe_num_batches the number of cell batches to integrate serially

2513:   Level: developer

2515: .seealso PetscFEView()
2516: @*/
2517: PetscErrorCode PetscFESetFromOptions(PetscFE fem)
2518: {
2519:   const char    *defaultType;
2520:   char           name[256];
2521:   PetscBool      flg;

2526:   if (!((PetscObject) fem)->type_name) {
2527:     defaultType = PETSCFEBASIC;
2528:   } else {
2529:     defaultType = ((PetscObject) fem)->type_name;
2530:   }
2531:   if (!PetscFERegisterAllCalled) {PetscFERegisterAll();}

2533:   PetscObjectOptionsBegin((PetscObject) fem);
2534:   PetscOptionsFList("-petscfe_type", "Finite element space", "PetscFESetType", PetscFEList, defaultType, name, 256, &flg);
2535:   if (flg) {
2536:     PetscFESetType(fem, name);
2537:   } else if (!((PetscObject) fem)->type_name) {
2538:     PetscFESetType(fem, defaultType);
2539:   }
2540:   PetscOptionsInt("-petscfe_num_blocks", "The number of cell blocks to integrate concurrently", "PetscSpaceSetTileSizes", fem->numBlocks, &fem->numBlocks, NULL);
2541:   PetscOptionsInt("-petscfe_num_batches", "The number of cell batches to integrate serially", "PetscSpaceSetTileSizes", fem->numBatches, &fem->numBatches, NULL);
2542:   if (fem->ops->setfromoptions) {
2543:     (*fem->ops->setfromoptions)(PetscOptionsObject,fem);
2544:   }
2545:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
2546:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject) fem);
2547:   PetscOptionsEnd();
2548:   PetscFEViewFromOptions(fem, NULL, "-petscfe_view");
2549:   return(0);
2550: }

2554: /*@C
2555:   PetscFESetUp - Construct data structures for the PetscFE

2557:   Collective on PetscFE

2559:   Input Parameter:
2560: . fem - the PetscFE object to setup

2562:   Level: developer

2564: .seealso PetscFEView(), PetscFEDestroy()
2565: @*/
2566: PetscErrorCode PetscFESetUp(PetscFE fem)
2567: {

2572:   if (fem->ops->setup) {(*fem->ops->setup)(fem);}
2573:   return(0);
2574: }

2578: /*@
2579:   PetscFEDestroy - Destroys a PetscFE object

2581:   Collective on PetscFE

2583:   Input Parameter:
2584: . fem - the PetscFE object to destroy

2586:   Level: developer

2588: .seealso PetscFEView()
2589: @*/
2590: PetscErrorCode PetscFEDestroy(PetscFE *fem)
2591: {

2595:   if (!*fem) return(0);

2598:   if (--((PetscObject)(*fem))->refct > 0) {*fem = 0; return(0);}
2599:   ((PetscObject) (*fem))->refct = 0;

2601:   PetscFree((*fem)->numDof);
2602:   PetscFree((*fem)->invV);
2603:   PetscFERestoreTabulation((*fem), 0, NULL, &(*fem)->B, &(*fem)->D, NULL /*&(*fem)->H*/);
2604:   PetscFERestoreTabulation((*fem), 0, NULL, &(*fem)->F, NULL, NULL);
2605:   PetscSpaceDestroy(&(*fem)->basisSpace);
2606:   PetscDualSpaceDestroy(&(*fem)->dualSpace);
2607:   PetscQuadratureDestroy(&(*fem)->quadrature);

2609:   if ((*fem)->ops->destroy) {(*(*fem)->ops->destroy)(*fem);}
2610:   PetscHeaderDestroy(fem);
2611:   return(0);
2612: }

2616: /*@
2617:   PetscFECreate - Creates an empty PetscFE object. The type can then be set with PetscFESetType().

2619:   Collective on MPI_Comm

2621:   Input Parameter:
2622: . comm - The communicator for the PetscFE object

2624:   Output Parameter:
2625: . fem - The PetscFE object

2627:   Level: beginner

2629: .seealso: PetscFESetType(), PETSCFEGALERKIN
2630: @*/
2631: PetscErrorCode PetscFECreate(MPI_Comm comm, PetscFE *fem)
2632: {
2633:   PetscFE        f;

2638:   PetscCitationsRegister(FECitation,&FEcite);
2639:   *fem = NULL;
2640:   PetscFEInitializePackage();

2642:   PetscHeaderCreate(f, PETSCFE_CLASSID, "PetscFE", "Finite Element", "PetscFE", comm, PetscFEDestroy, PetscFEView);

2644:   f->basisSpace    = NULL;
2645:   f->dualSpace     = NULL;
2646:   f->numComponents = 1;
2647:   f->numDof        = NULL;
2648:   f->invV          = NULL;
2649:   f->B             = NULL;
2650:   f->D             = NULL;
2651:   f->H             = NULL;
2652:   PetscMemzero(&f->quadrature, sizeof(PetscQuadrature));
2653:   f->blockSize     = 0;
2654:   f->numBlocks     = 1;
2655:   f->batchSize     = 0;
2656:   f->numBatches    = 1;

2658:   *fem = f;
2659:   return(0);
2660: }

2664: /*@
2665:   PetscFEGetSpatialDimension - Returns the spatial dimension of the element

2667:   Not collective

2669:   Input Parameter:
2670: . fem - The PetscFE object

2672:   Output Parameter:
2673: . dim - The spatial dimension

2675:   Level: intermediate

2677: .seealso: PetscFECreate()
2678: @*/
2679: PetscErrorCode PetscFEGetSpatialDimension(PetscFE fem, PetscInt *dim)
2680: {
2681:   DM             dm;

2687:   PetscDualSpaceGetDM(fem->dualSpace, &dm);
2688:   DMGetDimension(dm, dim);
2689:   return(0);
2690: }

2694: /*@
2695:   PetscFESetNumComponents - Sets the number of components in the element

2697:   Not collective

2699:   Input Parameters:
2700: + fem - The PetscFE object
2701: - comp - The number of field components

2703:   Level: intermediate

2705: .seealso: PetscFECreate()
2706: @*/
2707: PetscErrorCode PetscFESetNumComponents(PetscFE fem, PetscInt comp)
2708: {
2711:   fem->numComponents = comp;
2712:   return(0);
2713: }

2717: /*@
2718:   PetscFEGetNumComponents - Returns the number of components in the element

2720:   Not collective

2722:   Input Parameter:
2723: . fem - The PetscFE object

2725:   Output Parameter:
2726: . comp - The number of field components

2728:   Level: intermediate

2730: .seealso: PetscFECreate()
2731: @*/
2732: PetscErrorCode PetscFEGetNumComponents(PetscFE fem, PetscInt *comp)
2733: {
2737:   *comp = fem->numComponents;
2738:   return(0);
2739: }

2743: /*@
2744:   PetscFESetTileSizes - Sets the tile sizes for evaluation

2746:   Not collective

2748:   Input Parameters:
2749: + fem - The PetscFE object
2750: . blockSize - The number of elements in a block
2751: . numBlocks - The number of blocks in a batch
2752: . batchSize - The number of elements in a batch
2753: - numBatches - The number of batches in a chunk

2755:   Level: intermediate

2757: .seealso: PetscFECreate()
2758: @*/
2759: PetscErrorCode PetscFESetTileSizes(PetscFE fem, PetscInt blockSize, PetscInt numBlocks, PetscInt batchSize, PetscInt numBatches)
2760: {
2763:   fem->blockSize  = blockSize;
2764:   fem->numBlocks  = numBlocks;
2765:   fem->batchSize  = batchSize;
2766:   fem->numBatches = numBatches;
2767:   return(0);
2768: }

2772: /*@
2773:   PetscFEGetTileSizes - Returns the tile sizes for evaluation

2775:   Not collective

2777:   Input Parameter:
2778: . fem - The PetscFE object

2780:   Output Parameters:
2781: + blockSize - The number of elements in a block
2782: . numBlocks - The number of blocks in a batch
2783: . batchSize - The number of elements in a batch
2784: - numBatches - The number of batches in a chunk

2786:   Level: intermediate

2788: .seealso: PetscFECreate()
2789: @*/
2790: PetscErrorCode PetscFEGetTileSizes(PetscFE fem, PetscInt *blockSize, PetscInt *numBlocks, PetscInt *batchSize, PetscInt *numBatches)
2791: {
2798:   if (blockSize)  *blockSize  = fem->blockSize;
2799:   if (numBlocks)  *numBlocks  = fem->numBlocks;
2800:   if (batchSize)  *batchSize  = fem->batchSize;
2801:   if (numBatches) *numBatches = fem->numBatches;
2802:   return(0);
2803: }

2807: /*@
2808:   PetscFEGetBasisSpace - Returns the PetscSpace used for approximation of the solution

2810:   Not collective

2812:   Input Parameter:
2813: . fem - The PetscFE object

2815:   Output Parameter:
2816: . sp - The PetscSpace object

2818:   Level: intermediate

2820: .seealso: PetscFECreate()
2821: @*/
2822: PetscErrorCode PetscFEGetBasisSpace(PetscFE fem, PetscSpace *sp)
2823: {
2827:   *sp = fem->basisSpace;
2828:   return(0);
2829: }

2833: /*@
2834:   PetscFESetBasisSpace - Sets the PetscSpace used for approximation of the solution

2836:   Not collective

2838:   Input Parameters:
2839: + fem - The PetscFE object
2840: - sp - The PetscSpace object

2842:   Level: intermediate

2844: .seealso: PetscFECreate()
2845: @*/
2846: PetscErrorCode PetscFESetBasisSpace(PetscFE fem, PetscSpace sp)
2847: {

2853:   PetscSpaceDestroy(&fem->basisSpace);
2854:   fem->basisSpace = sp;
2855:   PetscObjectReference((PetscObject) fem->basisSpace);
2856:   return(0);
2857: }

2861: /*@
2862:   PetscFEGetDualSpace - Returns the PetscDualSpace used to define the inner product

2864:   Not collective

2866:   Input Parameter:
2867: . fem - The PetscFE object

2869:   Output Parameter:
2870: . sp - The PetscDualSpace object

2872:   Level: intermediate

2874: .seealso: PetscFECreate()
2875: @*/
2876: PetscErrorCode PetscFEGetDualSpace(PetscFE fem, PetscDualSpace *sp)
2877: {
2881:   *sp = fem->dualSpace;
2882:   return(0);
2883: }

2887: /*@
2888:   PetscFESetDualSpace - Sets the PetscDualSpace used to define the inner product

2890:   Not collective

2892:   Input Parameters:
2893: + fem - The PetscFE object
2894: - sp - The PetscDualSpace object

2896:   Level: intermediate

2898: .seealso: PetscFECreate()
2899: @*/
2900: PetscErrorCode PetscFESetDualSpace(PetscFE fem, PetscDualSpace sp)
2901: {

2907:   PetscDualSpaceDestroy(&fem->dualSpace);
2908:   fem->dualSpace = sp;
2909:   PetscObjectReference((PetscObject) fem->dualSpace);
2910:   return(0);
2911: }

2915: /*@
2916:   PetscFEGetQuadrature - Returns the PetscQuadreture used to calculate inner products

2918:   Not collective

2920:   Input Parameter:
2921: . fem - The PetscFE object

2923:   Output Parameter:
2924: . q - The PetscQuadrature object

2926:   Level: intermediate

2928: .seealso: PetscFECreate()
2929: @*/
2930: PetscErrorCode PetscFEGetQuadrature(PetscFE fem, PetscQuadrature *q)
2931: {
2935:   *q = fem->quadrature;
2936:   return(0);
2937: }

2941: /*@
2942:   PetscFESetQuadrature - Sets the PetscQuadreture used to calculate inner products

2944:   Not collective

2946:   Input Parameters:
2947: + fem - The PetscFE object
2948: - q - The PetscQuadrature object

2950:   Level: intermediate

2952: .seealso: PetscFECreate()
2953: @*/
2954: PetscErrorCode PetscFESetQuadrature(PetscFE fem, PetscQuadrature q)
2955: {

2960:   PetscFERestoreTabulation(fem, 0, NULL, &fem->B, &fem->D, NULL /*&(*fem)->H*/);
2961:   PetscQuadratureDestroy(&fem->quadrature);
2962:   fem->quadrature = q;
2963:   PetscObjectReference((PetscObject) q);
2964:   return(0);
2965: }

2969: PetscErrorCode PetscFEGetNumDof(PetscFE fem, const PetscInt **numDof)
2970: {
2971:   const PetscInt *numDofDual;
2972:   PetscErrorCode  ierr;

2977:   PetscDualSpaceGetNumDof(fem->dualSpace, &numDofDual);
2978:   if (!fem->numDof) {
2979:     DM       dm;
2980:     PetscInt dim, d;

2982:     PetscDualSpaceGetDM(fem->dualSpace, &dm);
2983:     DMGetDimension(dm, &dim);
2984:     PetscMalloc1(dim+1, &fem->numDof);
2985:     for (d = 0; d <= dim; ++d) {
2986:       fem->numDof[d] = fem->numComponents*numDofDual[d];
2987:     }
2988:   }
2989:   *numDof = fem->numDof;
2990:   return(0);
2991: }

2995: PetscErrorCode PetscFEGetDefaultTabulation(PetscFE fem, PetscReal **B, PetscReal **D, PetscReal **H)
2996: {
2997:   PetscInt         npoints;
2998:   const PetscReal *points;
2999:   PetscErrorCode   ierr;

3006:   PetscQuadratureGetData(fem->quadrature, NULL, &npoints, &points, NULL);
3007:   if (!fem->B) {PetscFEGetTabulation(fem, npoints, points, &fem->B, &fem->D, NULL/*&fem->H*/);}
3008:   if (B) *B = fem->B;
3009:   if (D) *D = fem->D;
3010:   if (H) *H = fem->H;
3011:   return(0);
3012: }

3016: PetscErrorCode PetscFEGetFaceTabulation(PetscFE fem, PetscReal **F)
3017: {
3018:   PetscErrorCode   ierr;

3023:   if (!fem->F) {
3024:     PetscDualSpace  sp;
3025:     DM              dm;
3026:     const PetscInt *cone;
3027:     PetscReal      *centroids;
3028:     PetscInt        dim, numFaces, f;

3030:     PetscFEGetDualSpace(fem, &sp);
3031:     PetscDualSpaceGetDM(sp, &dm);
3032:     DMGetDimension(dm, &dim);
3033:     DMPlexGetConeSize(dm, 0, &numFaces);
3034:     DMPlexGetCone(dm, 0, &cone);
3035:     PetscMalloc1(numFaces*dim, &centroids);
3036:     for (f = 0; f < numFaces; ++f) {DMPlexComputeCellGeometryFVM(dm, cone[f], NULL, &centroids[f*dim], NULL);}
3037:     PetscFEGetTabulation(fem, numFaces, centroids, &fem->F, NULL, NULL);
3038:     PetscFree(centroids);
3039:   }
3040:   *F = fem->F;
3041:   return(0);
3042: }

3046: PetscErrorCode PetscFEGetTabulation(PetscFE fem, PetscInt npoints, const PetscReal points[], PetscReal **B, PetscReal **D, PetscReal **H)
3047: {
3048:   DM               dm;
3049:   PetscInt         pdim; /* Dimension of FE space P */
3050:   PetscInt         dim;  /* Spatial dimension */
3051:   PetscInt         comp; /* Field components */
3052:   PetscErrorCode   ierr;

3060:   PetscDualSpaceGetDM(fem->dualSpace, &dm);
3061:   DMGetDimension(dm, &dim);
3062:   PetscDualSpaceGetDimension(fem->dualSpace, &pdim);
3063:   PetscFEGetNumComponents(fem, &comp);
3064:   if (B) {DMGetWorkArray(dm, npoints*pdim*comp, PETSC_REAL, B);}
3065:   if (D) {DMGetWorkArray(dm, npoints*pdim*comp*dim, PETSC_REAL, D);}
3066:   if (H) {DMGetWorkArray(dm, npoints*pdim*comp*dim*dim, PETSC_REAL, H);}
3067:   (*fem->ops->gettabulation)(fem, npoints, points, B ? *B : NULL, D ? *D : NULL, H ? *H : NULL);
3068:   return(0);
3069: }

3073: PetscErrorCode PetscFERestoreTabulation(PetscFE fem, PetscInt npoints, const PetscReal points[], PetscReal **B, PetscReal **D, PetscReal **H)
3074: {
3075:   DM             dm;

3080:   PetscDualSpaceGetDM(fem->dualSpace, &dm);
3081:   if (B && *B) {DMRestoreWorkArray(dm, 0, PETSC_REAL, B);}
3082:   if (D && *D) {DMRestoreWorkArray(dm, 0, PETSC_REAL, D);}
3083:   if (H && *H) {DMRestoreWorkArray(dm, 0, PETSC_REAL, H);}
3084:   return(0);
3085: }

3089: PetscErrorCode PetscFEDestroy_Basic(PetscFE fem)
3090: {
3091:   PetscFE_Basic *b = (PetscFE_Basic *) fem->data;

3095:   PetscFree(b);
3096:   return(0);
3097: }

3101: PetscErrorCode PetscFEView_Basic_Ascii(PetscFE fe, PetscViewer viewer)
3102: {
3103:   PetscSpace        basis;
3104:   PetscDualSpace    dual;
3105:   PetscQuadrature   q;
3106:   PetscInt          dim, Nq;
3107:   PetscViewerFormat format;
3108:   PetscErrorCode    ierr;

3111:   PetscFEGetBasisSpace(fe, &basis);
3112:   PetscFEGetDualSpace(fe, &dual);
3113:   PetscFEGetQuadrature(fe, &q);
3114:   PetscQuadratureGetData(q, &dim, &Nq, NULL, NULL);
3115:   PetscViewerGetFormat(viewer, &format);
3116:   PetscViewerASCIIPrintf(viewer, "Basic Finite Element:\n");
3117:   if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3118:     PetscViewerASCIIPrintf(viewer, "  dimension:       %d\n", dim);
3119:     PetscViewerASCIIPrintf(viewer, "  num quad points: %d\n", Nq);
3120:     PetscViewerASCIIPushTab(viewer);
3121:     PetscQuadratureView(q, viewer);
3122:     PetscViewerASCIIPopTab(viewer);
3123:   } else {
3124:     PetscViewerASCIIPrintf(viewer, "  dimension:       %d\n", dim);
3125:     PetscViewerASCIIPrintf(viewer, "  num quad points: %d\n", Nq);
3126:   }
3127:   PetscViewerASCIIPushTab(viewer);
3128:   PetscSpaceView(basis, viewer);
3129:   PetscDualSpaceView(dual, viewer);
3130:   PetscViewerASCIIPopTab(viewer);
3131:   return(0);
3132: }

3136: PetscErrorCode PetscFEView_Basic(PetscFE fe, PetscViewer viewer)
3137: {
3138:   PetscBool      iascii;

3144:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERASCII, &iascii);
3145:   if (iascii) {PetscFEView_Basic_Ascii(fe, viewer);}
3146:   return(0);
3147: }

3151: /* Construct the change of basis from prime basis to nodal basis */
3152: PetscErrorCode PetscFESetUp_Basic(PetscFE fem)
3153: {
3154:   PetscScalar   *work, *invVscalar;
3155:   PetscBLASInt  *pivots;
3156:   PetscBLASInt   n, info;
3157:   PetscInt       pdim, j;

3161:   PetscDualSpaceGetDimension(fem->dualSpace, &pdim);
3162:   PetscMalloc1(pdim*pdim,&fem->invV);
3163: #if defined(PETSC_USE_COMPLEX)
3164:   PetscMalloc1(pdim*pdim,&invVscalar);
3165: #else
3166:   invVscalar = fem->invV;
3167: #endif
3168:   for (j = 0; j < pdim; ++j) {
3169:     PetscReal      *Bf;
3170:     PetscQuadrature f;
3171:     PetscInt        q, k;

3173:     PetscDualSpaceGetFunctional(fem->dualSpace, j, &f);
3174:     PetscMalloc1(f->numPoints*pdim,&Bf);
3175:     PetscSpaceEvaluate(fem->basisSpace, f->numPoints, f->points, Bf, NULL, NULL);
3176:     for (k = 0; k < pdim; ++k) {
3177:       /* n_j \cdot \phi_k */
3178:       invVscalar[j*pdim+k] = 0.0;
3179:       for (q = 0; q < f->numPoints; ++q) {
3180:         invVscalar[j*pdim+k] += Bf[q*pdim+k]*f->weights[q];
3181:       }
3182:     }
3183:     PetscFree(Bf);
3184:   }
3185:   PetscMalloc2(pdim,&pivots,pdim,&work);
3186:   n = pdim;
3187:   PetscStackCallBLAS("LAPACKgetrf", LAPACKgetrf_(&n, &n, invVscalar, &n, pivots, &info));
3188:   PetscStackCallBLAS("LAPACKgetri", LAPACKgetri_(&n, invVscalar, &n, pivots, work, &n, &info));
3189: #if defined(PETSC_USE_COMPLEX)
3190:   for (j = 0; j < pdim*pdim; j++) fem->invV[j] = PetscRealPart(invVscalar[j]);
3191:   PetscFree(invVscalar);
3192: #endif
3193:   PetscFree2(pivots,work);
3194:   return(0);
3195: }

3199: PetscErrorCode PetscFEGetDimension_Basic(PetscFE fem, PetscInt *dim)
3200: {

3204:   PetscDualSpaceGetDimension(fem->dualSpace, dim);
3205:   return(0);
3206: }

3210: PetscErrorCode PetscFEGetTabulation_Basic(PetscFE fem, PetscInt npoints, const PetscReal points[], PetscReal *B, PetscReal *D, PetscReal *H)
3211: {
3212:   DM               dm;
3213:   PetscInt         pdim; /* Dimension of FE space P */
3214:   PetscInt         dim;  /* Spatial dimension */
3215:   PetscInt         comp; /* Field components */
3216:   PetscReal       *tmpB, *tmpD, *tmpH;
3217:   PetscInt         p, d, j, k;
3218:   PetscErrorCode   ierr;

3221:   PetscDualSpaceGetDM(fem->dualSpace, &dm);
3222:   DMGetDimension(dm, &dim);
3223:   PetscDualSpaceGetDimension(fem->dualSpace, &pdim);
3224:   PetscFEGetNumComponents(fem, &comp);
3225:   /* Evaluate the prime basis functions at all points */
3226:   if (B) {DMGetWorkArray(dm, npoints*pdim, PETSC_REAL, &tmpB);}
3227:   if (D) {DMGetWorkArray(dm, npoints*pdim*dim, PETSC_REAL, &tmpD);}
3228:   if (H) {DMGetWorkArray(dm, npoints*pdim*dim*dim, PETSC_REAL, &tmpH);}
3229:   PetscSpaceEvaluate(fem->basisSpace, npoints, points, B ? tmpB : NULL, D ? tmpD : NULL, H ? tmpH : NULL);
3230:   /* Translate to the nodal basis */
3231:   for (p = 0; p < npoints; ++p) {
3232:     if (B) {
3233:       /* Multiply by V^{-1} (pdim x pdim) */
3234:       for (j = 0; j < pdim; ++j) {
3235:         const PetscInt i = (p*pdim + j)*comp;
3236:         PetscInt       c;

3238:         B[i] = 0.0;
3239:         for (k = 0; k < pdim; ++k) {
3240:           B[i] += fem->invV[k*pdim+j] * tmpB[p*pdim + k];
3241:         }
3242:         for (c = 1; c < comp; ++c) {
3243:           B[i+c] = B[i];
3244:         }
3245:       }
3246:     }
3247:     if (D) {
3248:       /* Multiply by V^{-1} (pdim x pdim) */
3249:       for (j = 0; j < pdim; ++j) {
3250:         for (d = 0; d < dim; ++d) {
3251:           const PetscInt i = ((p*pdim + j)*comp + 0)*dim + d;
3252:           PetscInt       c;

3254:           D[i] = 0.0;
3255:           for (k = 0; k < pdim; ++k) {
3256:             D[i] += fem->invV[k*pdim+j] * tmpD[(p*pdim + k)*dim + d];
3257:           }
3258:           for (c = 1; c < comp; ++c) {
3259:             D[((p*pdim + j)*comp + c)*dim + d] = D[i];
3260:           }
3261:         }
3262:       }
3263:     }
3264:     if (H) {
3265:       /* Multiply by V^{-1} (pdim x pdim) */
3266:       for (j = 0; j < pdim; ++j) {
3267:         for (d = 0; d < dim*dim; ++d) {
3268:           const PetscInt i = ((p*pdim + j)*comp + 0)*dim*dim + d;
3269:           PetscInt       c;

3271:           H[i] = 0.0;
3272:           for (k = 0; k < pdim; ++k) {
3273:             H[i] += fem->invV[k*pdim+j] * tmpH[(p*pdim + k)*dim*dim + d];
3274:           }
3275:           for (c = 1; c < comp; ++c) {
3276:             H[((p*pdim + j)*comp + c)*dim*dim + d] = H[i];
3277:           }
3278:         }
3279:       }
3280:     }
3281:   }
3282:   if (B) {DMRestoreWorkArray(dm, npoints*pdim, PETSC_REAL, &tmpB);}
3283:   if (D) {DMRestoreWorkArray(dm, npoints*pdim*dim, PETSC_REAL, &tmpD);}
3284:   if (H) {DMRestoreWorkArray(dm, npoints*pdim*dim*dim, PETSC_REAL, &tmpH);}
3285:   return(0);
3286: }

3290: PetscErrorCode PetscFEIntegrate_Basic(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
3291:                                       const PetscScalar coefficients[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscReal integral[])
3292: {
3293:   const PetscInt  debug = 0;
3294:   PetscPointFunc  obj_func;
3295:   PetscQuadrature quad;
3296:   PetscScalar    *u, *u_x, *a, *a_x;
3297:   PetscReal      *x;
3298:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3299:   PetscInt        dim, Nf, NfAux = 0, totDim, totDimAux, cOffset = 0, cOffsetAux = 0, e;
3300:   PetscErrorCode  ierr;

3303:   PetscDSGetObjective(prob, field, &obj_func);
3304:   if (!obj_func) return(0);
3305:   PetscFEGetSpatialDimension(fem, &dim);
3306:   PetscFEGetQuadrature(fem, &quad);
3307:   PetscDSGetNumFields(prob, &Nf);
3308:   PetscDSGetTotalDimension(prob, &totDim);
3309:   PetscDSGetComponentOffsets(prob, &uOff);
3310:   PetscDSGetComponentDerivativeOffsets(prob, &uOff_x);
3311:   PetscDSGetEvaluationArrays(prob, &u, NULL, &u_x);
3312:   PetscDSGetRefCoordArrays(prob, &x, NULL);
3313:   if (probAux) {
3314:     PetscDSGetNumFields(probAux, &NfAux);
3315:     PetscDSGetTotalDimension(probAux, &totDimAux);
3316:     PetscDSGetComponentOffsets(probAux, &aOff);
3317:     PetscDSGetComponentDerivativeOffsets(probAux, &aOff_x);
3318:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3319:   }
3320:   for (e = 0; e < Ne; ++e) {
3321:     const PetscReal *v0   = geom[e].v0;
3322:     const PetscReal *J    = geom[e].J;
3323:     const PetscReal *invJ = geom[e].invJ;
3324:     const PetscReal  detJ = geom[e].detJ;
3325:     const PetscReal *quadPoints, *quadWeights;
3326:     PetscInt         Nq, q;

3328:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3329:     if (debug > 1) {
3330:       PetscPrintf(PETSC_COMM_SELF, "  detJ: %g\n", detJ);
3331: #ifndef PETSC_USE_COMPLEX
3332:       DMPrintCellMatrix(e, "invJ", dim, dim, invJ);
3333: #endif
3334:     }
3335:     for (q = 0; q < Nq; ++q) {
3336:       PetscScalar integrand;

3338:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3339:       CoordinatesRefToReal(dim, dim, v0, J, &quadPoints[q*dim], x);
3340:       EvaluateFieldJets(prob,    PETSC_FALSE, q, invJ, &coefficients[cOffset],       NULL, u, u_x, NULL);
3341:       EvaluateFieldJets(probAux, PETSC_FALSE, q, invJ, &coefficientsAux[cOffsetAux], NULL, a, a_x, NULL);
3342:       obj_func(dim, Nf, NfAux, uOff, uOff_x, u, NULL, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, &integrand);
3343:       integrand *= detJ*quadWeights[q];
3344:       integral[field] += PetscRealPart(integrand);
3345:       if (debug > 1) {PetscPrintf(PETSC_COMM_SELF, "    int: %g %g\n", PetscRealPart(integrand), integral[field]);}
3346:     }
3347:     cOffset    += totDim;
3348:     cOffsetAux += totDimAux;
3349:   }
3350:   return(0);
3351: }

3355: PetscErrorCode PetscFEIntegrateResidual_Basic(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
3356:                                               const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
3357: {
3358:   const PetscInt  debug = 0;
3359:   PetscPointFunc  f0_func;
3360:   PetscPointFunc  f1_func;
3361:   PetscQuadrature quad;
3362:   PetscReal     **basisField, **basisFieldDer;
3363:   PetscScalar    *f0, *f1, *u, *u_t = NULL, *u_x, *a, *a_x, *refSpaceDer;
3364:   PetscReal      *x;
3365:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3366:   PetscInt        dim, Nf, NfAux = 0, Nb, Nc, totDim, totDimAux = 0, cOffset = 0, cOffsetAux = 0, fOffset, e;
3367:   PetscErrorCode  ierr;

3370:   PetscFEGetSpatialDimension(fem, &dim);
3371:   PetscFEGetQuadrature(fem, &quad);
3372:   PetscFEGetDimension(fem, &Nb);
3373:   PetscFEGetNumComponents(fem, &Nc);
3374:   PetscDSGetNumFields(prob, &Nf);
3375:   PetscDSGetTotalDimension(prob, &totDim);
3376:   PetscDSGetComponentOffsets(prob, &uOff);
3377:   PetscDSGetComponentDerivativeOffsets(prob, &uOff_x);
3378:   PetscDSGetFieldOffset(prob, field, &fOffset);
3379:   PetscDSGetResidual(prob, field, &f0_func, &f1_func);
3380:   PetscDSGetEvaluationArrays(prob, &u, coefficients_t ? &u_t : NULL, &u_x);
3381:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
3382:   PetscDSGetWeakFormArrays(prob, &f0, &f1, NULL, NULL, NULL, NULL);
3383:   PetscDSGetTabulation(prob, &basisField, &basisFieldDer);
3384:   if (probAux) {
3385:     PetscDSGetNumFields(probAux, &NfAux);
3386:     PetscDSGetTotalDimension(probAux, &totDimAux);
3387:     PetscDSGetComponentOffsets(probAux, &aOff);
3388:     PetscDSGetComponentDerivativeOffsets(probAux, &aOff_x);
3389:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3390:   }
3391:   for (e = 0; e < Ne; ++e) {
3392:     const PetscReal *v0   = geom[e].v0;
3393:     const PetscReal *J    = geom[e].J;
3394:     const PetscReal *invJ = geom[e].invJ;
3395:     const PetscReal  detJ = geom[e].detJ;
3396:     const PetscReal *quadPoints, *quadWeights;
3397:     PetscInt         Nq, q;

3399:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3400:     PetscMemzero(f0, Nq*Nc* sizeof(PetscScalar));
3401:     PetscMemzero(f1, Nq*Nc*dim * sizeof(PetscScalar));
3402:     if (debug > 1) {
3403:       PetscPrintf(PETSC_COMM_SELF, "  detJ: %g\n", detJ);
3404: #ifndef PETSC_USE_COMPLEX
3405:       DMPrintCellMatrix(e, "invJ", dim, dim, invJ);
3406: #endif
3407:     }
3408:     for (q = 0; q < Nq; ++q) {
3409:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3410:       CoordinatesRefToReal(dim, dim, v0, J, &quadPoints[q*dim], x);
3411:       EvaluateFieldJets(prob,    PETSC_FALSE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
3412:       EvaluateFieldJets(probAux, PETSC_FALSE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
3413:       if (f0_func) f0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, &f0[q*Nc]);
3414:       if (f1_func) f1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, refSpaceDer);
3415:       TransformF(dim, Nc, q, invJ, detJ, quadWeights, refSpaceDer, f0, f1);
3416:     }
3417:     UpdateElementVec(dim, Nq, Nb, Nc, basisField[field], basisFieldDer[field], f0, f1, &elemVec[cOffset+fOffset]);
3418:     cOffset    += totDim;
3419:     cOffsetAux += totDimAux;
3420:   }
3421:   return(0);
3422: }

3426: PetscErrorCode PetscFEIntegrateBdResidual_Basic(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
3427:                                                 const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
3428: {
3429:   const PetscInt  debug = 0;
3430:   PetscBdPointFunc f0_func;
3431:   PetscBdPointFunc f1_func;
3432:   PetscQuadrature quad;
3433:   PetscReal     **basisField, **basisFieldDer;
3434:   PetscScalar    *f0, *f1, *u, *u_t = NULL, *u_x, *a, *a_x, *refSpaceDer;
3435:   PetscReal      *x;
3436:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3437:   PetscInt        dim, Nf, NfAux = 0, Nb, Nc, totDim, totDimAux, cOffset = 0, cOffsetAux = 0, fOffset, e;
3438:   PetscErrorCode  ierr;

3441:   PetscFEGetSpatialDimension(fem, &dim);
3442:   dim += 1; /* Spatial dimension is one higher than topological dimension */
3443:   PetscFEGetQuadrature(fem, &quad);
3444:   PetscFEGetDimension(fem, &Nb);
3445:   PetscFEGetNumComponents(fem, &Nc);
3446:   PetscDSGetNumFields(prob, &Nf);
3447:   PetscDSGetTotalBdDimension(prob, &totDim);
3448:   PetscDSGetComponentBdOffsets(prob, &uOff);
3449:   PetscDSGetComponentBdDerivativeOffsets(prob, &uOff_x);
3450:   PetscDSGetBdFieldOffset(prob, field, &fOffset);
3451:   PetscDSGetBdResidual(prob, field, &f0_func, &f1_func);
3452:   PetscDSGetEvaluationArrays(prob, &u, coefficients_t ? &u_t : NULL, &u_x);
3453:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
3454:   PetscDSGetWeakFormArrays(prob, &f0, &f1, NULL, NULL, NULL, NULL);
3455:   PetscDSGetBdTabulation(prob, &basisField, &basisFieldDer);
3456:   if (probAux) {
3457:     PetscDSGetNumFields(probAux, &NfAux);
3458:     PetscDSGetTotalBdDimension(probAux, &totDimAux);
3459:     PetscDSGetComponentBdOffsets(probAux, &aOff);
3460:     PetscDSGetComponentBdDerivativeOffsets(probAux, &aOff_x);
3461:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3462:   }
3463:   for (e = 0; e < Ne; ++e) {
3464:     const PetscReal *v0          = geom[e].v0;
3465:     const PetscReal *n           = geom[e].n;
3466:     const PetscReal *J           = geom[e].J;
3467:     const PetscReal *invJ        = geom[e].invJ;
3468:     const PetscReal  detJ        = geom[e].detJ;
3469:     const PetscReal *quadPoints, *quadWeights;
3470:     PetscInt         Nq, q;

3472:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3473:     PetscMemzero(f0, Nq*Nc* sizeof(PetscScalar));
3474:     PetscMemzero(f1, Nq*Nc*dim * sizeof(PetscScalar));
3475:     if (debug > 1) {
3476:       PetscPrintf(PETSC_COMM_SELF, "  detJ: %g\n", detJ);
3477: #ifndef PETSC_USE_COMPLEX
3478:       DMPrintCellMatrix(e, "invJ", dim, dim, invJ);
3479: #endif
3480:     }
3481:     for (q = 0; q < Nq; ++q) {
3482:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3483:       CoordinatesRefToReal(dim, dim-1, v0, J, &quadPoints[q*(dim-1)], x);
3484:       EvaluateFieldJets(prob,    PETSC_TRUE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
3485:       EvaluateFieldJets(probAux, PETSC_TRUE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
3486:       if (f0_func) f0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, n, &f0[q*Nc]);
3487:       if (f1_func) f1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, n, refSpaceDer);
3488:       TransformF(dim, Nc, q, invJ, detJ, quadWeights, refSpaceDer, f0, f1);
3489:     }
3490:     UpdateElementVec(dim-1, Nq, Nb, Nc, basisField[field], basisFieldDer[field], f0, f1, &elemVec[cOffset+fOffset]);
3491:     cOffset    += totDim;
3492:     cOffsetAux += totDimAux;
3493:   }
3494:   return(0);
3495: }

3499: PetscErrorCode PetscFEIntegrateJacobian_Basic(PetscFE fem, PetscDS prob, PetscBool isPrec, PetscInt fieldI, PetscInt fieldJ, PetscInt Ne, PetscFECellGeom *geom,
3500:                                               const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemMat[])
3501: {
3502:   const PetscInt  debug      = 0;
3503:   PetscPointJac   g0_func;
3504:   PetscPointJac   g1_func;
3505:   PetscPointJac   g2_func;
3506:   PetscPointJac   g3_func;
3507:   PetscFE         fe;
3508:   PetscInt        cOffset    = 0; /* Offset into coefficients[] for element e */
3509:   PetscInt        cOffsetAux = 0; /* Offset into coefficientsAux[] for element e */
3510:   PetscInt        eOffset    = 0; /* Offset into elemMat[] for element e */
3511:   PetscInt        offsetI    = 0; /* Offset into an element vector for fieldI */
3512:   PetscInt        offsetJ    = 0; /* Offset into an element vector for fieldJ */
3513:   PetscQuadrature quad;
3514:   PetscScalar    *g0, *g1, *g2, *g3, *u, *u_t = NULL, *u_x, *a, *a_x, *refSpaceDer;
3515:   PetscReal      *x;
3516:   PetscReal     **basisField, **basisFieldDer, *basisI, *basisDerI, *basisJ, *basisDerJ;
3517:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3518:   PetscInt        NbI = 0, NcI = 0, NbJ = 0, NcJ = 0;
3519:   PetscInt        dim, Nf, NfAux = 0, totDim, totDimAux, e;
3520:   PetscErrorCode  ierr;

3523:   PetscFEGetSpatialDimension(fem, &dim);
3524:   PetscFEGetQuadrature(fem, &quad);
3525:   PetscDSGetNumFields(prob, &Nf);
3526:   PetscDSGetTotalDimension(prob, &totDim);
3527:   PetscDSGetComponentOffsets(prob, &uOff);
3528:   PetscDSGetComponentDerivativeOffsets(prob, &uOff_x);
3529:   if (isPrec) {PetscDSGetJacobianPreconditioner(prob, fieldI, fieldJ, &g0_func, &g1_func, &g2_func, &g3_func);}
3530:   else        {PetscDSGetJacobian(prob, fieldI, fieldJ, &g0_func, &g1_func, &g2_func, &g3_func);}
3531:   PetscDSGetEvaluationArrays(prob, &u, coefficients_t ? &u_t : NULL, &u_x);
3532:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
3533:   PetscDSGetWeakFormArrays(prob, NULL, NULL, &g0, &g1, &g2, &g3);
3534:   PetscDSGetTabulation(prob, &basisField, &basisFieldDer);
3535:   PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);
3536:   PetscFEGetDimension(fe, &NbI);
3537:   PetscFEGetNumComponents(fe, &NcI);
3538:   PetscDSGetFieldOffset(prob, fieldI, &offsetI);
3539:   PetscDSGetDiscretization(prob, fieldJ, (PetscObject *) &fe);
3540:   PetscFEGetDimension(fe, &NbJ);
3541:   PetscFEGetNumComponents(fe, &NcJ);
3542:   PetscDSGetFieldOffset(prob, fieldJ, &offsetJ);
3543:   if (probAux) {
3544:     PetscDSGetNumFields(probAux, &NfAux);
3545:     PetscDSGetTotalDimension(probAux, &totDimAux);
3546:     PetscDSGetComponentOffsets(probAux, &aOff);
3547:     PetscDSGetComponentDerivativeOffsets(probAux, &aOff_x);
3548:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3549:   }
3550:   basisI    = basisField[fieldI];
3551:   basisJ    = basisField[fieldJ];
3552:   basisDerI = basisFieldDer[fieldI];
3553:   basisDerJ = basisFieldDer[fieldJ];
3554:   /* Initialize here in case the function is not defined */
3555:   PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
3556:   PetscMemzero(g1, NcI*NcJ*dim * sizeof(PetscScalar));
3557:   PetscMemzero(g2, NcI*NcJ*dim * sizeof(PetscScalar));
3558:   PetscMemzero(g3, NcI*NcJ*dim*dim * sizeof(PetscScalar));
3559:   for (e = 0; e < Ne; ++e) {
3560:     const PetscReal *v0   = geom[e].v0;
3561:     const PetscReal *J    = geom[e].J;
3562:     const PetscReal *invJ = geom[e].invJ;
3563:     const PetscReal  detJ = geom[e].detJ;
3564:     const PetscReal *quadPoints, *quadWeights;
3565:     PetscInt         Nq, q;

3567:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3568:     for (q = 0; q < Nq; ++q) {
3569:       PetscInt f, g, fc, gc, c;

3571:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3572:       CoordinatesRefToReal(dim, dim, v0, J, &quadPoints[q*dim], x);
3573:       EvaluateFieldJets(prob,    PETSC_FALSE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
3574:       EvaluateFieldJets(probAux, PETSC_FALSE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
3575:       if (g0_func) {
3576:         PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
3577:         g0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, g0);
3578:         for (c = 0; c < NcI*NcJ; ++c) {g0[c] *= detJ*quadWeights[q];}
3579:       }
3580:       if (g1_func) {
3581:         PetscInt d, d2;
3582:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
3583:         g1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
3584:         for (fc = 0; fc < NcI; ++fc) {
3585:           for (gc = 0; gc < NcJ; ++gc) {
3586:             for (d = 0; d < dim; ++d) {
3587:               g1[(fc*NcJ+gc)*dim+d] = 0.0;
3588:               for (d2 = 0; d2 < dim; ++d2) g1[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
3589:               g1[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
3590:             }
3591:           }
3592:         }
3593:       }
3594:       if (g2_func) {
3595:         PetscInt d, d2;
3596:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
3597:         g2_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
3598:         for (fc = 0; fc < NcI; ++fc) {
3599:           for (gc = 0; gc < NcJ; ++gc) {
3600:             for (d = 0; d < dim; ++d) {
3601:               g2[(fc*NcJ+gc)*dim+d] = 0.0;
3602:               for (d2 = 0; d2 < dim; ++d2) g2[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
3603:               g2[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
3604:             }
3605:           }
3606:         }
3607:       }
3608:       if (g3_func) {
3609:         PetscInt d, d2, dp, d3;
3610:         PetscMemzero(refSpaceDer, NcI*NcJ*dim*dim * sizeof(PetscScalar));
3611:         g3_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
3612:         for (fc = 0; fc < NcI; ++fc) {
3613:           for (gc = 0; gc < NcJ; ++gc) {
3614:             for (d = 0; d < dim; ++d) {
3615:               for (dp = 0; dp < dim; ++dp) {
3616:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] = 0.0;
3617:                 for (d2 = 0; d2 < dim; ++d2) {
3618:                   for (d3 = 0; d3 < dim; ++d3) {
3619:                     g3[((fc*NcJ+gc)*dim+d)*dim+dp] += invJ[d*dim+d2]*refSpaceDer[((fc*NcJ+gc)*dim+d2)*dim+d3]*invJ[dp*dim+d3];
3620:                   }
3621:                 }
3622:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] *= detJ*quadWeights[q];
3623:               }
3624:             }
3625:           }
3626:         }
3627:       }

3629:       for (f = 0; f < NbI; ++f) {
3630:         for (fc = 0; fc < NcI; ++fc) {
3631:           const PetscInt fidx = f*NcI+fc; /* Test function basis index */
3632:           const PetscInt i    = offsetI+fidx; /* Element matrix row */
3633:           for (g = 0; g < NbJ; ++g) {
3634:             for (gc = 0; gc < NcJ; ++gc) {
3635:               const PetscInt gidx = g*NcJ+gc; /* Trial function basis index */
3636:               const PetscInt j    = offsetJ+gidx; /* Element matrix column */
3637:               const PetscInt fOff = eOffset+i*totDim+j;
3638:               PetscInt       d, d2;

3640:               elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g0[fc*NcJ+gc]*basisJ[q*NbJ*NcJ+gidx];
3641:               for (d = 0; d < dim; ++d) {
3642:                 elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g1[(fc*NcJ+gc)*dim+d]*basisDerJ[(q*NbJ*NcJ+gidx)*dim+d];
3643:                 elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*dim+d]*g2[(fc*NcJ+gc)*dim+d]*basisJ[q*NbJ*NcJ+gidx];
3644:                 for (d2 = 0; d2 < dim; ++d2) {
3645:                   elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*dim+d]*g3[((fc*NcJ+gc)*dim+d)*dim+d2]*basisDerJ[(q*NbJ*NcJ+gidx)*dim+d2];
3646:                 }
3647:               }
3648:             }
3649:           }
3650:         }
3651:       }
3652:     }
3653:     if (debug > 1) {
3654:       PetscInt fc, f, gc, g;

3656:       PetscPrintf(PETSC_COMM_SELF, "Element matrix for fields %d and %d\n", fieldI, fieldJ);
3657:       for (fc = 0; fc < NcI; ++fc) {
3658:         for (f = 0; f < NbI; ++f) {
3659:           const PetscInt i = offsetI + f*NcI+fc;
3660:           for (gc = 0; gc < NcJ; ++gc) {
3661:             for (g = 0; g < NbJ; ++g) {
3662:               const PetscInt j = offsetJ + g*NcJ+gc;
3663:               PetscPrintf(PETSC_COMM_SELF, "    elemMat[%d,%d,%d,%d]: %g\n", f, fc, g, gc, PetscRealPart(elemMat[eOffset+i*totDim+j]));
3664:             }
3665:           }
3666:           PetscPrintf(PETSC_COMM_SELF, "\n");
3667:         }
3668:       }
3669:     }
3670:     cOffset    += totDim;
3671:     cOffsetAux += totDimAux;
3672:     eOffset    += PetscSqr(totDim);
3673:   }
3674:   return(0);
3675: }

3679: PetscErrorCode PetscFEIntegrateBdJacobian_Basic(PetscFE fem, PetscDS prob, PetscInt fieldI, PetscInt fieldJ, PetscInt Ne, PetscFECellGeom *geom,
3680:                                                 const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemMat[])
3681: {
3682:   const PetscInt  debug      = 0;
3683:   PetscBdPointJac g0_func;
3684:   PetscBdPointJac g1_func;
3685:   PetscBdPointJac g2_func;
3686:   PetscBdPointJac g3_func;
3687:   PetscFE         fe;
3688:   PetscInt        cOffset    = 0; /* Offset into coefficients[] for element e */
3689:   PetscInt        cOffsetAux = 0; /* Offset into coefficientsAux[] for element e */
3690:   PetscInt        eOffset    = 0; /* Offset into elemMat[] for element e */
3691:   PetscInt        offsetI    = 0; /* Offset into an element vector for fieldI */
3692:   PetscInt        offsetJ    = 0; /* Offset into an element vector for fieldJ */
3693:   PetscQuadrature quad;
3694:   PetscScalar    *g0, *g1, *g2, *g3, *u, *u_t = NULL, *u_x, *a, *a_x, *refSpaceDer;
3695:   PetscReal      *x;
3696:   PetscReal     **basisField, **basisFieldDer, *basisI, *basisDerI, *basisJ, *basisDerJ;
3697:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3698:   PetscInt        NbI = 0, NcI = 0, NbJ = 0, NcJ = 0;
3699:   PetscInt        dim, Nf, NfAux = 0, bdim, totDim, totDimAux, e;
3700:   PetscErrorCode  ierr;

3703:   PetscFEGetQuadrature(fem, &quad);
3704:   PetscFEGetSpatialDimension(fem, &dim);
3705:   dim += 1; /* Spatial dimension is one higher than topological dimension */
3706:   bdim = dim-1;
3707:   PetscDSGetNumFields(prob, &Nf);
3708:   PetscDSGetTotalBdDimension(prob, &totDim);
3709:   PetscDSGetComponentBdOffsets(prob, &uOff);
3710:   PetscDSGetComponentBdDerivativeOffsets(prob, &uOff_x);
3711:   PetscDSGetBdJacobian(prob, fieldI, fieldJ, &g0_func, &g1_func, &g2_func, &g3_func);
3712:   PetscDSGetEvaluationArrays(prob, &u, coefficients_t ? &u_t : NULL, &u_x);
3713:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
3714:   PetscDSGetWeakFormArrays(prob, NULL, NULL, &g0, &g1, &g2, &g3);
3715:   PetscDSGetBdTabulation(prob, &basisField, &basisFieldDer);
3716:   PetscDSGetBdDiscretization(prob, fieldI, (PetscObject *) &fe);
3717:   PetscFEGetDimension(fe, &NbI);
3718:   PetscFEGetNumComponents(fe, &NcI);
3719:   PetscDSGetBdFieldOffset(prob, fieldI, &offsetI);
3720:   PetscDSGetBdDiscretization(prob, fieldJ, (PetscObject *) &fe);
3721:   PetscFEGetDimension(fe, &NbJ);
3722:   PetscFEGetNumComponents(fe, &NcJ);
3723:   PetscDSGetBdFieldOffset(prob, fieldJ, &offsetJ);
3724:   if (probAux) {
3725:     PetscDSGetNumFields(probAux, &NfAux);
3726:     PetscDSGetTotalBdDimension(probAux, &totDimAux);
3727:     PetscDSGetComponentBdOffsets(probAux, &aOff);
3728:     PetscDSGetComponentBdDerivativeOffsets(probAux, &aOff_x);
3729:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3730:   }
3731:   basisI    = basisField[fieldI];
3732:   basisJ    = basisField[fieldJ];
3733:   basisDerI = basisFieldDer[fieldI];
3734:   basisDerJ = basisFieldDer[fieldJ];
3735:   /* Initialize here in case the function is not defined */
3736:   PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
3737:   PetscMemzero(g1, NcI*NcJ*dim * sizeof(PetscScalar));
3738:   PetscMemzero(g2, NcI*NcJ*dim * sizeof(PetscScalar));
3739:   PetscMemzero(g3, NcI*NcJ*dim*dim * sizeof(PetscScalar));
3740:   for (e = 0; e < Ne; ++e) {
3741:     const PetscReal *v0   = geom[e].v0;
3742:     const PetscReal *n    = geom[e].n;
3743:     const PetscReal *J    = geom[e].J;
3744:     const PetscReal *invJ = geom[e].invJ;
3745:     const PetscReal  detJ = geom[e].detJ;
3746:     const PetscReal *quadPoints, *quadWeights;
3747:     PetscInt         Nq, q;

3749:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3750:     for (q = 0; q < Nq; ++q) {
3751:       PetscInt f, g, fc, gc, c;

3753:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3754:       CoordinatesRefToReal(dim, bdim, v0, J, &quadPoints[q*bdim], x);
3755:       EvaluateFieldJets(prob,    PETSC_TRUE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
3756:       EvaluateFieldJets(probAux, PETSC_TRUE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
3757:       /* TODO: I think I have a mistake in the dim loops here */
3758:       if (g0_func) {
3759:         PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
3760:         g0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, n, g0);
3761:         for (c = 0; c < NcI*NcJ; ++c) {g0[c] *= detJ*quadWeights[q];}
3762:       }
3763:       if (g1_func) {
3764:         PetscInt d, d2;
3765:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
3766:         g1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, n, refSpaceDer);
3767:         for (fc = 0; fc < NcI; ++fc) {
3768:           for (gc = 0; gc < NcJ; ++gc) {
3769:             for (d = 0; d < dim; ++d) {
3770:               g1[(fc*NcJ+gc)*dim+d] = 0.0;
3771:               for (d2 = 0; d2 < dim; ++d2) g1[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
3772:               g1[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
3773:             }
3774:           }
3775:         }
3776:       }
3777:       if (g2_func) {
3778:         PetscInt d, d2;
3779:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
3780:         g2_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, n, refSpaceDer);
3781:         for (fc = 0; fc < NcI; ++fc) {
3782:           for (gc = 0; gc < NcJ; ++gc) {
3783:             for (d = 0; d < dim; ++d) {
3784:               g2[(fc*NcJ+gc)*dim+d] = 0.0;
3785:               for (d2 = 0; d2 < dim; ++d2) g2[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
3786:               g2[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
3787:             }
3788:           }
3789:         }
3790:       }
3791:       if (g3_func) {
3792:         PetscInt d, d2, dp, d3;
3793:         PetscMemzero(refSpaceDer, NcI*NcJ*dim*dim * sizeof(PetscScalar));
3794:         g3_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, n, g3);
3795:         for (fc = 0; fc < NcI; ++fc) {
3796:           for (gc = 0; gc < NcJ; ++gc) {
3797:             for (d = 0; d < dim; ++d) {
3798:               for (dp = 0; dp < dim; ++dp) {
3799:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] = 0.0;
3800:                 for (d2 = 0; d2 < dim; ++d2) {
3801:                   for (d3 = 0; d3 < dim; ++d3) {
3802:                     g3[((fc*NcJ+gc)*dim+d)*dim+dp] += invJ[d*dim+d2]*refSpaceDer[((fc*NcJ+gc)*dim+d2)*dim+d3]*invJ[dp*dim+d3];
3803:                   }
3804:                 }
3805:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] *= detJ*quadWeights[q];
3806:               }
3807:             }
3808:           }
3809:         }
3810:       }

3812:       for (f = 0; f < NbI; ++f) {
3813:         for (fc = 0; fc < NcI; ++fc) {
3814:           const PetscInt fidx = f*NcI+fc; /* Test function basis index */
3815:           const PetscInt i    = offsetI+fidx; /* Element matrix row */
3816:           for (g = 0; g < NbJ; ++g) {
3817:             for (gc = 0; gc < NcJ; ++gc) {
3818:               const PetscInt gidx = g*NcJ+gc; /* Trial function basis index */
3819:               const PetscInt j    = offsetJ+gidx; /* Element matrix column */
3820:               const PetscInt fOff = eOffset+i*totDim+j;
3821:               PetscInt       d, d2;

3823:               elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g0[fc*NcJ+gc]*basisJ[q*NbJ*NcJ+gidx];
3824:               for (d = 0; d < bdim; ++d) {
3825:                 elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g1[(fc*NcJ+gc)*bdim+d]*basisDerJ[(q*NbJ*NcJ+gidx)*bdim+d];
3826:                 elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*bdim+d]*g2[(fc*NcJ+gc)*bdim+d]*basisJ[q*NbJ*NcJ+gidx];
3827:                 for (d2 = 0; d2 < bdim; ++d2) {
3828:                   elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*bdim+d]*g3[((fc*NcJ+gc)*bdim+d)*bdim+d2]*basisDerJ[(q*NbJ*NcJ+gidx)*bdim+d2];
3829:                 }
3830:               }
3831:             }
3832:           }
3833:         }
3834:       }
3835:     }
3836:     if (debug > 1) {
3837:       PetscInt fc, f, gc, g;

3839:       PetscPrintf(PETSC_COMM_SELF, "Element matrix for fields %d and %d\n", fieldI, fieldJ);
3840:       for (fc = 0; fc < NcI; ++fc) {
3841:         for (f = 0; f < NbI; ++f) {
3842:           const PetscInt i = offsetI + f*NcI+fc;
3843:           for (gc = 0; gc < NcJ; ++gc) {
3844:             for (g = 0; g < NbJ; ++g) {
3845:               const PetscInt j = offsetJ + g*NcJ+gc;
3846:               PetscPrintf(PETSC_COMM_SELF, "    elemMat[%d,%d,%d,%d]: %g\n", f, fc, g, gc, PetscRealPart(elemMat[eOffset+i*totDim+j]));
3847:             }
3848:           }
3849:           PetscPrintf(PETSC_COMM_SELF, "\n");
3850:         }
3851:       }
3852:     }
3853:     cOffset    += totDim;
3854:     cOffsetAux += totDimAux;
3855:     eOffset    += PetscSqr(totDim);
3856:   }
3857:   return(0);
3858: }

3862: PetscErrorCode PetscFEInitialize_Basic(PetscFE fem)
3863: {
3865:   fem->ops->setfromoptions          = NULL;
3866:   fem->ops->setup                   = PetscFESetUp_Basic;
3867:   fem->ops->view                    = PetscFEView_Basic;
3868:   fem->ops->destroy                 = PetscFEDestroy_Basic;
3869:   fem->ops->getdimension            = PetscFEGetDimension_Basic;
3870:   fem->ops->gettabulation           = PetscFEGetTabulation_Basic;
3871:   fem->ops->integrate               = PetscFEIntegrate_Basic;
3872:   fem->ops->integrateresidual       = PetscFEIntegrateResidual_Basic;
3873:   fem->ops->integratebdresidual     = PetscFEIntegrateBdResidual_Basic;
3874:   fem->ops->integratejacobianaction = NULL/* PetscFEIntegrateJacobianAction_Basic */;
3875:   fem->ops->integratejacobian       = PetscFEIntegrateJacobian_Basic;
3876:   fem->ops->integratebdjacobian     = PetscFEIntegrateBdJacobian_Basic;
3877:   return(0);
3878: }

3880: /*MC
3881:   PETSCFEBASIC = "basic" - A PetscFE object that integrates with basic tiling and no vectorization

3883:   Level: intermediate

3885: .seealso: PetscFEType, PetscFECreate(), PetscFESetType()
3886: M*/

3890: PETSC_EXTERN PetscErrorCode PetscFECreate_Basic(PetscFE fem)
3891: {
3892:   PetscFE_Basic *b;

3897:   PetscNewLog(fem,&b);
3898:   fem->data = b;

3900:   PetscFEInitialize_Basic(fem);
3901:   return(0);
3902: }

3906: PetscErrorCode PetscFEDestroy_Nonaffine(PetscFE fem)
3907: {
3908:   PetscFE_Nonaffine *na = (PetscFE_Nonaffine *) fem->data;

3912:   PetscFree(na);
3913:   return(0);
3914: }

3918: PetscErrorCode PetscFEIntegrateResidual_Nonaffine(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
3919:                                                   const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
3920: {
3921:   const PetscInt  debug = 0;
3922:   PetscPointFunc  f0_func;
3923:   PetscPointFunc  f1_func;
3924:   PetscQuadrature quad;
3925:   PetscReal     **basisField, **basisFieldDer;
3926:   PetscScalar    *f0, *f1, *u, *u_t, *u_x, *a, *a_x, *refSpaceDer;
3927:   PetscReal      *x;
3928:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3929:   PetscInt        dim, Nf, NfAux = 0, Nb, Nc, totDim, totDimAux = 0, cOffset = 0, cOffsetAux = 0, fOffset, e;
3930:   PetscErrorCode  ierr;

3933:   PetscFEGetSpatialDimension(fem, &dim);
3934:   PetscFEGetQuadrature(fem, &quad);
3935:   PetscFEGetDimension(fem, &Nb);
3936:   PetscFEGetNumComponents(fem, &Nc);
3937:   PetscDSGetNumFields(prob, &Nf);
3938:   PetscDSGetTotalDimension(prob, &totDim);
3939:   PetscDSGetComponentOffsets(prob, &uOff);
3940:   PetscDSGetComponentDerivativeOffsets(prob, &uOff_x);
3941:   PetscDSGetFieldOffset(prob, field, &fOffset);
3942:   PetscDSGetResidual(prob, field, &f0_func, &f1_func);
3943:   PetscDSGetEvaluationArrays(prob, &u, &u_t, &u_x);
3944:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
3945:   PetscDSGetWeakFormArrays(prob, &f0, &f1, NULL, NULL, NULL, NULL);
3946:   PetscDSGetTabulation(prob, &basisField, &basisFieldDer);
3947:   if (probAux) {
3948:     PetscDSGetNumFields(probAux, &NfAux);
3949:     PetscDSGetTotalDimension(probAux, &totDimAux);
3950:     PetscDSGetComponentOffsets(probAux, &aOff);
3951:     PetscDSGetComponentDerivativeOffsets(probAux, &aOff_x);
3952:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
3953:   }
3954:   for (e = 0; e < Ne; ++e) {
3955:     const PetscReal *quadPoints, *quadWeights;
3956:     PetscInt         Nq, q;

3958:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
3959:     PetscMemzero(f0, Nq*Nc* sizeof(PetscScalar));
3960:     PetscMemzero(f1, Nq*Nc*dim * sizeof(PetscScalar));
3961:     for (q = 0; q < Nq; ++q) {
3962:       const PetscReal *v0   = geom[e*Nq+q].v0;
3963:       const PetscReal *J    = geom[e*Nq+q].J;
3964:       const PetscReal *invJ = geom[e*Nq+q].invJ;
3965:       const PetscReal  detJ = geom[e*Nq+q].detJ;

3967:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
3968:       CoordinatesRefToReal(dim, dim, v0, J, &quadPoints[q*dim], x);
3969:       EvaluateFieldJets(prob,    PETSC_FALSE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
3970:       EvaluateFieldJets(probAux, PETSC_FALSE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
3971:       if (f0_func) f0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, &f0[q*Nc]);
3972:       if (f1_func) f1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, refSpaceDer);
3973:       TransformF(dim, Nc, q, invJ, detJ, quadWeights, refSpaceDer, f0, f1);
3974:     }
3975:     UpdateElementVec(dim, Nq, Nb, Nc, basisField[field], basisFieldDer[field], f0, f1, &elemVec[cOffset+fOffset]);
3976:     cOffset    += totDim;
3977:     cOffsetAux += totDimAux;
3978:   }
3979:   return(0);
3980: }

3984: PetscErrorCode PetscFEIntegrateBdResidual_Nonaffine(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
3985:                                                     const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
3986: {
3987:   const PetscInt   debug = 0;
3988:   PetscBdPointFunc f0_func;
3989:   PetscBdPointFunc f1_func;
3990:   PetscQuadrature  quad;
3991:   PetscReal      **basisField, **basisFieldDer;
3992:   PetscScalar     *f0, *f1, *u, *u_t, *u_x, *a, *a_x, *refSpaceDer;
3993:   PetscReal       *x;
3994:   PetscInt        *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
3995:   PetscInt         dim, Nf, NfAux = 0, Nb, Nc, totDim, totDimAux, cOffset = 0, cOffsetAux = 0, fOffset, e;
3996:   PetscErrorCode   ierr;

3999:   PetscFEGetSpatialDimension(fem, &dim);
4000:   dim += 1; /* Spatial dimension is one higher than topological dimension */
4001:   PetscFEGetQuadrature(fem, &quad);
4002:   PetscFEGetDimension(fem, &Nb);
4003:   PetscFEGetNumComponents(fem, &Nc);
4004:   PetscDSGetNumFields(prob, &Nf);
4005:   PetscDSGetTotalBdDimension(prob, &totDim);
4006:   PetscDSGetComponentBdOffsets(prob, &uOff);
4007:   PetscDSGetComponentBdDerivativeOffsets(prob, &uOff_x);
4008:   PetscDSGetBdFieldOffset(prob, field, &fOffset);
4009:   PetscDSGetBdResidual(prob, field, &f0_func, &f1_func);
4010:   PetscDSGetEvaluationArrays(prob, &u, &u_t, &u_x);
4011:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
4012:   PetscDSGetWeakFormArrays(prob, &f0, &f1, NULL, NULL, NULL, NULL);
4013:   PetscDSGetBdTabulation(prob, &basisField, &basisFieldDer);
4014:   if (probAux) {
4015:     PetscDSGetNumFields(probAux, &NfAux);
4016:     PetscDSGetTotalBdDimension(probAux, &totDimAux);
4017:     PetscDSGetComponentBdOffsets(probAux, &aOff);
4018:     PetscDSGetComponentBdDerivativeOffsets(probAux, &aOff_x);
4019:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
4020:   }
4021:   for (e = 0; e < Ne; ++e) {
4022:     const PetscReal *quadPoints, *quadWeights;
4023:     PetscInt         Nq, q;

4025:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
4026:     PetscMemzero(f0, Nq*Nc* sizeof(PetscScalar));
4027:     PetscMemzero(f1, Nq*Nc*dim * sizeof(PetscScalar));
4028:     for (q = 0; q < Nq; ++q) {
4029:       const PetscReal *v0   = geom[e*Nq+q].v0;
4030:       const PetscReal *n    = geom[e*Nq+q].n;
4031:       const PetscReal *J    = geom[e*Nq+q].J;
4032:       const PetscReal *invJ = geom[e*Nq+q].invJ;
4033:       const PetscReal  detJ = geom[e*Nq+q].detJ;

4035:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
4036:       CoordinatesRefToReal(dim, dim-1, v0, J, &quadPoints[q*(dim-1)], x);
4037:       EvaluateFieldJets(prob,    PETSC_TRUE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
4038:       EvaluateFieldJets(probAux, PETSC_TRUE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
4039:       if (f0_func) f0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, n, &f0[q*Nc]);
4040:       if (f1_func) f1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, x, n, refSpaceDer);
4041:       TransformF(dim, Nc, q, invJ, detJ, quadWeights, refSpaceDer, f0, f1);
4042:     }
4043:     UpdateElementVec(dim, Nq, Nb, Nc, basisField[field], basisFieldDer[field], f0, f1, &elemVec[cOffset+fOffset]);
4044:     cOffset    += totDim;
4045:     cOffsetAux += totDimAux;
4046:   }
4047:   return(0);
4048: }

4052: PetscErrorCode PetscFEIntegrateJacobian_Nonaffine(PetscFE fem, PetscDS prob, PetscBool isPrec, PetscInt fieldI, PetscInt fieldJ, PetscInt Ne, PetscFECellGeom *geom,
4053:                                                   const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemMat[])
4054: {
4055:   const PetscInt  debug      = 0;
4056:   PetscPointJac   g0_func;
4057:   PetscPointJac   g1_func;
4058:   PetscPointJac   g2_func;
4059:   PetscPointJac   g3_func;
4060:   PetscFE         fe;
4061:   PetscInt        cOffset    = 0; /* Offset into coefficients[] for element e */
4062:   PetscInt        cOffsetAux = 0; /* Offset into coefficientsAux[] for element e */
4063:   PetscInt        eOffset    = 0; /* Offset into elemMat[] for element e */
4064:   PetscInt        offsetI    = 0; /* Offset into an element vector for fieldI */
4065:   PetscInt        offsetJ    = 0; /* Offset into an element vector for fieldJ */
4066:   PetscQuadrature quad;
4067:   PetscScalar    *g0, *g1, *g2, *g3, *u, *u_t, *u_x, *a, *a_x, *refSpaceDer;
4068:   PetscReal      *x;
4069:   PetscReal     **basisField, **basisFieldDer, *basisI, *basisDerI, *basisJ, *basisDerJ;
4070:   PetscInt        NbI = 0, NcI = 0, NbJ = 0, NcJ = 0;
4071:   PetscInt       *uOff, *uOff_x, *aOff = NULL, *aOff_x = NULL;
4072:   PetscInt        dim, Nf, NfAux = 0, totDim, totDimAux, e;
4073:   PetscErrorCode  ierr;

4076:   PetscFEGetSpatialDimension(fem, &dim);
4077:   PetscFEGetQuadrature(fem, &quad);
4078:   PetscDSGetNumFields(prob, &Nf);
4079:   PetscDSGetTotalDimension(prob, &totDim);
4080:   PetscDSGetComponentOffsets(prob, &uOff);
4081:   PetscDSGetComponentDerivativeOffsets(prob, &uOff_x);
4082:   if (isPrec) {PetscDSGetJacobianPreconditioner(prob, fieldI, fieldJ, &g0_func, &g1_func, &g2_func, &g3_func);}
4083:   else        {PetscDSGetJacobian(prob, fieldI, fieldJ, &g0_func, &g1_func, &g2_func, &g3_func);}
4084:   PetscDSGetEvaluationArrays(prob, &u, &u_t, &u_x);
4085:   PetscDSGetRefCoordArrays(prob, &x, &refSpaceDer);
4086:   PetscDSGetWeakFormArrays(prob, NULL, NULL, &g0, &g1, &g2, &g3);
4087:   PetscDSGetTabulation(prob, &basisField, &basisFieldDer);
4088:   PetscDSGetDiscretization(prob, fieldI, (PetscObject *) &fe);
4089:   PetscFEGetDimension(fe, &NbI);
4090:   PetscFEGetNumComponents(fe, &NcI);
4091:   PetscDSGetFieldOffset(prob, fieldI, &offsetI);
4092:   PetscDSGetDiscretization(prob, fieldJ, (PetscObject *) &fe);
4093:   PetscFEGetDimension(fe, &NbJ);
4094:   PetscFEGetNumComponents(fe, &NcJ);
4095:   PetscDSGetFieldOffset(prob, fieldJ, &offsetJ);
4096:   if (probAux) {
4097:     PetscDSGetNumFields(probAux, &NfAux);
4098:     PetscDSGetTotalDimension(probAux, &totDimAux);
4099:     PetscDSGetComponentOffsets(probAux, &aOff);
4100:     PetscDSGetComponentDerivativeOffsets(probAux, &aOff_x);
4101:     PetscDSGetEvaluationArrays(probAux, &a, NULL, &a_x);
4102:   }
4103:   basisI    = basisField[fieldI];
4104:   basisJ    = basisField[fieldJ];
4105:   basisDerI = basisFieldDer[fieldI];
4106:   basisDerJ = basisFieldDer[fieldJ];
4107:   /* Initialize here in case the function is not defined */
4108:   PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
4109:   PetscMemzero(g1, NcI*NcJ*dim * sizeof(PetscScalar));
4110:   PetscMemzero(g2, NcI*NcJ*dim * sizeof(PetscScalar));
4111:   PetscMemzero(g3, NcI*NcJ*dim*dim * sizeof(PetscScalar));
4112:   for (e = 0; e < Ne; ++e) {
4113:     const PetscReal *quadPoints, *quadWeights;
4114:     PetscInt         Nq, q;

4116:     PetscQuadratureGetData(quad, NULL, &Nq, &quadPoints, &quadWeights);
4117:     for (q = 0; q < Nq; ++q) {
4118:       const PetscReal *v0   = geom[e*Nq+q].v0;
4119:       const PetscReal *J    = geom[e*Nq+q].J;
4120:       const PetscReal *invJ = geom[e*Nq+q].invJ;
4121:       const PetscReal  detJ = geom[e*Nq+q].detJ;
4122:       PetscInt         f, g, fc, gc, c;

4124:       if (debug) {PetscPrintf(PETSC_COMM_SELF, "  quad point %d\n", q);}
4125:       CoordinatesRefToReal(dim, dim, v0, J, &quadPoints[q*dim], x);
4126:       EvaluateFieldJets(prob,    PETSC_FALSE, q, invJ, &coefficients[cOffset],       &coefficients_t[cOffset], u, u_x, u_t);
4127:       EvaluateFieldJets(probAux, PETSC_FALSE, q, invJ, &coefficientsAux[cOffsetAux], NULL,                     a, a_x, NULL);
4128:       if (g0_func) {
4129:         PetscMemzero(g0, NcI*NcJ * sizeof(PetscScalar));
4130:         g0_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, g0);
4131:         for (c = 0; c < NcI*NcJ; ++c) {g0[c] *= detJ*quadWeights[q];}
4132:       }
4133:       if (g1_func) {
4134:         PetscInt d, d2;
4135:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
4136:         g1_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
4137:         for (fc = 0; fc < NcI; ++fc) {
4138:           for (gc = 0; gc < NcJ; ++gc) {
4139:             for (d = 0; d < dim; ++d) {
4140:               g1[(fc*NcJ+gc)*dim+d] = 0.0;
4141:               for (d2 = 0; d2 < dim; ++d2) g1[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
4142:               g1[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
4143:             }
4144:           }
4145:         }
4146:       }
4147:       if (g2_func) {
4148:         PetscInt d, d2;
4149:         PetscMemzero(refSpaceDer, NcI*NcJ*dim * sizeof(PetscScalar));
4150:         g2_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
4151:         for (fc = 0; fc < NcI; ++fc) {
4152:           for (gc = 0; gc < NcJ; ++gc) {
4153:             for (d = 0; d < dim; ++d) {
4154:               g2[(fc*NcJ+gc)*dim+d] = 0.0;
4155:               for (d2 = 0; d2 < dim; ++d2) g2[(fc*NcJ+gc)*dim+d] += invJ[d*dim+d2]*refSpaceDer[(fc*NcJ+gc)*dim+d2];
4156:               g2[(fc*NcJ+gc)*dim+d] *= detJ*quadWeights[q];
4157:             }
4158:           }
4159:         }
4160:       }
4161:       if (g3_func) {
4162:         PetscInt d, d2, dp, d3;
4163:         PetscMemzero(refSpaceDer, NcI*NcJ*dim*dim * sizeof(PetscScalar));
4164:         g3_func(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, NULL, a_x, 0.0, 0.0, x, refSpaceDer);
4165:         for (fc = 0; fc < NcI; ++fc) {
4166:           for (gc = 0; gc < NcJ; ++gc) {
4167:             for (d = 0; d < dim; ++d) {
4168:               for (dp = 0; dp < dim; ++dp) {
4169:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] = 0.0;
4170:                 for (d2 = 0; d2 < dim; ++d2) {
4171:                   for (d3 = 0; d3 < dim; ++d3) {
4172:                     g3[((fc*NcJ+gc)*dim+d)*dim+dp] += invJ[d*dim+d2]*refSpaceDer[((fc*NcJ+gc)*dim+d2)*dim+d3]*invJ[dp*dim+d3];
4173:                   }
4174:                 }
4175:                 g3[((fc*NcJ+gc)*dim+d)*dim+dp] *= detJ*quadWeights[q];
4176:               }
4177:             }
4178:           }
4179:         }
4180:       }

4182:       for (f = 0; f < NbI; ++f) {
4183:         for (fc = 0; fc < NcI; ++fc) {
4184:           const PetscInt fidx = f*NcI+fc; /* Test function basis index */
4185:           const PetscInt i    = offsetI+fidx; /* Element matrix row */
4186:           for (g = 0; g < NbJ; ++g) {
4187:             for (gc = 0; gc < NcJ; ++gc) {
4188:               const PetscInt gidx = g*NcJ+gc; /* Trial function basis index */
4189:               const PetscInt j    = offsetJ+gidx; /* Element matrix column */
4190:               const PetscInt fOff = eOffset+i*totDim+j;
4191:               PetscInt       d, d2;

4193:               elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g0[fc*NcJ+gc]*basisJ[q*NbJ*NcJ+gidx];
4194:               for (d = 0; d < dim; ++d) {
4195:                 elemMat[fOff] += basisI[q*NbI*NcI+fidx]*g1[(fc*NcJ+gc)*dim+d]*basisDerJ[(q*NbJ*NcJ+gidx)*dim+d];
4196:                 elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*dim+d]*g2[(fc*NcJ+gc)*dim+d]*basisJ[q*NbJ*NcJ+gidx];
4197:                 for (d2 = 0; d2 < dim; ++d2) {
4198:                   elemMat[fOff] += basisDerI[(q*NbI*NcI+fidx)*dim+d]*g3[((fc*NcJ+gc)*dim+d)*dim+d2]*basisDerJ[(q*NbJ*NcJ+gidx)*dim+d2];
4199:                 }
4200:               }
4201:             }
4202:           }
4203:         }
4204:       }
4205:     }
4206:     if (debug > 1) {
4207:       PetscInt fc, f, gc, g;

4209:       PetscPrintf(PETSC_COMM_SELF, "Element matrix for fields %d and %d\n", fieldI, fieldJ);
4210:       for (fc = 0; fc < NcI; ++fc) {
4211:         for (f = 0; f < NbI; ++f) {
4212:           const PetscInt i = offsetI + f*NcI+fc;
4213:           for (gc = 0; gc < NcJ; ++gc) {
4214:             for (g = 0; g < NbJ; ++g) {
4215:               const PetscInt j = offsetJ + g*NcJ+gc;
4216:               PetscPrintf(PETSC_COMM_SELF, "    elemMat[%d,%d,%d,%d]: %g\n", f, fc, g, gc, PetscRealPart(elemMat[eOffset+i*totDim+j]));
4217:             }
4218:           }
4219:           PetscPrintf(PETSC_COMM_SELF, "\n");
4220:         }
4221:       }
4222:     }
4223:     cOffset    += totDim;
4224:     cOffsetAux += totDimAux;
4225:     eOffset    += PetscSqr(totDim);
4226:   }
4227:   return(0);
4228: }

4232: PetscErrorCode PetscFEInitialize_Nonaffine(PetscFE fem)
4233: {
4235:   fem->ops->setfromoptions          = NULL;
4236:   fem->ops->setup                   = PetscFESetUp_Basic;
4237:   fem->ops->view                    = NULL;
4238:   fem->ops->destroy                 = PetscFEDestroy_Nonaffine;
4239:   fem->ops->getdimension            = PetscFEGetDimension_Basic;
4240:   fem->ops->gettabulation           = PetscFEGetTabulation_Basic;
4241:   fem->ops->integrateresidual       = PetscFEIntegrateResidual_Nonaffine;
4242:   fem->ops->integratebdresidual     = PetscFEIntegrateBdResidual_Nonaffine;
4243:   fem->ops->integratejacobianaction = NULL/* PetscFEIntegrateJacobianAction_Nonaffine */;
4244:   fem->ops->integratejacobian       = PetscFEIntegrateJacobian_Nonaffine;
4245:   return(0);
4246: }

4248: /*MC
4249:   PETSCFENONAFFINE = "nonaffine" - A PetscFE object that integrates with basic tiling and no vectorization for non-affine mappings

4251:   Level: intermediate

4253: .seealso: PetscFEType, PetscFECreate(), PetscFESetType()
4254: M*/

4258: PETSC_EXTERN PetscErrorCode PetscFECreate_Nonaffine(PetscFE fem)
4259: {
4260:   PetscFE_Nonaffine *na;
4261:   PetscErrorCode     ierr;

4265:   PetscNewLog(fem, &na);
4266:   fem->data = na;

4268:   PetscFEInitialize_Nonaffine(fem);
4269:   return(0);
4270: }

4272: #ifdef PETSC_HAVE_OPENCL

4276: PetscErrorCode PetscFEDestroy_OpenCL(PetscFE fem)
4277: {
4278:   PetscFE_OpenCL *ocl = (PetscFE_OpenCL *) fem->data;
4279:   PetscErrorCode  ierr;

4282:   clReleaseCommandQueue(ocl->queue_id);
4283:   ocl->queue_id = 0;
4284:   clReleaseContext(ocl->ctx_id);
4285:   ocl->ctx_id = 0;
4286:   PetscFree(ocl);
4287:   return(0);
4288: }

4290: #define STRING_ERROR_CHECK(MSG) do { string_tail += count; if (string_tail == end_of_buffer) SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, MSG);} while(0)
4291: enum {LAPLACIAN = 0, ELASTICITY = 1};

4295: /* dim     Number of spatial dimensions:          2                   */
4296: /* N_b     Number of basis functions:             generated           */
4297: /* N_{bt}  Number of total basis functions:       N_b * N_{comp}      */
4298: /* N_q     Number of quadrature points:           generated           */
4299: /* N_{bs}  Number of block cells                  LCM(N_b, N_q)       */
4300: /* N_{bst} Number of block cell components        LCM(N_{bt}, N_q)    */
4301: /* N_{bl}  Number of concurrent blocks            generated           */
4302: /* N_t     Number of threads:                     N_{bl} * N_{bs}     */
4303: /* N_{cbc} Number of concurrent basis      cells: N_{bl} * N_q        */
4304: /* N_{cqc} Number of concurrent quadrature cells: N_{bl} * N_b        */
4305: /* N_{sbc} Number of serial     basis      cells: N_{bs} / N_q        */
4306: /* N_{sqc} Number of serial     quadrature cells: N_{bs} / N_b        */
4307: /* N_{cb}  Number of serial cell batches:         input               */
4308: /* N_c     Number of total cells:                 N_{cb}*N_{t}/N_{comp} */
4309: PetscErrorCode PetscFEOpenCLGenerateIntegrationCode(PetscFE fem, char **string_buffer, PetscInt buffer_length, PetscBool useAux, PetscInt N_bl)
4310: {
4311:   PetscFE_OpenCL *ocl = (PetscFE_OpenCL *) fem->data;
4312:   PetscQuadrature q;
4313:   char           *string_tail   = *string_buffer;
4314:   char           *end_of_buffer = *string_buffer + buffer_length;
4315:   char            float_str[]   = "float", double_str[]  = "double";
4316:   char           *numeric_str   = &(float_str[0]);
4317:   PetscInt        op            = ocl->op;
4318:   PetscBool       useField      = PETSC_FALSE;
4319:   PetscBool       useFieldDer   = PETSC_TRUE;
4320:   PetscBool       useFieldAux   = useAux;
4321:   PetscBool       useFieldDerAux= PETSC_FALSE;
4322:   PetscBool       useF0         = PETSC_TRUE;
4323:   PetscBool       useF1         = PETSC_TRUE;
4324:   PetscReal      *basis, *basisDer;
4325:   PetscInt        dim, N_b, N_c, N_q, N_t, p, d, b, c;
4326:   size_t          count;
4327:   PetscErrorCode  ierr;

4330:   PetscFEGetSpatialDimension(fem, &dim);
4331:   PetscFEGetDimension(fem, &N_b);
4332:   PetscFEGetNumComponents(fem, &N_c);
4333:   PetscFEGetQuadrature(fem, &q);
4334:   N_q  = q->numPoints;
4335:   N_t  = N_b * N_c * N_q * N_bl;
4336:   /* Enable device extension for double precision */
4337:   if (ocl->realType == PETSC_DOUBLE) {
4338:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4339: "#if defined(cl_khr_fp64)\n"
4340: "#  pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
4341: "#elif defined(cl_amd_fp64)\n"
4342: "#  pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
4343: "#endif\n",
4344:                               &count);STRING_ERROR_CHECK("Message to short");
4345:     numeric_str  = &(double_str[0]);
4346:   }
4347:   /* Kernel API */
4348:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4349: "\n"
4350: "__kernel void integrateElementQuadrature(int N_cb, __global %s *coefficients, __global %s *coefficientsAux, __global %s *jacobianInverses, __global %s *jacobianDeterminants, __global %s *elemVec)\n"
4351: "{\n",
4352:                        &count, numeric_str, numeric_str, numeric_str, numeric_str, numeric_str);STRING_ERROR_CHECK("Message to short");
4353:   /* Quadrature */
4354:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4355: "  /* Quadrature points\n"
4356: "   - (x1,y1,x2,y2,...) */\n"
4357: "  const %s points[%d] = {\n",
4358:                        &count, numeric_str, N_q*dim);STRING_ERROR_CHECK("Message to short");
4359:   for (p = 0; p < N_q; ++p) {
4360:     for (d = 0; d < dim; ++d) {
4361:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "%g,\n", &count, q->points[p*dim+d]);STRING_ERROR_CHECK("Message to short");
4362:     }
4363:   }
4364:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "};\n", &count);STRING_ERROR_CHECK("Message to short");
4365:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4366: "  /* Quadrature weights\n"
4367: "   - (v1,v2,...) */\n"
4368: "  const %s weights[%d] = {\n",
4369:                        &count, numeric_str, N_q);STRING_ERROR_CHECK("Message to short");
4370:   for (p = 0; p < N_q; ++p) {
4371:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "%g,\n", &count, q->weights[p]);STRING_ERROR_CHECK("Message to short");
4372:   }
4373:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "};\n", &count);STRING_ERROR_CHECK("Message to short");
4374:   /* Basis Functions */
4375:   PetscFEGetDefaultTabulation(fem, &basis, &basisDer, NULL);
4376:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4377: "  /* Nodal basis function evaluations\n"
4378: "    - basis component is fastest varying, the basis function, then point */\n"
4379: "  const %s Basis[%d] = {\n",
4380:                        &count, numeric_str, N_q*N_b*N_c);STRING_ERROR_CHECK("Message to short");
4381:   for (p = 0; p < N_q; ++p) {
4382:     for (b = 0; b < N_b; ++b) {
4383:       for (c = 0; c < N_c; ++c) {
4384:         PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "%g,\n", &count, basis[(p*N_b + b)*N_c + c]);STRING_ERROR_CHECK("Message to short");
4385:       }
4386:     }
4387:   }
4388:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "};\n", &count);STRING_ERROR_CHECK("Message to short");
4389:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4390: "\n"
4391: "  /* Nodal basis function derivative evaluations,\n"
4392: "      - derivative direction is fastest varying, then basis component, then basis function, then point */\n"
4393: "  const %s%d BasisDerivatives[%d] = {\n",
4394:                        &count, numeric_str, dim, N_q*N_b*N_c);STRING_ERROR_CHECK("Message to short");
4395:   for (p = 0; p < N_q; ++p) {
4396:     for (b = 0; b < N_b; ++b) {
4397:       for (c = 0; c < N_c; ++c) {
4398:         PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "(%s%d)(", &count, numeric_str, dim);STRING_ERROR_CHECK("Message to short");
4399:         for (d = 0; d < dim; ++d) {
4400:           if (d > 0) {
4401:             PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, ", %g", &count, basisDer[((p*N_b + b)*dim + d)*N_c + c]);STRING_ERROR_CHECK("Message to short");
4402:           } else {
4403:             PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "%g", &count, basisDer[((p*N_b + b)*dim + d)*N_c + c]);STRING_ERROR_CHECK("Message to short");
4404:           }
4405:         }
4406:         PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "),\n", &count);STRING_ERROR_CHECK("Message to short");
4407:       }
4408:     }
4409:   }
4410:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "};\n", &count);STRING_ERROR_CHECK("Message to short");
4411:   /* Sizes */
4412:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4413: "  const int dim    = %d;                           // The spatial dimension\n"
4414: "  const int N_bl   = %d;                           // The number of concurrent blocks\n"
4415: "  const int N_b    = %d;                           // The number of basis functions\n"
4416: "  const int N_comp = %d;                           // The number of basis function components\n"
4417: "  const int N_bt   = N_b*N_comp;                    // The total number of scalar basis functions\n"
4418: "  const int N_q    = %d;                           // The number of quadrature points\n"
4419: "  const int N_bst  = N_bt*N_q;                      // The block size, LCM(N_b*N_comp, N_q), Notice that a block is not processed simultaneously\n"
4420: "  const int N_t    = N_bst*N_bl;                    // The number of threads, N_bst * N_bl\n"
4421: "  const int N_bc   = N_t/N_comp;                    // The number of cells per batch (N_b*N_q*N_bl)\n"
4422: "  const int N_sbc  = N_bst / (N_q * N_comp);\n"
4423: "  const int N_sqc  = N_bst / N_bt;\n"
4424: "  /*const int N_c    = N_cb * N_bc;*/\n"
4425: "\n"
4426: "  /* Calculated indices */\n"
4427: "  /*const int tidx    = get_local_id(0) + get_local_size(0)*get_local_id(1);*/\n"
4428: "  const int tidx    = get_local_id(0);\n"
4429: "  const int blidx   = tidx / N_bst;                  // Block number for this thread\n"
4430: "  const int bidx    = tidx %% N_bt;                   // Basis function mapped to this thread\n"
4431: "  const int cidx    = tidx %% N_comp;                 // Basis component mapped to this thread\n"
4432: "  const int qidx    = tidx %% N_q;                    // Quadrature point mapped to this thread\n"
4433: "  const int blbidx  = tidx %% N_q + blidx*N_q;        // Cell mapped to this thread in the basis phase\n"
4434: "  const int blqidx  = tidx %% N_b + blidx*N_b;        // Cell mapped to this thread in the quadrature phase\n"
4435: "  const int gidx    = get_group_id(1)*get_num_groups(0) + get_group_id(0);\n"
4436: "  const int Goffset = gidx*N_cb*N_bc;\n",
4437:                             &count, dim, N_bl, N_b, N_c, N_q);STRING_ERROR_CHECK("Message to short");
4438:   /* Local memory */
4439:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4440: "\n"
4441: "  /* Quadrature data */\n"
4442: "  %s                w;                   // $w_q$, Quadrature weight at $x_q$\n"
4443: "  __local %s         phi_i[%d];    //[N_bt*N_q];  // $\\phi_i(x_q)$, Value of the basis function $i$ at $x_q$\n"
4444: "  __local %s%d       phiDer_i[%d]; //[N_bt*N_q];  // $\\frac{\\partial\\phi_i(x_q)}{\\partial x_d}$, Value of the derivative of basis function $i$ in direction $x_d$ at $x_q$\n"
4445: "  /* Geometric data */\n"
4446: "  __local %s        detJ[%d]; //[N_t];           // $|J(x_q)|$, Jacobian determinant at $x_q$\n"
4447: "  __local %s        invJ[%d];//[N_t*dim*dim];   // $J^{-1}(x_q)$, Jacobian inverse at $x_q$\n",
4448:                             &count, numeric_str, numeric_str, N_b*N_c*N_q, numeric_str, dim, N_b*N_c*N_q, numeric_str, N_t,
4449:                             numeric_str, N_t*dim*dim, numeric_str, N_t*N_b*N_c);STRING_ERROR_CHECK("Message to short");
4450:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4451: "  /* FEM data */\n"
4452: "  __local %s        u_i[%d]; //[N_t*N_bt];       // Coefficients $u_i$ of the field $u|_{\\mathcal{T}} = \\sum_i u_i \\phi_i$\n",
4453:                             &count, numeric_str, N_t*N_b*N_c);STRING_ERROR_CHECK("Message to short");
4454:   if (useAux) {
4455:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4456: "  __local %s        a_i[%d]; //[N_t];            // Coefficients $a_i$ of the auxiliary field $a|_{\\mathcal{T}} = \\sum_i a_i \\phi^R_i$\n",
4457:                             &count, numeric_str, N_t);STRING_ERROR_CHECK("Message to short");
4458:   }
4459:   if (useF0) {
4460:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4461: "  /* Intermediate calculations */\n"
4462: "  __local %s         f_0[%d]; //[N_t*N_sqc];      // $f_0(u(x_q), \\nabla u(x_q)) |J(x_q)| w_q$\n",
4463:                               &count, numeric_str, N_t*N_q);STRING_ERROR_CHECK("Message to short");
4464:   }
4465:   if (useF1) {
4466:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4467: "  __local %s%d       f_1[%d]; //[N_t*N_sqc];      // $f_1(u(x_q), \\nabla u(x_q)) |J(x_q)| w_q$\n",
4468:                               &count, numeric_str, dim, N_t*N_q);STRING_ERROR_CHECK("Message to short");
4469:   }
4470:   /* TODO: If using elasticity, put in mu/lambda coefficients */
4471:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4472: "  /* Output data */\n"
4473: "  %s                e_i;                 // Coefficient $e_i$ of the residual\n\n",
4474:                             &count, numeric_str);STRING_ERROR_CHECK("Message to short");
4475:   /* One-time loads */
4476:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4477: "  /* These should be generated inline */\n"
4478: "  /* Load quadrature weights */\n"
4479: "  w = weights[qidx];\n"
4480: "  /* Load basis tabulation \\phi_i for this cell */\n"
4481: "  if (tidx < N_bt*N_q) {\n"
4482: "    phi_i[tidx]    = Basis[tidx];\n"
4483: "    phiDer_i[tidx] = BasisDerivatives[tidx];\n"
4484: "  }\n\n",
4485:                        &count);STRING_ERROR_CHECK("Message to short");
4486:   /* Batch loads */
4487:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4488: "  for (int batch = 0; batch < N_cb; ++batch) {\n"
4489: "    /* Load geometry */\n"
4490: "    detJ[tidx] = jacobianDeterminants[Goffset+batch*N_bc+tidx];\n"
4491: "    for (int n = 0; n < dim*dim; ++n) {\n"
4492: "      const int offset = n*N_t;\n"
4493: "      invJ[offset+tidx] = jacobianInverses[(Goffset+batch*N_bc)*dim*dim+offset+tidx];\n"
4494: "    }\n"
4495: "    /* Load coefficients u_i for this cell */\n"
4496: "    for (int n = 0; n < N_bt; ++n) {\n"
4497: "      const int offset = n*N_t;\n"
4498: "      u_i[offset+tidx] = coefficients[(Goffset*N_bt)+batch*N_t*N_b+offset+tidx];\n"
4499: "    }\n",
4500:                        &count);STRING_ERROR_CHECK("Message to short");
4501:   if (useAux) {
4502:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4503: "    /* Load coefficients a_i for this cell */\n"
4504: "    /* TODO: This should not be N_t here, it should be N_bc*N_comp_aux */\n"
4505: "    a_i[tidx] = coefficientsAux[Goffset+batch*N_t+tidx];\n",
4506:                             &count);STRING_ERROR_CHECK("Message to short");
4507:   }
4508:   /* Quadrature phase */
4509:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4510: "    barrier(CLK_LOCAL_MEM_FENCE);\n"
4511: "\n"
4512: "    /* Map coefficients to values at quadrature points */\n"
4513: "    for (int c = 0; c < N_sqc; ++c) {\n"
4514: "      const int cell          = c*N_bl*N_b + blqidx;\n"
4515: "      const int fidx          = (cell*N_q + qidx)*N_comp + cidx;\n",
4516:                        &count);STRING_ERROR_CHECK("Message to short");
4517:   if (useField) {
4518:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4519: "      %s  u[%d]; //[N_comp];     // $u(x_q)$, Value of the field at $x_q$\n",
4520:                               &count, numeric_str, N_c);STRING_ERROR_CHECK("Message to short");
4521:   }
4522:   if (useFieldDer) {
4523:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4524: "      %s%d   gradU[%d]; //[N_comp]; // $\\nabla u(x_q)$, Value of the field gradient at $x_q$\n",
4525:                               &count, numeric_str, dim, N_c);STRING_ERROR_CHECK("Message to short");
4526:   }
4527:   if (useFieldAux) {
4528:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4529: "      %s  a[%d]; //[1];     // $a(x_q)$, Value of the auxiliary fields at $x_q$\n",
4530:                               &count, numeric_str, 1);STRING_ERROR_CHECK("Message to short");
4531:   }
4532:   if (useFieldDerAux) {
4533:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4534: "      %s%d   gradA[%d]; //[1]; // $\\nabla a(x_q)$, Value of the auxiliary field gradient at $x_q$\n",
4535:                               &count, numeric_str, dim, 1);STRING_ERROR_CHECK("Message to short");
4536:   }
4537:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4538: "\n"
4539: "      for (int comp = 0; comp < N_comp; ++comp) {\n",
4540:                             &count);STRING_ERROR_CHECK("Message to short");
4541:   if (useField) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "        u[comp] = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");}
4542:   if (useFieldDer) {
4543:     switch (dim) {
4544:     case 1:
4545:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "        gradU[comp].x = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4546:     case 2:
4547:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "        gradU[comp].x = 0.0; gradU[comp].y = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4548:     case 3:
4549:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "        gradU[comp].x = 0.0; gradU[comp].y = 0.0; gradU[comp].z = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4550:     }
4551:   }
4552:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4553: "      }\n",
4554:                             &count);STRING_ERROR_CHECK("Message to short");
4555:   if (useFieldAux) {
4556:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      a[0] = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");
4557:   }
4558:   if (useFieldDerAux) {
4559:     switch (dim) {
4560:     case 1:
4561:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      gradA[0].x = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4562:     case 2:
4563:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      gradA[0].x = 0.0; gradA[0].y = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4564:     case 3:
4565:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      gradA[0].x = 0.0; gradA[0].y = 0.0; gradA[0].z = 0.0;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4566:     }
4567:   }
4568:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4569: "      /* Get field and derivatives at this quadrature point */\n"
4570: "      for (int i = 0; i < N_b; ++i) {\n"
4571: "        for (int comp = 0; comp < N_comp; ++comp) {\n"
4572: "          const int b    = i*N_comp+comp;\n"
4573: "          const int pidx = qidx*N_bt + b;\n"
4574: "          const int uidx = cell*N_bt + b;\n"
4575: "          %s%d   realSpaceDer;\n\n",
4576:                             &count, numeric_str, dim);STRING_ERROR_CHECK("Message to short");
4577:   if (useField) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"          u[comp] += u_i[uidx]*phi_i[pidx];\n", &count);STRING_ERROR_CHECK("Message to short");}
4578:   if (useFieldDer) {
4579:     switch (dim) {
4580:     case 2:
4581:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4582: "          realSpaceDer.x = invJ[cell*dim*dim+0*dim+0]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+0]*phiDer_i[pidx].y;\n"
4583: "          gradU[comp].x += u_i[uidx]*realSpaceDer.x;\n"
4584: "          realSpaceDer.y = invJ[cell*dim*dim+0*dim+1]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+1]*phiDer_i[pidx].y;\n"
4585: "          gradU[comp].y += u_i[uidx]*realSpaceDer.y;\n",
4586:                            &count);STRING_ERROR_CHECK("Message to short");break;
4587:     case 3:
4588:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4589: "          realSpaceDer.x = invJ[cell*dim*dim+0*dim+0]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+0]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+0]*phiDer_i[pidx].z;\n"
4590: "          gradU[comp].x += u_i[uidx]*realSpaceDer.x;\n"
4591: "          realSpaceDer.y = invJ[cell*dim*dim+0*dim+1]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+1]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+1]*phiDer_i[pidx].z;\n"
4592: "          gradU[comp].y += u_i[uidx]*realSpaceDer.y;\n"
4593: "          realSpaceDer.z = invJ[cell*dim*dim+0*dim+2]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+2]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+2]*phiDer_i[pidx].z;\n"
4594: "          gradU[comp].z += u_i[uidx]*realSpaceDer.z;\n",
4595:                            &count);STRING_ERROR_CHECK("Message to short");break;
4596:     }
4597:   }
4598:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4599: "        }\n"
4600: "      }\n",
4601:                             &count);STRING_ERROR_CHECK("Message to short");
4602:   if (useFieldAux) {
4603:     PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"          a[0] += a_i[cell];\n", &count);STRING_ERROR_CHECK("Message to short");
4604:   }
4605:   /* Calculate residual at quadrature points: Should be generated by an weak form egine */
4606:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4607: "      /* Process values at quadrature points */\n",
4608:                             &count);STRING_ERROR_CHECK("Message to short");
4609:   switch (op) {
4610:   case LAPLACIAN:
4611:     if (useF0) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      f_0[fidx] = 4.0;\n", &count);STRING_ERROR_CHECK("Message to short");}
4612:     if (useF1) {
4613:       if (useAux) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      f_1[fidx] = a[0]*gradU[cidx];\n", &count);STRING_ERROR_CHECK("Message to short");}
4614:       else        {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      f_1[fidx] = gradU[cidx];\n", &count);STRING_ERROR_CHECK("Message to short");}
4615:     }
4616:     break;
4617:   case ELASTICITY:
4618:     if (useF0) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail, "      f_0[fidx] = 4.0;\n", &count);STRING_ERROR_CHECK("Message to short");}
4619:     if (useF1) {
4620:     switch (dim) {
4621:     case 2:
4622:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4623: "      switch (cidx) {\n"
4624: "      case 0:\n"
4625: "        f_1[fidx].x = lambda*(gradU[0].x + gradU[1].y) + mu*(gradU[0].x + gradU[0].x);\n"
4626: "        f_1[fidx].y = lambda*(gradU[0].x + gradU[1].y) + mu*(gradU[0].y + gradU[1].x);\n"
4627: "        break;\n"
4628: "      case 1:\n"
4629: "        f_1[fidx].x = lambda*(gradU[0].x + gradU[1].y) + mu*(gradU[1].x + gradU[0].y);\n"
4630: "        f_1[fidx].y = lambda*(gradU[0].x + gradU[1].y) + mu*(gradU[1].y + gradU[1].y);\n"
4631: "      }\n",
4632:                            &count);STRING_ERROR_CHECK("Message to short");break;
4633:     case 3:
4634:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4635: "      switch (cidx) {\n"
4636: "      case 0:\n"
4637: "        f_1[fidx].x = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[0].x + gradU[0].x);\n"
4638: "        f_1[fidx].y = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[0].y + gradU[1].x);\n"
4639: "        f_1[fidx].z = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[0].z + gradU[2].x);\n"
4640: "        break;\n"
4641: "      case 1:\n"
4642: "        f_1[fidx].x = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[1].x + gradU[0].y);\n"
4643: "        f_1[fidx].y = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[1].y + gradU[1].y);\n"
4644: "        f_1[fidx].z = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[1].y + gradU[2].y);\n"
4645: "        break;\n"
4646: "      case 2:\n"
4647: "        f_1[fidx].x = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[2].x + gradU[0].z);\n"
4648: "        f_1[fidx].y = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[2].y + gradU[1].z);\n"
4649: "        f_1[fidx].z = lambda*(gradU[0].x + gradU[1].y + gradU[2].z) + mu*(gradU[2].y + gradU[2].z);\n"
4650: "      }\n",
4651:                            &count);STRING_ERROR_CHECK("Message to short");break;
4652:     }}
4653:     break;
4654:   default:
4655:     SETERRQ1(PETSC_COMM_WORLD, PETSC_ERR_SUP, "PDE operator %d is not supported", op);
4656:   }
4657:   if (useF0) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"      f_0[fidx] *= detJ[cell]*w;\n", &count);STRING_ERROR_CHECK("Message to short");}
4658:   if (useF1) {
4659:     switch (dim) {
4660:     case 1:
4661:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"      f_1[fidx].x *= detJ[cell]*w;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4662:     case 2:
4663:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"      f_1[fidx].x *= detJ[cell]*w; f_1[fidx].y *= detJ[cell]*w;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4664:     case 3:
4665:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"      f_1[fidx].x *= detJ[cell]*w; f_1[fidx].y *= detJ[cell]*w; f_1[fidx].z *= detJ[cell]*w;\n", &count);STRING_ERROR_CHECK("Message to short");break;
4666:     }
4667:   }
4668:   /* Thread transpose */
4669:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4670: "    }\n\n"
4671: "    /* ==== TRANSPOSE THREADS ==== */\n"
4672: "    barrier(CLK_LOCAL_MEM_FENCE);\n\n",
4673:                        &count);STRING_ERROR_CHECK("Message to short");
4674:   /* Basis phase */
4675:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4676: "    /* Map values at quadrature points to coefficients */\n"
4677: "    for (int c = 0; c < N_sbc; ++c) {\n"
4678: "      const int cell = c*N_bl*N_q + blbidx; /* Cell number in batch */\n"
4679: "\n"
4680: "      e_i = 0.0;\n"
4681: "      for (int q = 0; q < N_q; ++q) {\n"
4682: "        const int pidx = q*N_bt + bidx;\n"
4683: "        const int fidx = (cell*N_q + q)*N_comp + cidx;\n"
4684: "        %s%d   realSpaceDer;\n\n",
4685:                        &count, numeric_str, dim);STRING_ERROR_CHECK("Message to short");

4687:   if (useF0) {PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,"        e_i += phi_i[pidx]*f_0[fidx];\n", &count);STRING_ERROR_CHECK("Message to short");}
4688:   if (useF1) {
4689:     switch (dim) {
4690:     case 2:
4691:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4692: "        realSpaceDer.x = invJ[cell*dim*dim+0*dim+0]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+0]*phiDer_i[pidx].y;\n"
4693: "        e_i           += realSpaceDer.x*f_1[fidx].x;\n"
4694: "        realSpaceDer.y = invJ[cell*dim*dim+0*dim+1]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+1]*phiDer_i[pidx].y;\n"
4695: "        e_i           += realSpaceDer.y*f_1[fidx].y;\n",
4696:                            &count);STRING_ERROR_CHECK("Message to short");break;
4697:     case 3:
4698:       PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4699: "        realSpaceDer.x = invJ[cell*dim*dim+0*dim+0]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+0]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+0]*phiDer_i[pidx].z;\n"
4700: "        e_i           += realSpaceDer.x*f_1[fidx].x;\n"
4701: "        realSpaceDer.y = invJ[cell*dim*dim+0*dim+1]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+1]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+1]*phiDer_i[pidx].z;\n"
4702: "        e_i           += realSpaceDer.y*f_1[fidx].y;\n"
4703: "        realSpaceDer.z = invJ[cell*dim*dim+0*dim+2]*phiDer_i[pidx].x + invJ[cell*dim*dim+1*dim+2]*phiDer_i[pidx].y + invJ[cell*dim*dim+2*dim+2]*phiDer_i[pidx].z;\n"
4704: "        e_i           += realSpaceDer.z*f_1[fidx].z;\n",
4705:                            &count);STRING_ERROR_CHECK("Message to short");break;
4706:     }
4707:   }
4708:   PetscSNPrintfCount(string_tail, end_of_buffer - string_tail,
4709: "      }\n"
4710: "      /* Write element vector for N_{cbc} cells at a time */\n"
4711: "      elemVec[(Goffset + batch*N_bc + c*N_bl*N_q)*N_bt + tidx] = e_i;\n"
4712: "    }\n"
4713: "    /* ==== Could do one write per batch ==== */\n"
4714: "  }\n"
4715: "  return;\n"
4716: "}\n",
4717:                        &count);STRING_ERROR_CHECK("Message to short");
4718:   return(0);
4719: }

4723: PetscErrorCode PetscFEOpenCLGetIntegrationKernel(PetscFE fem, PetscBool useAux, cl_program *ocl_prog, cl_kernel *ocl_kernel)
4724: {
4725:   PetscFE_OpenCL *ocl = (PetscFE_OpenCL *) fem->data;
4726:   PetscInt        dim, N_bl;
4727:   PetscBool       flg;
4728:   char           *buffer;
4729:   size_t          len;
4730:   char            errMsg[8192];
4731:   cl_int          ierr2;
4732:   PetscErrorCode  ierr;

4735:   PetscFEGetSpatialDimension(fem, &dim);
4736:   PetscMalloc1(8192, &buffer);
4737:   PetscFEGetTileSizes(fem, NULL, &N_bl, NULL, NULL);
4738:   PetscFEOpenCLGenerateIntegrationCode(fem, &buffer, 8192, useAux, N_bl);
4739:   PetscOptionsHasName(((PetscObject)fem)->options,((PetscObject)fem)->prefix, "-petscfe_opencl_kernel_print", &flg);
4740:   if (flg) {PetscPrintf(PetscObjectComm((PetscObject) fem), "OpenCL FE Integration Kernel:\n%s\n", buffer);}
4741:   len  = strlen(buffer);
4742:   *ocl_prog = clCreateProgramWithSource(ocl->ctx_id, 1, (const char **) &buffer, &len, &ierr2);CHKERRQ(ierr2);
4743:   clBuildProgram(*ocl_prog, 0, NULL, NULL, NULL, NULL);
4744:   if (ierr != CL_SUCCESS) {
4745:     clGetProgramBuildInfo(*ocl_prog, ocl->dev_id, CL_PROGRAM_BUILD_LOG, 8192*sizeof(char), &errMsg, NULL);
4746:     SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Build failed! Log:\n %s", errMsg);
4747:   }
4748:   PetscFree(buffer);
4749:   *ocl_kernel = clCreateKernel(*ocl_prog, "integrateElementQuadrature", &ierr);
4750:   return(0);
4751: }

4755: PetscErrorCode PetscFEOpenCLCalculateGrid(PetscFE fem, PetscInt N, PetscInt blockSize, size_t *x, size_t *y, size_t *z)
4756: {
4757:   const PetscInt Nblocks = N/blockSize;

4760:   if (N % blockSize) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Invalid block size %d for %d elements", blockSize, N);
4761:   *z = 1;
4762:   for (*x = (size_t) (PetscSqrtReal(Nblocks) + 0.5); *x > 0; --*x) {
4763:     *y = Nblocks / *x;
4764:     if (*x * *y == Nblocks) break;
4765:   }
4766:   if (*x * *y != Nblocks) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Could not find partition for %d with block size %d", N, blockSize);
4767:   return(0);
4768: }

4772: PetscErrorCode PetscFEOpenCLLogResidual(PetscFE fem, PetscLogDouble time, PetscLogDouble flops)
4773: {
4774:   PetscFE_OpenCL   *ocl = (PetscFE_OpenCL *) fem->data;
4775:   PetscStageLog     stageLog;
4776:   PetscEventPerfLog eventLog = NULL;
4777:   PetscInt          stage;
4778:   PetscErrorCode    ierr;

4781:   PetscLogGetStageLog(&stageLog);
4782:   PetscStageLogGetCurrent(stageLog, &stage);
4783:   PetscStageLogGetEventPerfLog(stageLog, stage, &eventLog);
4784:     /* Log performance info */
4785:   eventLog->eventInfo[ocl->residualEvent].count++;
4786:   eventLog->eventInfo[ocl->residualEvent].time  += time;
4787:   eventLog->eventInfo[ocl->residualEvent].flops += flops;
4788:   return(0);
4789: }

4793: PetscErrorCode PetscFEIntegrateResidual_OpenCL(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
4794:                                                const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
4795: {
4796:   /* Nbc = batchSize */
4797:   PetscFE_OpenCL   *ocl = (PetscFE_OpenCL *) fem->data;
4798:   PetscPointFunc    f0_func;
4799:   PetscPointFunc    f1_func;
4800:   PetscQuadrature   q;
4801:   PetscInt          dim;
4802:   PetscInt          N_b;    /* The number of basis functions */
4803:   PetscInt          N_comp; /* The number of basis function components */
4804:   PetscInt          N_bt;   /* The total number of scalar basis functions */
4805:   PetscInt          N_q;    /* The number of quadrature points */
4806:   PetscInt          N_bst;  /* The block size, LCM(N_bt, N_q), Notice that a block is not process simultaneously */
4807:   PetscInt          N_t;    /* The number of threads, N_bst * N_bl */
4808:   PetscInt          N_bl;   /* The number of blocks */
4809:   PetscInt          N_bc;   /* The batch size, N_bl*N_q*N_b */
4810:   PetscInt          N_cb;   /* The number of batches */
4811:   PetscInt          numFlops, f0Flops = 0, f1Flops = 0;
4812:   PetscBool         useAux      = probAux ? PETSC_TRUE : PETSC_FALSE;
4813:   PetscBool         useField    = PETSC_FALSE;
4814:   PetscBool         useFieldDer = PETSC_TRUE;
4815:   PetscBool         useF0       = PETSC_TRUE;
4816:   PetscBool         useF1       = PETSC_TRUE;
4817:   /* OpenCL variables */
4818:   cl_program        ocl_prog;
4819:   cl_kernel         ocl_kernel;
4820:   cl_event          ocl_ev;         /* The event for tracking kernel execution */
4821:   cl_ulong          ns_start;       /* Nanoseconds counter on GPU at kernel start */
4822:   cl_ulong          ns_end;         /* Nanoseconds counter on GPU at kernel stop */
4823:   cl_mem            o_jacobianInverses, o_jacobianDeterminants;
4824:   cl_mem            o_coefficients, o_coefficientsAux, o_elemVec;
4825:   float            *f_coeff = NULL, *f_coeffAux = NULL, *f_invJ = NULL, *f_detJ = NULL;
4826:   double           *d_coeff = NULL, *d_coeffAux = NULL, *d_invJ = NULL, *d_detJ = NULL;
4827:   PetscReal        *r_invJ = NULL, *r_detJ = NULL;
4828:   void             *oclCoeff, *oclCoeffAux, *oclInvJ, *oclDetJ;
4829:   size_t            local_work_size[3], global_work_size[3];
4830:   size_t            realSize, x, y, z;
4831:   PetscErrorCode    ierr;

4834:   if (!Ne) {PetscFEOpenCLLogResidual(fem, 0.0, 0.0); return(0);}
4835:   PetscFEGetSpatialDimension(fem, &dim);
4836:   PetscFEGetQuadrature(fem, &q);
4837:   PetscFEGetDimension(fem, &N_b);
4838:   PetscFEGetNumComponents(fem, &N_comp);
4839:   PetscDSGetResidual(prob, field, &f0_func, &f1_func);
4840:   PetscFEGetTileSizes(fem, NULL, &N_bl, &N_bc, &N_cb);
4841:   N_bt  = N_b*N_comp;
4842:   N_q   = q->numPoints;
4843:   N_bst = N_bt*N_q;
4844:   N_t   = N_bst*N_bl;
4845:   if (N_bc*N_comp != N_t) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of threads %d should be %d * %d", N_t, N_bc, N_comp);
4846:   /* Calculate layout */
4847:   if (Ne % (N_cb*N_bc)) { /* Remainder cells */
4848:     PetscFEIntegrateResidual_Basic(fem, prob, field, Ne, geom, coefficients, coefficients_t, probAux, coefficientsAux, elemVec);
4849:     return(0);
4850:   }
4851:   PetscFEOpenCLCalculateGrid(fem, Ne, N_cb*N_bc, &x, &y, &z);
4852:   local_work_size[0]  = N_bc*N_comp;
4853:   local_work_size[1]  = 1;
4854:   local_work_size[2]  = 1;
4855:   global_work_size[0] = x * local_work_size[0];
4856:   global_work_size[1] = y * local_work_size[1];
4857:   global_work_size[2] = z * local_work_size[2];
4858:   PetscInfo7(fem, "GPU layout grid(%d,%d,%d) block(%d,%d,%d) with %d batches\n", x, y, z, local_work_size[0], local_work_size[1], local_work_size[2], N_cb);
4859:   PetscInfo2(fem, " N_t: %d, N_cb: %d\n", N_t, N_cb);
4860:   /* Generate code */
4861:   if (probAux) {
4862:     PetscSpace P;
4863:     PetscInt   NfAux, order, f;

4865:     PetscDSGetNumFields(probAux, &NfAux);
4866:     for (f = 0; f < NfAux; ++f) {
4867:       PetscFE feAux;

4869:       PetscDSGetDiscretization(probAux, f, (PetscObject *) &feAux);
4870:       PetscFEGetBasisSpace(feAux, &P);
4871:       PetscSpaceGetOrder(P, &order);
4872:       if (order > 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Can only handle P0 coefficient fields");
4873:     }
4874:   }
4875:   PetscFEOpenCLGetIntegrationKernel(fem, useAux, &ocl_prog, &ocl_kernel);
4876:   /* Create buffers on the device and send data over */
4877:   PetscDataTypeGetSize(ocl->realType, &realSize);
4878:   if (sizeof(PetscReal) != realSize) {
4879:     switch (ocl->realType) {
4880:     case PETSC_FLOAT:
4881:     {
4882:       PetscInt c, b, d;

4884:       PetscMalloc4(Ne*N_bt,&f_coeff,Ne,&f_coeffAux,Ne*dim*dim,&f_invJ,Ne,&f_detJ);
4885:       for (c = 0; c < Ne; ++c) {
4886:         f_detJ[c] = (float) geom[c].detJ;
4887:         for (d = 0; d < dim*dim; ++d) {
4888:           f_invJ[c*dim*dim+d] = (float) geom[c].invJ[d];
4889:         }
4890:         for (b = 0; b < N_bt; ++b) {
4891:           f_coeff[c*N_bt+b] = (float) coefficients[c*N_bt+b];
4892:         }
4893:       }
4894:       if (coefficientsAux) { /* Assume P0 */
4895:         for (c = 0; c < Ne; ++c) {
4896:           f_coeffAux[c] = (float) coefficientsAux[c];
4897:         }
4898:       }
4899:       oclCoeff      = (void *) f_coeff;
4900:       if (coefficientsAux) {
4901:         oclCoeffAux = (void *) f_coeffAux;
4902:       } else {
4903:         oclCoeffAux = NULL;
4904:       }
4905:       oclInvJ       = (void *) f_invJ;
4906:       oclDetJ       = (void *) f_detJ;
4907:     }
4908:     break;
4909:     case PETSC_DOUBLE:
4910:     {
4911:       PetscInt c, b, d;

4913:       PetscMalloc4(Ne*N_bt,&d_coeff,Ne,&d_coeffAux,Ne*dim*dim,&d_invJ,Ne,&d_detJ);
4914:       for (c = 0; c < Ne; ++c) {
4915:         d_detJ[c] = (double) geom[c].detJ;
4916:         for (d = 0; d < dim*dim; ++d) {
4917:           d_invJ[c*dim*dim+d] = (double) geom[c].invJ[d];
4918:         }
4919:         for (b = 0; b < N_bt; ++b) {
4920:           d_coeff[c*N_bt+b] = (double) coefficients[c*N_bt+b];
4921:         }
4922:       }
4923:       if (coefficientsAux) { /* Assume P0 */
4924:         for (c = 0; c < Ne; ++c) {
4925:           d_coeffAux[c] = (double) coefficientsAux[c];
4926:         }
4927:       }
4928:       oclCoeff      = (void *) d_coeff;
4929:       if (coefficientsAux) {
4930:         oclCoeffAux = (void *) d_coeffAux;
4931:       } else {
4932:         oclCoeffAux = NULL;
4933:       }
4934:       oclInvJ       = (void *) d_invJ;
4935:       oclDetJ       = (void *) d_detJ;
4936:     }
4937:     break;
4938:     default:
4939:       SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported PETSc type %d", ocl->realType);
4940:     }
4941:   } else {
4942:     PetscInt c, d;

4944:     PetscMalloc2(Ne*dim*dim,&r_invJ,Ne,&r_detJ);
4945:     for (c = 0; c < Ne; ++c) {
4946:       r_detJ[c] = geom[c].detJ;
4947:       for (d = 0; d < dim*dim; ++d) {
4948:         r_invJ[c*dim*dim+d] = geom[c].invJ[d];
4949:       }
4950:     }
4951:     oclCoeff    = (void *) coefficients;
4952:     oclCoeffAux = (void *) coefficientsAux;
4953:     oclInvJ     = (void *) r_invJ;
4954:     oclDetJ     = (void *) r_detJ;
4955:   }
4956:   o_coefficients         = clCreateBuffer(ocl->ctx_id, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, Ne*N_bt    * realSize, oclCoeff,    &ierr);
4957:   if (coefficientsAux) {
4958:     o_coefficientsAux    = clCreateBuffer(ocl->ctx_id, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, Ne         * realSize, oclCoeffAux, &ierr);
4959:   } else {
4960:     o_coefficientsAux    = clCreateBuffer(ocl->ctx_id, CL_MEM_READ_ONLY,                        Ne         * realSize, oclCoeffAux, &ierr);
4961:   }
4962:   o_jacobianInverses     = clCreateBuffer(ocl->ctx_id, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, Ne*dim*dim * realSize, oclInvJ,     &ierr);
4963:   o_jacobianDeterminants = clCreateBuffer(ocl->ctx_id, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, Ne         * realSize, oclDetJ,     &ierr);
4964:   o_elemVec              = clCreateBuffer(ocl->ctx_id, CL_MEM_WRITE_ONLY,                       Ne*N_bt    * realSize, NULL,        &ierr);
4965:   /* Kernel launch */
4966:   clSetKernelArg(ocl_kernel, 0, sizeof(cl_int), (void*) &N_cb);
4967:   clSetKernelArg(ocl_kernel, 1, sizeof(cl_mem), (void*) &o_coefficients);
4968:   clSetKernelArg(ocl_kernel, 2, sizeof(cl_mem), (void*) &o_coefficientsAux);
4969:   clSetKernelArg(ocl_kernel, 3, sizeof(cl_mem), (void*) &o_jacobianInverses);
4970:   clSetKernelArg(ocl_kernel, 4, sizeof(cl_mem), (void*) &o_jacobianDeterminants);
4971:   clSetKernelArg(ocl_kernel, 5, sizeof(cl_mem), (void*) &o_elemVec);
4972:   clEnqueueNDRangeKernel(ocl->queue_id, ocl_kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &ocl_ev);
4973:   /* Read data back from device */
4974:   if (sizeof(PetscReal) != realSize) {
4975:     switch (ocl->realType) {
4976:     case PETSC_FLOAT:
4977:     {
4978:       float   *elem;
4979:       PetscInt c, b;

4981:       PetscFree4(f_coeff,f_coeffAux,f_invJ,f_detJ);
4982:       PetscMalloc1(Ne*N_bt, &elem);
4983:       clEnqueueReadBuffer(ocl->queue_id, o_elemVec, CL_TRUE, 0, Ne*N_bt * realSize, elem, 0, NULL, NULL);
4984:       for (c = 0; c < Ne; ++c) {
4985:         for (b = 0; b < N_bt; ++b) {
4986:           elemVec[c*N_bt+b] = (PetscScalar) elem[c*N_bt+b];
4987:         }
4988:       }
4989:       PetscFree(elem);
4990:     }
4991:     break;
4992:     case PETSC_DOUBLE:
4993:     {
4994:       double  *elem;
4995:       PetscInt c, b;

4997:       PetscFree4(d_coeff,d_coeffAux,d_invJ,d_detJ);
4998:       PetscMalloc1(Ne*N_bt, &elem);
4999:       clEnqueueReadBuffer(ocl->queue_id, o_elemVec, CL_TRUE, 0, Ne*N_bt * realSize, elem, 0, NULL, NULL);
5000:       for (c = 0; c < Ne; ++c) {
5001:         for (b = 0; b < N_bt; ++b) {
5002:           elemVec[c*N_bt+b] = (PetscScalar) elem[c*N_bt+b];
5003:         }
5004:       }
5005:       PetscFree(elem);
5006:     }
5007:     break;
5008:     default:
5009:       SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unsupported PETSc type %d", ocl->realType);
5010:     }
5011:   } else {
5012:     PetscFree2(r_invJ,r_detJ);
5013:     clEnqueueReadBuffer(ocl->queue_id, o_elemVec, CL_TRUE, 0, Ne*N_bt * realSize, elemVec, 0, NULL, NULL);
5014:   }
5015:   /* Log performance */
5016:   clGetEventProfilingInfo(ocl_ev, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ns_start, NULL);
5017:   clGetEventProfilingInfo(ocl_ev, CL_PROFILING_COMMAND_END,   sizeof(cl_ulong), &ns_end,   NULL);
5018:   f0Flops = 0;
5019:   switch (ocl->op) {
5020:   case LAPLACIAN:
5021:     f1Flops = useAux ? dim : 0;break;
5022:   case ELASTICITY:
5023:     f1Flops = 2*dim*dim;break;
5024:   }
5025:   numFlops = Ne*(
5026:     N_q*(
5027:       N_b*N_comp*((useField ? 2 : 0) + (useFieldDer ? 2*dim*(dim + 1) : 0))
5028:       /*+
5029:        N_ba*N_compa*((useFieldAux ? 2 : 0) + (useFieldDerAux ? 2*dim*(dim + 1) : 0))*/
5030:       +
5031:       N_comp*((useF0 ? f0Flops + 2 : 0) + (useF1 ? f1Flops + 2*dim : 0)))
5032:     +
5033:     N_b*((useF0 ? 2 : 0) + (useF1 ? 2*dim*(dim + 1) : 0)));
5034:   PetscFEOpenCLLogResidual(fem, (ns_end - ns_start)*1.0e-9, numFlops);
5035:   /* Cleanup */
5036:   clReleaseMemObject(o_coefficients);
5037:   clReleaseMemObject(o_coefficientsAux);
5038:   clReleaseMemObject(o_jacobianInverses);
5039:   clReleaseMemObject(o_jacobianDeterminants);
5040:   clReleaseMemObject(o_elemVec);
5041:   clReleaseKernel(ocl_kernel);
5042:   clReleaseProgram(ocl_prog);
5043:   return(0);
5044: }

5048: PetscErrorCode PetscFEInitialize_OpenCL(PetscFE fem)
5049: {
5051:   fem->ops->setfromoptions          = NULL;
5052:   fem->ops->setup                   = PetscFESetUp_Basic;
5053:   fem->ops->view                    = NULL;
5054:   fem->ops->destroy                 = PetscFEDestroy_OpenCL;
5055:   fem->ops->getdimension            = PetscFEGetDimension_Basic;
5056:   fem->ops->gettabulation           = PetscFEGetTabulation_Basic;
5057:   fem->ops->integrateresidual       = PetscFEIntegrateResidual_OpenCL;
5058:   fem->ops->integratebdresidual     = NULL/* PetscFEIntegrateBdResidual_OpenCL */;
5059:   fem->ops->integratejacobianaction = NULL/* PetscFEIntegrateJacobianAction_OpenCL */;
5060:   fem->ops->integratejacobian       = PetscFEIntegrateJacobian_Basic;
5061:   return(0);
5062: }

5064: /*MC
5065:   PETSCFEOPENCL = "opencl" - A PetscFE object that integrates using a vectorized OpenCL implementation

5067:   Level: intermediate

5069: .seealso: PetscFEType, PetscFECreate(), PetscFESetType()
5070: M*/

5074: PETSC_EXTERN PetscErrorCode PetscFECreate_OpenCL(PetscFE fem)
5075: {
5076:   PetscFE_OpenCL *ocl;
5077:   cl_uint         num_platforms;
5078:   cl_platform_id  platform_ids[42];
5079:   cl_uint         num_devices;
5080:   cl_device_id    device_ids[42];
5081:   cl_int          ierr2;
5082:   PetscErrorCode  ierr;

5086:   PetscNewLog(fem,&ocl);
5087:   fem->data = ocl;

5089:   /* Init Platform */
5090:   clGetPlatformIDs(42, platform_ids, &num_platforms);
5091:   if (!num_platforms) SETERRQ(PetscObjectComm((PetscObject) fem), PETSC_ERR_SUP, "No OpenCL platform found.");
5092:   ocl->pf_id = platform_ids[0];
5093:   /* Init Device */
5094:   clGetDeviceIDs(ocl->pf_id, CL_DEVICE_TYPE_ALL, 42, device_ids, &num_devices);
5095:   if (!num_devices) SETERRQ(PetscObjectComm((PetscObject) fem), PETSC_ERR_SUP, "No OpenCL device found.");
5096:   ocl->dev_id = device_ids[0];
5097:   /* Create context with one command queue */
5098:   ocl->ctx_id   = clCreateContext(0, 1, &(ocl->dev_id), NULL, NULL, &ierr2);CHKERRQ(ierr2);
5099:   ocl->queue_id = clCreateCommandQueue(ocl->ctx_id, ocl->dev_id, CL_QUEUE_PROFILING_ENABLE, &ierr2);CHKERRQ(ierr2);
5100:   /* Types */
5101:   ocl->realType = PETSC_FLOAT;
5102:   /* Register events */
5103:   PetscLogEventRegister("OpenCL FEResidual", PETSCFE_CLASSID, &ocl->residualEvent);
5104:   /* Equation handling */
5105:   ocl->op = LAPLACIAN;

5107:   PetscFEInitialize_OpenCL(fem);
5108:   return(0);
5109: }

5113: PetscErrorCode PetscFEOpenCLSetRealType(PetscFE fem, PetscDataType realType)
5114: {
5115:   PetscFE_OpenCL *ocl = (PetscFE_OpenCL *) fem->data;

5119:   ocl->realType = realType;
5120:   return(0);
5121: }

5125: PetscErrorCode PetscFEOpenCLGetRealType(PetscFE fem, PetscDataType *realType)
5126: {
5127:   PetscFE_OpenCL *ocl = (PetscFE_OpenCL *) fem->data;

5132:   *realType = ocl->realType;
5133:   return(0);
5134: }

5136: #endif /* PETSC_HAVE_OPENCL */

5140: PetscErrorCode PetscFEDestroy_Composite(PetscFE fem)
5141: {
5142:   PetscFE_Composite *cmp = (PetscFE_Composite *) fem->data;
5143:   PetscErrorCode     ierr;

5146:   CellRefinerRestoreAffineTransforms_Internal(cmp->cellRefiner, &cmp->numSubelements, &cmp->v0, &cmp->jac, &cmp->invjac);
5147:   PetscFree(cmp->embedding);
5148:   PetscFree(cmp);
5149:   return(0);
5150: }

5154: PetscErrorCode PetscFESetUp_Composite(PetscFE fem)
5155: {
5156:   PetscFE_Composite *cmp = (PetscFE_Composite *) fem->data;
5157:   DM                 K;
5158:   PetscReal         *subpoint;
5159:   PetscBLASInt      *pivots;
5160:   PetscBLASInt       n, info;
5161:   PetscScalar       *work, *invVscalar;
5162:   PetscInt           dim, pdim, spdim, j, s;
5163:   PetscErrorCode     ierr;

5166:   /* Get affine mapping from reference cell to each subcell */
5167:   PetscDualSpaceGetDM(fem->dualSpace, &K);
5168:   DMGetDimension(K, &dim);
5169:   DMPlexGetCellRefiner_Internal(K, &cmp->cellRefiner);
5170:   CellRefinerGetAffineTransforms_Internal(cmp->cellRefiner, &cmp->numSubelements, &cmp->v0, &cmp->jac, &cmp->invjac);
5171:   /* Determine dof embedding into subelements */
5172:   PetscDualSpaceGetDimension(fem->dualSpace, &pdim);
5173:   PetscSpaceGetDimension(fem->basisSpace, &spdim);
5174:   PetscMalloc1(cmp->numSubelements*spdim,&cmp->embedding);
5175:   DMGetWorkArray(K, dim, PETSC_REAL, &subpoint);
5176:   for (s = 0; s < cmp->numSubelements; ++s) {
5177:     PetscInt sd = 0;

5179:     for (j = 0; j < pdim; ++j) {
5180:       PetscBool       inside;
5181:       PetscQuadrature f;
5182:       PetscInt        d, e;

5184:       PetscDualSpaceGetFunctional(fem->dualSpace, j, &f);
5185:       /* Apply transform to first point, and check that point is inside subcell */
5186:       for (d = 0; d < dim; ++d) {
5187:         subpoint[d] = -1.0;
5188:         for (e = 0; e < dim; ++e) subpoint[d] += cmp->invjac[(s*dim + d)*dim+e]*(f->points[e] - cmp->v0[s*dim+e]);
5189:       }
5190:       CellRefinerInCellTest_Internal(cmp->cellRefiner, subpoint, &inside);
5191:       if (inside) {cmp->embedding[s*spdim+sd++] = j;}
5192:     }
5193:     if (sd != spdim) SETERRQ3(PetscObjectComm((PetscObject) fem), PETSC_ERR_PLIB, "Subelement %d has %d dual basis vectors != %d", s, sd, spdim);
5194:   }
5195:   DMRestoreWorkArray(K, dim, PETSC_REAL, &subpoint);
5196:   /* Construct the change of basis from prime basis to nodal basis for each subelement */
5197:   PetscMalloc1(cmp->numSubelements*spdim*spdim,&fem->invV);
5198:   PetscMalloc2(spdim,&pivots,spdim,&work);
5199: #if defined(PETSC_USE_COMPLEX)
5200:   PetscMalloc1(cmp->numSubelements*spdim*spdim,&invVscalar);
5201: #else
5202:   invVscalar = fem->invV;
5203: #endif
5204:   for (s = 0; s < cmp->numSubelements; ++s) {
5205:     for (j = 0; j < spdim; ++j) {
5206:       PetscReal      *Bf;
5207:       PetscQuadrature f;
5208:       PetscInt        q, k;

5210:       PetscDualSpaceGetFunctional(fem->dualSpace, cmp->embedding[s*spdim+j], &f);
5211:       PetscMalloc1(f->numPoints*spdim,&Bf);
5212:       PetscSpaceEvaluate(fem->basisSpace, f->numPoints, f->points, Bf, NULL, NULL);
5213:       for (k = 0; k < spdim; ++k) {
5214:         /* n_j \cdot \phi_k */
5215:         invVscalar[(s*spdim + j)*spdim+k] = 0.0;
5216:         for (q = 0; q < f->numPoints; ++q) {
5217:           invVscalar[(s*spdim + j)*spdim+k] += Bf[q*spdim+k]*f->weights[q];
5218:         }
5219:       }
5220:       PetscFree(Bf);
5221:     }
5222:     n = spdim;
5223:     PetscStackCallBLAS("LAPACKgetrf", LAPACKgetrf_(&n, &n, &invVscalar[s*spdim*spdim], &n, pivots, &info));
5224:     PetscStackCallBLAS("LAPACKgetri", LAPACKgetri_(&n, &invVscalar[s*spdim*spdim], &n, pivots, work, &n, &info));
5225:   }
5226: #if defined(PETSC_USE_COMPLEX)
5227:   for (s = 0; s <cmp->numSubelements*spdim*spdim; s++) fem->invV[s] = PetscRealPart(invVscalar[s]);
5228:   PetscFree(invVscalar);
5229: #endif
5230:   PetscFree2(pivots,work);
5231:   return(0);
5232: }

5236: PetscErrorCode PetscFEGetTabulation_Composite(PetscFE fem, PetscInt npoints, const PetscReal points[], PetscReal *B, PetscReal *D, PetscReal *H)
5237: {
5238:   PetscFE_Composite *cmp = (PetscFE_Composite *) fem->data;
5239:   DM                 dm;
5240:   PetscInt           pdim;  /* Dimension of FE space P */
5241:   PetscInt           spdim; /* Dimension of subelement FE space P */
5242:   PetscInt           dim;   /* Spatial dimension */
5243:   PetscInt           comp;  /* Field components */
5244:   PetscInt          *subpoints;
5245:   PetscReal         *tmpB, *tmpD, *tmpH, *subpoint;
5246:   PetscInt           p, s, d, e, j, k;
5247:   PetscErrorCode     ierr;

5250:   PetscDualSpaceGetDM(fem->dualSpace, &dm);
5251:   DMGetDimension(dm, &dim);
5252:   PetscSpaceGetDimension(fem->basisSpace, &spdim);
5253:   PetscDualSpaceGetDimension(fem->dualSpace, &pdim);
5254:   PetscFEGetNumComponents(fem, &comp);
5255:   /* Divide points into subelements */
5256:   DMGetWorkArray(dm, npoints, PETSC_INT, &subpoints);
5257:   DMGetWorkArray(dm, dim, PETSC_REAL, &subpoint);
5258:   for (p = 0; p < npoints; ++p) {
5259:     for (s = 0; s < cmp->numSubelements; ++s) {
5260:       PetscBool inside;

5262:       /* Apply transform, and check that point is inside cell */
5263:       for (d = 0; d < dim; ++d) {
5264:         subpoint[d] = -1.0;
5265:         for (e = 0; e < dim; ++e) subpoint[d] += cmp->invjac[(s*dim + d)*dim+e]*(points[p*dim+e] - cmp->v0[s*dim+e]);
5266:       }
5267:       CellRefinerInCellTest_Internal(cmp->cellRefiner, subpoint, &inside);
5268:       if (inside) {subpoints[p] = s; break;}
5269:     }
5270:     if (s >= cmp->numSubelements) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Point %d was not found in any subelement", p);
5271:   }
5272:   DMRestoreWorkArray(dm, dim, PETSC_REAL, &subpoint);
5273:   /* Evaluate the prime basis functions at all points */
5274:   if (B) {DMGetWorkArray(dm, npoints*spdim, PETSC_REAL, &tmpB);}
5275:   if (D) {DMGetWorkArray(dm, npoints*spdim*dim, PETSC_REAL, &tmpD);}
5276:   if (H) {DMGetWorkArray(dm, npoints*spdim*dim*dim, PETSC_REAL, &tmpH);}
5277:   PetscSpaceEvaluate(fem->basisSpace, npoints, points, B ? tmpB : NULL, D ? tmpD : NULL, H ? tmpH : NULL);
5278:   /* Translate to the nodal basis */
5279:   if (B) {PetscMemzero(B, npoints*pdim*comp * sizeof(PetscReal));}
5280:   if (D) {PetscMemzero(D, npoints*pdim*comp*dim * sizeof(PetscReal));}
5281:   if (H) {PetscMemzero(H, npoints*pdim*comp*dim*dim * sizeof(PetscReal));}
5282:   for (p = 0; p < npoints; ++p) {
5283:     const PetscInt s = subpoints[p];

5285:     if (B) {
5286:       /* Multiply by V^{-1} (spdim x spdim) */
5287:       for (j = 0; j < spdim; ++j) {
5288:         const PetscInt i = (p*pdim + cmp->embedding[s*spdim+j])*comp;
5289:         PetscInt       c;

5291:         B[i] = 0.0;
5292:         for (k = 0; k < spdim; ++k) {
5293:           B[i] += fem->invV[(s*spdim + k)*spdim+j] * tmpB[p*spdim + k];
5294:         }
5295:         for (c = 1; c < comp; ++c) {
5296:           B[i+c] = B[i];
5297:         }
5298:       }
5299:     }
5300:     if (D) {
5301:       /* Multiply by V^{-1} (spdim x spdim) */
5302:       for (j = 0; j < spdim; ++j) {
5303:         for (d = 0; d < dim; ++d) {
5304:           const PetscInt i = ((p*pdim + cmp->embedding[s*spdim+j])*comp + 0)*dim + d;
5305:           PetscInt       c;

5307:           D[i] = 0.0;
5308:           for (k = 0; k < spdim; ++k) {
5309:             D[i] += fem->invV[(s*spdim + k)*spdim+j] * tmpD[(p*spdim + k)*dim + d];
5310:           }
5311:           for (c = 1; c < comp; ++c) {
5312:             D[((p*pdim + cmp->embedding[s*spdim+j])*comp + c)*dim + d] = D[i];
5313:           }
5314:         }
5315:       }
5316:     }
5317:     if (H) {
5318:       /* Multiply by V^{-1} (pdim x pdim) */
5319:       for (j = 0; j < spdim; ++j) {
5320:         for (d = 0; d < dim*dim; ++d) {
5321:           const PetscInt i = ((p*pdim + cmp->embedding[s*spdim+j])*comp + 0)*dim*dim + d;
5322:           PetscInt       c;

5324:           H[i] = 0.0;
5325:           for (k = 0; k < spdim; ++k) {
5326:             H[i] += fem->invV[(s*spdim + k)*spdim+j] * tmpH[(p*spdim + k)*dim*dim + d];
5327:           }
5328:           for (c = 1; c < comp; ++c) {
5329:             H[((p*pdim + cmp->embedding[s*spdim+j])*comp + c)*dim*dim + d] = H[i];
5330:           }
5331:         }
5332:       }
5333:     }
5334:   }
5335:   DMRestoreWorkArray(dm, npoints, PETSC_INT, &subpoints);
5336:   if (B) {DMRestoreWorkArray(dm, npoints*spdim, PETSC_REAL, &tmpB);}
5337:   if (D) {DMRestoreWorkArray(dm, npoints*spdim*dim, PETSC_REAL, &tmpD);}
5338:   if (H) {DMRestoreWorkArray(dm, npoints*spdim*dim*dim, PETSC_REAL, &tmpH);}
5339:   return(0);
5340: }

5344: PetscErrorCode PetscFEInitialize_Composite(PetscFE fem)
5345: {
5347:   fem->ops->setfromoptions          = NULL;
5348:   fem->ops->setup                   = PetscFESetUp_Composite;
5349:   fem->ops->view                    = NULL;
5350:   fem->ops->destroy                 = PetscFEDestroy_Composite;
5351:   fem->ops->getdimension            = PetscFEGetDimension_Basic;
5352:   fem->ops->gettabulation           = PetscFEGetTabulation_Composite;
5353:   fem->ops->integrateresidual       = PetscFEIntegrateResidual_Basic;
5354:   fem->ops->integratebdresidual     = PetscFEIntegrateBdResidual_Basic;
5355:   fem->ops->integratejacobianaction = NULL/* PetscFEIntegrateJacobianAction_Basic */;
5356:   fem->ops->integratejacobian       = PetscFEIntegrateJacobian_Basic;
5357:   return(0);
5358: }

5360: /*MC
5361:   PETSCFECOMPOSITE = "composite" - A PetscFE object that represents a composite element

5363:   Level: intermediate

5365: .seealso: PetscFEType, PetscFECreate(), PetscFESetType()
5366: M*/

5370: PETSC_EXTERN PetscErrorCode PetscFECreate_Composite(PetscFE fem)
5371: {
5372:   PetscFE_Composite *cmp;
5373:   PetscErrorCode     ierr;

5377:   PetscNewLog(fem, &cmp);
5378:   fem->data = cmp;

5380:   cmp->cellRefiner    = REFINER_NOOP;
5381:   cmp->numSubelements = -1;
5382:   cmp->v0             = NULL;
5383:   cmp->jac            = NULL;

5385:   PetscFEInitialize_Composite(fem);
5386:   return(0);
5387: }

5391: /*@C
5392:   PetscFECompositeGetMapping - Returns the mappings from the reference element to each subelement

5394:   Not collective

5396:   Input Parameter:
5397: . fem - The PetscFE object

5399:   Output Parameters:
5400: + blockSize - The number of elements in a block
5401: . numBlocks - The number of blocks in a batch
5402: . batchSize - The number of elements in a batch
5403: - numBatches - The number of batches in a chunk

5405:   Level: intermediate

5407: .seealso: PetscFECreate()
5408: @*/
5409: PetscErrorCode PetscFECompositeGetMapping(PetscFE fem, PetscInt *numSubelements, const PetscReal *v0[], const PetscReal *jac[], const PetscReal *invjac[])
5410: {
5411:   PetscFE_Composite *cmp = (PetscFE_Composite *) fem->data;

5419:   return(0);
5420: }

5424: /*@
5425:   PetscFEGetDimension - Get the dimension of the finite element space on a cell

5427:   Not collective

5429:   Input Parameter:
5430: . fe - The PetscFE

5432:   Output Parameter:
5433: . dim - The dimension

5435:   Level: intermediate

5437: .seealso: PetscFECreate(), PetscSpaceGetDimension(), PetscDualSpaceGetDimension()
5438: @*/
5439: PetscErrorCode PetscFEGetDimension(PetscFE fem, PetscInt *dim)
5440: {

5446:   if (fem->ops->getdimension) {(*fem->ops->getdimension)(fem, dim);}
5447:   return(0);
5448: }

5450: /*
5451: Purpose: Compute element vector for chunk of elements

5453: Input:
5454:   Sizes:
5455:      Ne:  number of elements
5456:      Nf:  number of fields
5457:      PetscFE
5458:        dim: spatial dimension
5459:        Nb:  number of basis functions
5460:        Nc:  number of field components
5461:        PetscQuadrature
5462:          Nq:  number of quadrature points

5464:   Geometry:
5465:      PetscFECellGeom[Ne] possibly *Nq
5466:        PetscReal v0s[dim]
5467:        PetscReal n[dim]
5468:        PetscReal jacobians[dim*dim]
5469:        PetscReal jacobianInverses[dim*dim]
5470:        PetscReal jacobianDeterminants
5471:   FEM:
5472:      PetscFE
5473:        PetscQuadrature
5474:          PetscReal   quadPoints[Nq*dim]
5475:          PetscReal   quadWeights[Nq]
5476:        PetscReal   basis[Nq*Nb*Nc]
5477:        PetscReal   basisDer[Nq*Nb*Nc*dim]
5478:      PetscScalar coefficients[Ne*Nb*Nc]
5479:      PetscScalar elemVec[Ne*Nb*Nc]

5481:   Problem:
5482:      PetscInt f: the active field
5483:      f0, f1

5485:   Work Space:
5486:      PetscFE
5487:        PetscScalar f0[Nq*dim];
5488:        PetscScalar f1[Nq*dim*dim];
5489:        PetscScalar u[Nc];
5490:        PetscScalar gradU[Nc*dim];
5491:        PetscReal   x[dim];
5492:        PetscScalar realSpaceDer[dim];

5494: Purpose: Compute element vector for N_cb batches of elements

5496: Input:
5497:   Sizes:
5498:      N_cb: Number of serial cell batches

5500:   Geometry:
5501:      PetscReal v0s[Ne*dim]
5502:      PetscReal jacobians[Ne*dim*dim]        possibly *Nq
5503:      PetscReal jacobianInverses[Ne*dim*dim] possibly *Nq
5504:      PetscReal jacobianDeterminants[Ne]     possibly *Nq
5505:   FEM:
5506:      static PetscReal   quadPoints[Nq*dim]
5507:      static PetscReal   quadWeights[Nq]
5508:      static PetscReal   basis[Nq*Nb*Nc]
5509:      static PetscReal   basisDer[Nq*Nb*Nc*dim]
5510:      PetscScalar coefficients[Ne*Nb*Nc]
5511:      PetscScalar elemVec[Ne*Nb*Nc]

5513: ex62.c:
5514:   PetscErrorCode PetscFEIntegrateResidualBatch(PetscInt Ne, PetscInt numFields, PetscInt field, PetscQuadrature quad[], const PetscScalar coefficients[],
5515:                                                const PetscReal v0s[], const PetscReal jacobians[], const PetscReal jacobianInverses[], const PetscReal jacobianDeterminants[],
5516:                                                void (*f0_func)(const PetscScalar u[], const PetscScalar gradU[], const PetscReal x[], PetscScalar f0[]),
5517:                                                void (*f1_func)(const PetscScalar u[], const PetscScalar gradU[], const PetscReal x[], PetscScalar f1[]), PetscScalar elemVec[])

5519: ex52.c:
5520:   PetscErrorCode IntegrateLaplacianBatchCPU(PetscInt Ne, PetscInt Nb, const PetscScalar coefficients[], const PetscReal jacobianInverses[], const PetscReal jacobianDeterminants[], PetscInt Nq, const PetscReal quadPoints[], const PetscReal quadWeights[], const PetscReal basisTabulation[], const PetscReal basisDerTabulation[], PetscScalar elemVec[], AppCtx *user)
5521:   PetscErrorCode IntegrateElasticityBatchCPU(PetscInt Ne, PetscInt Nb, PetscInt Ncomp, const PetscScalar coefficients[], const PetscReal jacobianInverses[], const PetscReal jacobianDeterminants[], PetscInt Nq, const PetscReal quadPoints[], const PetscReal quadWeights[], const PetscReal basisTabulation[], const PetscReal basisDerTabulation[], PetscScalar elemVec[], AppCtx *user)

5523: ex52_integrateElement.cu
5524: __global__ void integrateElementQuadrature(int N_cb, realType *coefficients, realType *jacobianInverses, realType *jacobianDeterminants, realType *elemVec)

5526: PETSC_EXTERN PetscErrorCode IntegrateElementBatchGPU(PetscInt spatial_dim, PetscInt Ne, PetscInt Ncb, PetscInt Nbc, PetscInt Nbl, const PetscScalar coefficients[],
5527:                                                      const PetscReal jacobianInverses[], const PetscReal jacobianDeterminants[], PetscScalar elemVec[],
5528:                                                      PetscLogEvent event, PetscInt debug, PetscInt pde_op)

5530: ex52_integrateElementOpenCL.c:
5531: PETSC_EXTERN PetscErrorCode IntegrateElementBatchGPU(PetscInt spatial_dim, PetscInt Ne, PetscInt Ncb, PetscInt Nbc, PetscInt N_bl, const PetscScalar coefficients[],
5532:                                                      const PetscReal jacobianInverses[], const PetscReal jacobianDeterminants[], PetscScalar elemVec[],
5533:                                                      PetscLogEvent event, PetscInt debug, PetscInt pde_op)

5535: __kernel void integrateElementQuadrature(int N_cb, __global float *coefficients, __global float *jacobianInverses, __global float *jacobianDeterminants, __global float *elemVec)
5536: */

5540: /*@C
5541:   PetscFEIntegrate - Produce the integral for the given field for a chunk of elements by quadrature integration

5543:   Not collective

5545:   Input Parameters:
5546: + fem          - The PetscFE object for the field being integrated
5547: . prob         - The PetscDS specifing the discretizations and continuum functions
5548: . field        - The field being integrated
5549: . Ne           - The number of elements in the chunk
5550: . geom         - The cell geometry for each cell in the chunk
5551: . coefficients - The array of FEM basis coefficients for the elements
5552: . probAux      - The PetscDS specifing the auxiliary discretizations
5553: - coefficientsAux - The array of FEM auxiliary basis coefficients for the elements

5555:   Output Parameter
5556: . integral     - the integral for this field

5558:   Level: developer

5560: .seealso: PetscFEIntegrateResidual()
5561: @*/
5562: PetscErrorCode PetscFEIntegrate(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
5563:                                 const PetscScalar coefficients[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscReal integral[])
5564: {

5570:   if (fem->ops->integrate) {(*fem->ops->integrate)(fem, prob, field, Ne, geom, coefficients, probAux, coefficientsAux, integral);}
5571:   return(0);
5572: }

5576: /*@C
5577:   PetscFEIntegrateResidual - Produce the element residual vector for a chunk of elements by quadrature integration

5579:   Not collective

5581:   Input Parameters:
5582: + fem          - The PetscFE object for the field being integrated
5583: . prob         - The PetscDS specifing the discretizations and continuum functions
5584: . field        - The field being integrated
5585: . Ne           - The number of elements in the chunk
5586: . geom         - The cell geometry for each cell in the chunk
5587: . coefficients - The array of FEM basis coefficients for the elements
5588: . coefficients_t - The array of FEM basis time derivative coefficients for the elements
5589: . probAux      - The PetscDS specifing the auxiliary discretizations
5590: - coefficientsAux - The array of FEM auxiliary basis coefficients for the elements

5592:   Output Parameter
5593: . elemVec      - the element residual vectors from each element

5595:   Note:
5596: $ Loop over batch of elements (e):
5597: $   Loop over quadrature points (q):
5598: $     Make u_q and gradU_q (loops over fields,Nb,Ncomp) and x_q
5599: $     Call f_0 and f_1
5600: $   Loop over element vector entries (f,fc --> i):
5601: $     elemVec[i] += \psi^{fc}_f(q) f0_{fc}(u, \nabla u) + \nabla\psi^{fc}_f(q) \cdot f1_{fc,df}(u, \nabla u)

5603:   Level: developer

5605: .seealso: PetscFEIntegrateResidual()
5606: @*/
5607: PetscErrorCode PetscFEIntegrateResidual(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
5608:                                         const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
5609: {

5615:   if (fem->ops->integrateresidual) {(*fem->ops->integrateresidual)(fem, prob, field, Ne, geom, coefficients, coefficients_t, probAux, coefficientsAux, elemVec);}
5616:   return(0);
5617: }

5621: /*@C
5622:   PetscFEIntegrateBdResidual - Produce the element residual vector for a chunk of elements by quadrature integration over a boundary

5624:   Not collective

5626:   Input Parameters:
5627: + fem          - The PetscFE object for the field being integrated
5628: . prob         - The PetscDS specifing the discretizations and continuum functions
5629: . field        - The field being integrated
5630: . Ne           - The number of elements in the chunk
5631: . geom         - The cell geometry for each cell in the chunk
5632: . coefficients - The array of FEM basis coefficients for the elements
5633: . coefficients_t - The array of FEM basis time derivative coefficients for the elements
5634: . probAux      - The PetscDS specifing the auxiliary discretizations
5635: - coefficientsAux - The array of FEM auxiliary basis coefficients for the elements

5637:   Output Parameter
5638: . elemVec      - the element residual vectors from each element

5640:   Level: developer

5642: .seealso: PetscFEIntegrateResidual()
5643: @*/
5644: PetscErrorCode PetscFEIntegrateBdResidual(PetscFE fem, PetscDS prob, PetscInt field, PetscInt Ne, PetscFECellGeom *geom,
5645:                                           const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemVec[])
5646: {

5651:   if (fem->ops->integratebdresidual) {(*fem->ops->integratebdresidual)(fem, prob, field, Ne, geom, coefficients, coefficients_t, probAux, coefficientsAux, elemVec);}
5652:   return(0);
5653: }

5657: /*@C
5658:   PetscFEIntegrateJacobian - Produce the element Jacobian for a chunk of elements by quadrature integration

5660:   Not collective

5662:   Input Parameters:
5663: + fem          - The PetscFE object for the field being integrated
5664: . prob         - The PetscDS specifing the discretizations and continuum functions
5665: . isPrec       - The flag indicating the preconditioner matrix pointwise functions should be used instead
5666: . fieldI       - The test field being integrated
5667: . fieldJ       - The basis field being integrated
5668: . Ne           - The number of elements in the chunk
5669: . geom         - The cell geometry for each cell in the chunk
5670: . coefficients - The array of FEM basis coefficients for the elements for the Jacobian evaluation point
5671: . coefficients_t - The array of FEM basis time derivative coefficients for the elements
5672: . probAux      - The PetscDS specifing the auxiliary discretizations
5673: - coefficientsAux - The array of FEM auxiliary basis coefficients for the elements

5675:   Output Parameter
5676: . elemMat      - the element matrices for the Jacobian from each element

5678:   Note:
5679: $ Loop over batch of elements (e):
5680: $   Loop over element matrix entries (f,fc,g,gc --> i,j):
5681: $     Loop over quadrature points (q):
5682: $       Make u_q and gradU_q (loops over fields,Nb,Ncomp)
5683: $         elemMat[i,j] += \psi^{fc}_f(q) g0_{fc,gc}(u, \nabla u) \phi^{gc}_g(q)
5684: $                      + \psi^{fc}_f(q) \cdot g1_{fc,gc,dg}(u, \nabla u) \nabla\phi^{gc}_g(q)
5685: $                      + \nabla\psi^{fc}_f(q) \cdot g2_{fc,gc,df}(u, \nabla u) \phi^{gc}_g(q)
5686: $                      + \nabla\psi^{fc}_f(q) \cdot g3_{fc,gc,df,dg}(u, \nabla u) \nabla\phi^{gc}_g(q)
5687: */
5688: PetscErrorCode PetscFEIntegrateJacobian(PetscFE fem, PetscDS prob, PetscBool isPrec, PetscInt fieldI, PetscInt fieldJ, PetscInt Ne, PetscFECellGeom *geom,
5689:                                         const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemMat[])
5690: {

5695:   if (fem->ops->integratejacobian) {(*fem->ops->integratejacobian)(fem, prob, isPrec, fieldI, fieldJ, Ne, geom, coefficients, coefficients_t, probAux, coefficientsAux, elemMat);}
5696:   return(0);
5697: }

5701: /*C
5702:   PetscFEIntegrateBdJacobian - Produce the boundary element Jacobian for a chunk of elements by quadrature integration

5704:   Not collective

5706:   Input Parameters:
5707: + fem          = The PetscFE object for the field being integrated
5708: . prob         - The PetscDS specifing the discretizations and continuum functions
5709: . fieldI       - The test field being integrated
5710: . fieldJ       - The basis field being integrated
5711: . Ne           - The number of elements in the chunk
5712: . geom         - The cell geometry for each cell in the chunk
5713: . coefficients - The array of FEM basis coefficients for the elements for the Jacobian evaluation point
5714: . coefficients_t - The array of FEM basis time derivative coefficients for the elements
5715: . probAux      - The PetscDS specifing the auxiliary discretizations
5716: - coefficientsAux - The array of FEM auxiliary basis coefficients for the elements

5718:   Output Parameter
5719: . elemMat              - the element matrices for the Jacobian from each element

5721:   Note:
5722: $ Loop over batch of elements (e):
5723: $   Loop over element matrix entries (f,fc,g,gc --> i,j):
5724: $     Loop over quadrature points (q):
5725: $       Make u_q and gradU_q (loops over fields,Nb,Ncomp)
5726: $         elemMat[i,j] += \psi^{fc}_f(q) g0_{fc,gc}(u, \nabla u) \phi^{gc}_g(q)
5727: $                      + \psi^{fc}_f(q) \cdot g1_{fc,gc,dg}(u, \nabla u) \nabla\phi^{gc}_g(q)
5728: $                      + \nabla\psi^{fc}_f(q) \cdot g2_{fc,gc,df}(u, \nabla u) \phi^{gc}_g(q)
5729: $                      + \nabla\psi^{fc}_f(q) \cdot g3_{fc,gc,df,dg}(u, \nabla u) \nabla\phi^{gc}_g(q)
5730: */
5731: PetscErrorCode PetscFEIntegrateBdJacobian(PetscFE fem, PetscDS prob, PetscInt fieldI, PetscInt fieldJ, PetscInt Ne, PetscFECellGeom *geom,
5732:                                           const PetscScalar coefficients[], const PetscScalar coefficients_t[], PetscDS probAux, const PetscScalar coefficientsAux[], PetscScalar elemMat[])
5733: {

5738:   if (fem->ops->integratebdjacobian) {(*fem->ops->integratebdjacobian)(fem, prob, fieldI, fieldJ, Ne, geom, coefficients, coefficients_t, probAux, coefficientsAux, elemMat);}
5739:   return(0);
5740: }

5744: /*@
5745:   PetscFERefine - Create a "refined" PetscFE object that refines the reference cell into smaller copies. This is typically used
5746:   to precondition a higher order method with a lower order method on a refined mesh having the same number of dofs (but more
5747:   sparsity). It is also used to create an interpolation between regularly refined meshes.

5749:   Input Parameter:
5750: . fe - The initial PetscFE

5752:   Output Parameter:
5753: . feRef - The refined PetscFE

5755:   Level: developer

5757: .seealso: PetscFEType, PetscFECreate(), PetscFESetType()
5758: @*/
5759: PetscErrorCode PetscFERefine(PetscFE fe, PetscFE *feRef)
5760: {
5761:   PetscSpace       P, Pref;
5762:   PetscDualSpace   Q, Qref;
5763:   DM               K, Kref;
5764:   PetscQuadrature  q, qref;
5765:   const PetscReal *v0, *jac;
5766:   PetscInt         numComp, numSubelements;
5767:   PetscErrorCode   ierr;

5770:   PetscFEGetBasisSpace(fe, &P);
5771:   PetscFEGetDualSpace(fe, &Q);
5772:   PetscFEGetQuadrature(fe, &q);
5773:   PetscDualSpaceGetDM(Q, &K);
5774:   /* Create space */
5775:   PetscObjectReference((PetscObject) P);
5776:   Pref = P;
5777:   /* Create dual space */
5778:   PetscDualSpaceDuplicate(Q, &Qref);
5779:   DMRefine(K, PetscObjectComm((PetscObject) fe), &Kref);
5780:   PetscDualSpaceSetDM(Qref, Kref);
5781:   DMDestroy(&Kref);
5782:   PetscDualSpaceSetUp(Qref);
5783:   /* Create element */
5784:   PetscFECreate(PetscObjectComm((PetscObject) fe), feRef);
5785:   PetscFESetType(*feRef, PETSCFECOMPOSITE);
5786:   PetscFESetBasisSpace(*feRef, Pref);
5787:   PetscFESetDualSpace(*feRef, Qref);
5788:   PetscFEGetNumComponents(fe,    &numComp);
5789:   PetscFESetNumComponents(*feRef, numComp);
5790:   PetscFESetUp(*feRef);
5791:   PetscSpaceDestroy(&Pref);
5792:   PetscDualSpaceDestroy(&Qref);
5793:   /* Create quadrature */
5794:   PetscFECompositeGetMapping(*feRef, &numSubelements, &v0, &jac, NULL);
5795:   PetscQuadratureExpandComposite(q, numSubelements, v0, jac, &qref);
5796:   PetscFESetQuadrature(*feRef, qref);
5797:   PetscQuadratureDestroy(&qref);
5798:   return(0);
5799: }

5803: /*@
5804:   PetscFECreateDefault - Create a PetscFE for basic FEM computation

5806:   Collective on DM

5808:   Input Parameters:
5809: + dm         - The underlying DM for the domain
5810: . dim        - The spatial dimension
5811: . numComp    - The number of components
5812: . isSimplex  - Flag for simplex reference cell, otherwise its a tensor product
5813: . prefix     - The options prefix, or NULL
5814: - qorder     - The quadrature order

5816:   Output Parameter:
5817: . fem - The PetscFE object

5819:   Level: beginner

5821: .keywords: PetscFE, finite element
5822: .seealso: PetscFECreate(), PetscSpaceCreate(), PetscDualSpaceCreate()
5823: @*/
5824: PetscErrorCode PetscFECreateDefault(DM dm, PetscInt dim, PetscInt numComp, PetscBool isSimplex, const char prefix[], PetscInt qorder, PetscFE *fem)
5825: {
5826:   PetscQuadrature q;
5827:   DM              K;
5828:   PetscSpace      P;
5829:   PetscDualSpace  Q;
5830:   PetscInt        order;
5831:   PetscErrorCode  ierr;

5834:   /* Create space */
5835:   PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P);
5836:   PetscObjectSetOptionsPrefix((PetscObject) P, prefix);
5837:   PetscSpaceSetFromOptions(P);
5838:   PetscSpacePolynomialSetNumVariables(P, dim);
5839:   PetscSpaceSetUp(P);
5840:   PetscSpaceGetOrder(P, &order);
5841:   /* Create dual space */
5842:   PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);
5843:   PetscObjectSetOptionsPrefix((PetscObject) Q, prefix);
5844:   PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K);
5845:   PetscDualSpaceSetDM(Q, K);
5846:   DMDestroy(&K);
5847:   PetscDualSpaceSetOrder(Q, order);
5848:   PetscDualSpaceSetFromOptions(Q);
5849:   PetscDualSpaceSetUp(Q);
5850:   /* Create element */
5851:   PetscFECreate(PetscObjectComm((PetscObject) dm), fem);
5852:   PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix);
5853:   PetscFESetFromOptions(*fem);
5854:   PetscFESetBasisSpace(*fem, P);
5855:   PetscFESetDualSpace(*fem, Q);
5856:   PetscFESetNumComponents(*fem, numComp);
5857:   PetscFESetUp(*fem);
5858:   PetscSpaceDestroy(&P);
5859:   PetscDualSpaceDestroy(&Q);
5860:   /* Create quadrature (with specified order if given) */
5861:   if (isSimplex) {PetscDTGaussJacobiQuadrature(dim, PetscMax(qorder > 0 ? qorder : order, 1), -1.0, 1.0, &q);}
5862:   else           {PetscDTGaussTensorQuadrature(dim, PetscMax(qorder > 0 ? qorder : order, 1), -1.0, 1.0, &q);}
5863:   PetscFESetQuadrature(*fem, q);
5864:   PetscQuadratureDestroy(&q);
5865:   return(0);
5866: }