Actual source code: plexegads.c

  1: #include <petsc/private/dmpleximpl.h>
  2: #include <petsc/private/hashmapi.h>

  4: /* We need to understand how to natively parse STEP files. There seems to be only one open-source implementation of
  5:    the STEP parser contained in the OpenCASCADE package. It is enough to make a strong man weep:

  7:      https://github.com/tpaviot/oce/tree/master/src/STEPControl

  9:    The STEP, and inner EXPRESS, formats are ISO standards, so they are documented

 11:      https://stackoverflow.com/questions/26774037/documentation-or-specification-for-step-and-stp-files
 12:      http://stepmod.sourceforge.net/express_model_spec/

 14:    but again it seems that there has been a deliberate effort at obfuscation, probably to raise the bar for entrants.
 15: */

 17: #if PetscDefined(HAVE_EGADS)
 18: #include <petscdmplexegads.h>

 20: PETSC_INTERN PetscErrorCode DMSnapToGeomModel_EGADS_Internal(DM, PetscInt, ego, PetscInt, PetscInt, PetscInt, const PetscScalar[], PetscScalar[], PetscBool);
 21: PETSC_INTERN PetscErrorCode DMPlex_Geom_EDGE_XYZtoUV_Internal(const PetscScalar[], ego, const PetscScalar[], const PetscInt, const PetscInt, PetscScalar[], PetscBool);
 22: PETSC_INTERN PetscErrorCode DMPlex_Geom_FACE_XYZtoUV_Internal(const PetscScalar[], ego, const PetscScalar[], const PetscInt, const PetscInt, PetscScalar[], PetscBool);

 24: PetscErrorCode DMPlex_EGADS_GeomDecode_Internal(const PetscInt geomClass, const PetscInt geomType, char **retClass, char **retType)
 25: {
 26:   PetscFunctionBeginHot;
 27:   /* EGADS Object Type */
 28:   if (geomClass == CONTXT) *retClass = (char *)"CONTEXT";
 29:   if (geomClass == TRANSFORM) *retClass = (char *)"TRANSFORM";
 30:   if (geomClass == TESSELLATION) *retClass = (char *)"TESSELLATION";
 31:   if (geomClass == NIL) *retClass = (char *)"NIL";
 32:   if (geomClass == EMPTY) *retClass = (char *)"EMPTY";
 33:   if (geomClass == REFERENCE) *retClass = (char *)"REFERENCE";
 34:   if (geomClass == PCURVE) *retClass = (char *)"PCURVE";
 35:   if (geomClass == CURVE) *retClass = (char *)"CURVE";
 36:   if (geomClass == SURFACE) *retClass = (char *)"SURFACE";
 37:   if (geomClass == NODE) *retClass = (char *)"NODE";
 38:   if (geomClass == EDGE) *retClass = (char *)"EDGE";
 39:   if (geomClass == LOOP) *retClass = (char *)"LOOP";
 40:   if (geomClass == FACE) *retClass = (char *)"FACE";
 41:   if (geomClass == SHELL) *retClass = (char *)"SHELL";
 42:   if (geomClass == BODY) *retClass = (char *)"BODY";
 43:   if (geomClass == MODEL) *retClass = (char *)"MODEL";

 45:   /* PCURVES & CURVES */
 46:   if (geomClass == PCURVE || geomClass == CURVE) {
 47:     if (geomType == LINE) *retType = (char *)"LINE";
 48:     if (geomType == CIRCLE) *retType = (char *)"CIRCLE";
 49:     if (geomType == ELLIPSE) *retType = (char *)"ELLIPSE";
 50:     if (geomType == PARABOLA) *retType = (char *)"PARABOLA";
 51:     if (geomType == HYPERBOLA) *retType = (char *)"HYPERBOLA";
 52:     if (geomType == TRIMMED) *retType = (char *)"TRIMMED";
 53:     if (geomType == BEZIER) *retType = (char *)"BEZIER";
 54:     if (geomType == BSPLINE) *retType = (char *)"BSPLINE";
 55:     if (geomType == OFFSET) *retType = (char *)"OFFSET";
 56:   }

 58:   /* SURFACE */
 59:   if (geomClass == SURFACE) {
 60:     if (geomType == PLANE) *retType = (char *)"PLANE";
 61:     if (geomType == SPHERICAL) *retType = (char *)"SPHERICAL";
 62:     if (geomType == CYLINDRICAL) *retType = (char *)"CYLINDRICAL";
 63:     if (geomType == REVOLUTION) *retType = (char *)"REVOLUTION";
 64:     if (geomType == TOROIDAL) *retType = (char *)"TOROIDAL";
 65:     if (geomType == CONICAL) *retType = (char *)"CONICAL";
 66:     if (geomType == EXTRUSION) *retType = (char *)"EXTRUSION";
 67:     if (geomType == BEZIER) *retType = (char *)"BEZIER";
 68:     if (geomType == BSPLINE) *retType = (char *)"BSPLINE";
 69:   }

 71:   /* TOPOLOGY */
 72:   if (geomClass == NODE || geomClass == EDGE || geomClass == LOOP || geomClass == FACE || geomClass == SHELL || geomClass == BODY || geomClass == MODEL) {
 73:     if (geomType == SREVERSE) *retType = (char *)"SREVERSE";
 74:     if (geomType == NOMTYPE) *retType = (char *)"NOMTYPE";
 75:     if (geomType == SFORWARD && geomClass == FACE) *retType = (char *)"SFORWARD";
 76:     if (geomType == ONENODE && geomClass == EDGE) *retType = (char *)"ONENODE";
 77:     if (geomType == TWONODE) *retType = (char *)"TWONODE";
 78:     if (geomType == OPEN) *retType = (char *)"OPEN";
 79:     if (geomType == CLOSED) *retType = (char *)"CLOSED";
 80:     if (geomType == DEGENERATE) *retType = (char *)"DEGENERATE";
 81:     if (geomType == WIREBODY) *retType = (char *)"WIREBODY";
 82:     if (geomType == FACEBODY) *retType = (char *)"FACEBODY";
 83:     if (geomType == SHEETBODY) *retType = (char *)"SHEETBODY";
 84:     if (geomType == SOLIDBODY) *retType = (char *)"SOLIDBODY";
 85:   }
 86:   PetscFunctionReturn(PETSC_SUCCESS);
 87: }

 89: PetscErrorCode DMPlex_EGADS_EDGE_XYZtoUV_Internal(const PetscScalar coords[], ego obj, const PetscScalar range[], const PetscInt v, const PetscInt dE, PetscScalar paramsV[])
 90: {
 91:   //
 92:   //
 93:   // Depreciated. Changed all references to DMPlex_Geom_FACE_XYZtoUV_Internal()
 94:   //
 95:   //

 97:   PetscInt    loopCntr = 0;
 98:   PetscScalar dx, dy, dz, lambda, tolr, obj_old, obj_tmp, target;
 99:   PetscScalar delta, A, b;
100:   PetscScalar ts[2], tt[2], eval[18], data[18];

102:   PetscFunctionBeginHot;
103:   /* Initialize Levenberg-Marquardt parameters */
104:   lambda = 1.0;
105:   tolr   = 1.0;
106:   target = 1.0E-20;
107:   ts[0]  = (range[0] + range[1]) / 2.;

109:   while (tolr >= target) {
110:     PetscCall(EG_evaluate(obj, ts, eval));
111:     dx      = coords[v * dE + 0] - eval[0];
112:     dy      = coords[v * dE + 1] - eval[1];
113:     dz      = coords[v * dE + 2] - eval[2];
114:     obj_old = dx * dx + dy * dy + dz * dz;

116:     if (obj_old < target) {
117:       tolr = obj_old;
118:       break;
119:     }

121:     A = (eval[3] * eval[3] + eval[4] * eval[4] + eval[5] * eval[5]) * (1.0 + lambda);
122:     if (A == 0.0) {
123:       PetscCall(PetscPrintf(PETSC_COMM_SELF, "A = 0.0 \n"));
124:       break;
125:     }
126:     b = eval[3] * dx + eval[4] * dy + eval[5] * dz;

128:     /* Solve A*delta = b */
129:     delta = b / A;

131:     /* Find a temp (u,v) and associated objective function */
132:     tt[0] = ts[0] + delta;
133:     if (tt[0] < range[0]) {
134:       tt[0] = range[0];
135:       delta = tt[0] - ts[0];
136:     }
137:     if (tt[0] > range[1]) {
138:       tt[0] = range[1];
139:       delta = tt[0] - ts[0];
140:     }

142:     PetscCall(EG_evaluate(obj, tt, data));

144:     obj_tmp = (coords[v * dE + 0] - data[0]) * (coords[v * dE + 0] - data[0]) + (coords[v * dE + 1] - data[1]) * (coords[v * dE + 1] - data[1]) + (coords[v * dE + 2] - data[2]) * (coords[v * dE + 2] - data[2]);

146:     /* If step is better, accept it and halve lambda (making it more Newton-like) */
147:     if (obj_tmp < obj_old) {
148:       obj_old = obj_tmp;
149:       ts[0]   = tt[0];
150:       for (int jj = 0; jj < 18; ++jj) eval[jj] = data[jj];
151:       lambda /= 2.0;
152:       if (lambda < 1.0E-14) lambda = 1.0E-14;
153:       if (obj_old < target) {
154:         tolr = obj_old;
155:         break;
156:       }
157:     } else {
158:       /* Otherwise reject it and double lambda (making it more gradient-descent like) */
159:       lambda *= 2.0;
160:     }

162:     if (tt[0] == range[0] || tt[0] == range[1]) break;
163:     if (fabs(delta) < target) {
164:       tolr = obj_old;
165:       break;
166:     }

168:     tolr = obj_old;

170:     loopCntr += 1;
171:     if (loopCntr > 100) break;
172:   }
173:   paramsV[v * 3 + 0] = ts[0];
174:   paramsV[v * 3 + 1] = 0.;
175:   PetscFunctionReturn(PETSC_SUCCESS);
176: }

178: PetscErrorCode DMPlex_Geom_EDGE_XYZtoUV_Internal(const PetscScalar coords[], ego obj, const PetscScalar range[], const PetscInt v, const PetscInt dE, PetscScalar paramsV[], PetscBool islite)
179: {
180:   PetscInt    loopCntr = 0;
181:   PetscScalar dx, dy, dz, lambda, tolr, obj_old, obj_tmp, target;
182:   PetscScalar delta, A, b;
183:   PetscScalar ts[2], tt[2], eval[18], data[18];

185:   PetscFunctionBeginHot;
186:   /* Initialize Levenberg-Marquardt parameters */
187:   lambda = 1.0;
188:   tolr   = 1.0;
189:   target = 1.0E-20;
190:   ts[0]  = (range[0] + range[1]) / 2.;

192:   while (tolr >= target) {
193:     if (islite) PetscCall(EGlite_evaluate(obj, ts, eval));
194:     else PetscCall(EG_evaluate(obj, ts, eval));

196:     dx      = coords[v * dE + 0] - eval[0];
197:     dy      = coords[v * dE + 1] - eval[1];
198:     dz      = coords[v * dE + 2] - eval[2];
199:     obj_old = dx * dx + dy * dy + dz * dz;

201:     if (obj_old < target) {
202:       tolr = obj_old;
203:       break;
204:     }

206:     A = (eval[3] * eval[3] + eval[4] * eval[4] + eval[5] * eval[5]) * (1.0 + lambda);
207:     if (A == 0.0) {
208:       PetscCall(PetscPrintf(PETSC_COMM_SELF, "A = 0.0 \n"));
209:       break;
210:     }
211:     b = eval[3] * dx + eval[4] * dy + eval[5] * dz;

213:     /* Solve A*delta = b */
214:     delta = b / A;

216:     /* Find a temp (u,v) and associated objective function */
217:     tt[0] = ts[0] + delta;
218:     if (tt[0] < range[0]) {
219:       tt[0] = range[0];
220:       delta = tt[0] - ts[0];
221:     }
222:     if (tt[0] > range[1]) {
223:       tt[0] = range[1];
224:       delta = tt[0] - ts[0];
225:     }

227:     if (islite) PetscCall(EGlite_evaluate(obj, tt, data));
228:     else PetscCall(EG_evaluate(obj, tt, data));

230:     obj_tmp = (coords[v * dE + 0] - data[0]) * (coords[v * dE + 0] - data[0]) + (coords[v * dE + 1] - data[1]) * (coords[v * dE + 1] - data[1]) + (coords[v * dE + 2] - data[2]) * (coords[v * dE + 2] - data[2]);

232:     /* If step is better, accept it and halve lambda (making it more Newton-like) */
233:     if (obj_tmp < obj_old) {
234:       obj_old = obj_tmp;
235:       ts[0]   = tt[0];
236:       for (int jj = 0; jj < 18; ++jj) eval[jj] = data[jj];
237:       lambda /= 2.0;
238:       if (lambda < 1.0E-14) lambda = 1.0E-14;
239:       if (obj_old < target) {
240:         tolr = obj_old;
241:         break;
242:       }
243:     } else {
244:       /* Otherwise reject it and double lambda (making it more gradient-descent like) */
245:       lambda *= 2.0;
246:     }

248:     if (tt[0] == range[0] || tt[0] == range[1]) break;
249:     if (fabs(delta) < target) {
250:       tolr = obj_old;
251:       break;
252:     }

254:     tolr = obj_old;

256:     loopCntr += 1;
257:     if (loopCntr > 100) break;
258:   }
259:   paramsV[v * 3 + 0] = ts[0];
260:   paramsV[v * 3 + 1] = 0.;
261:   PetscFunctionReturn(PETSC_SUCCESS);
262: }

264: PetscErrorCode DMPlex_EGADS_FACE_XYZtoUV_Internal(const PetscScalar coords[], ego obj, const PetscScalar range[], const PetscInt v, const PetscInt dE, PetscScalar paramsV[])
265: {
266:   //
267:   //
268:   // Depreciated. Changed all references to DMPlex_Geom_FACE_XYZtoUV_Internal()
269:   //
270:   //

272:   PetscInt    loopCntr = 0;
273:   PetscScalar dx, dy, dz, lambda, tolr, denom, obj_old, obj_tmp, target;
274:   PetscScalar uvs[2], uvt[2], delta[2], A[4], b[2], eval[18], data[18];

276:   PetscFunctionBeginHot;
277:   /* Initialize Levenberg-Marquardt parameters */
278:   lambda = 1.0;
279:   tolr   = 1.0;
280:   target = 1.0E-20;
281:   uvs[0] = (range[0] + range[1]) / 2.;
282:   uvs[1] = (range[2] + range[3]) / 2.;

284:   while (tolr >= target) {
285:     PetscCall(EG_evaluate(obj, uvs, eval));
286:     dx      = coords[v * dE + 0] - eval[0];
287:     dy      = coords[v * dE + 1] - eval[1];
288:     dz      = coords[v * dE + 2] - eval[2];
289:     obj_old = dx * dx + dy * dy + dz * dz;

291:     if (obj_old < target) {
292:       tolr = obj_old;
293:       break;
294:     }

296:     A[0] = (eval[3] * eval[3] + eval[4] * eval[4] + eval[5] * eval[5]) * (1.0 + lambda);
297:     A[1] = eval[3] * eval[6] + eval[4] * eval[7] + eval[5] * eval[8];
298:     A[2] = A[1];
299:     A[3] = (eval[6] * eval[6] + eval[7] * eval[7] + eval[8] * eval[8]) * (1.0 + lambda);

301:     b[0] = eval[3] * dx + eval[4] * dy + eval[5] * dz;
302:     b[1] = eval[6] * dx + eval[7] * dy + eval[8] * dz;

304:     /* Solve A*delta = b using Cramer's Rule */
305:     denom = A[0] * A[3] - A[2] * A[1];
306:     if (denom == 0.0) PetscCall(PetscPrintf(PETSC_COMM_SELF, "denom = 0.0 \n"));
307:     delta[0] = (b[0] * A[3] - b[1] * A[1]) / denom;
308:     delta[1] = (A[0] * b[1] - A[2] * b[0]) / denom;

310:     /* Find a temp (u,v) and associated objective function */
311:     uvt[0] = uvs[0] + delta[0];
312:     uvt[1] = uvs[1] + delta[1];

314:     if (uvt[0] < range[0]) {
315:       uvt[0]   = range[0];
316:       delta[0] = uvt[0] - uvs[0];
317:     }
318:     if (uvt[0] > range[1]) {
319:       uvt[0]   = range[1];
320:       delta[0] = uvt[0] - uvs[0];
321:     }
322:     if (uvt[1] < range[2]) {
323:       uvt[1]   = range[2];
324:       delta[1] = uvt[1] - uvs[1];
325:     }
326:     if (uvt[1] > range[3]) {
327:       uvt[1]   = range[3];
328:       delta[1] = uvt[1] - uvs[1];
329:     }

331:     PetscCall(EG_evaluate(obj, uvt, data));

333:     obj_tmp = (coords[v * dE + 0] - data[0]) * (coords[v * dE + 0] - data[0]) + (coords[v * dE + 1] - data[1]) * (coords[v * dE + 1] - data[1]) + (coords[v * dE + 2] - data[2]) * (coords[v * dE + 2] - data[2]);

335:     /* If step is better, accept it and halve lambda (making it more Newton-like) */
336:     if (obj_tmp < obj_old) {
337:       obj_old = obj_tmp;
338:       uvs[0]  = uvt[0];
339:       uvs[1]  = uvt[1];
340:       for (int jj = 0; jj < 18; ++jj) eval[jj] = data[jj];
341:       lambda /= 2.0;
342:       if (lambda < 1.0E-14) lambda = 1.0E-14;
343:       if (obj_old < target) {
344:         tolr = obj_old;
345:         break;
346:       }
347:     } else {
348:       /* Otherwise reject it and double lambda (making it more gradient-descent like) */
349:       lambda *= 2.0;
350:     }

352:     if (sqrt(delta[0] * delta[0] + delta[1] * delta[1]) < target) {
353:       tolr = obj_old;
354:       break;
355:     }

357:     tolr = obj_old;

359:     loopCntr += 1;
360:     if (loopCntr > 100) break;
361:   }
362:   paramsV[v * 3 + 0] = uvs[0];
363:   paramsV[v * 3 + 1] = uvs[1];
364:   PetscFunctionReturn(PETSC_SUCCESS);
365: }

367: PetscErrorCode DMPlex_Geom_FACE_XYZtoUV_Internal(const PetscScalar coords[], ego obj, const PetscScalar range[], const PetscInt v, const PetscInt dE, PetscScalar paramsV[], PetscBool islite)
368: {
369:   PetscInt    loopCntr = 0;
370:   PetscScalar dx, dy, dz, lambda, tolr, denom, obj_old, obj_tmp, target;
371:   PetscScalar uvs[2], uvt[2], delta[2], A[4], b[2], eval[18], data[18];

373:   PetscFunctionBeginHot;
374:   /* Initialize Levenberg-Marquardt parameters */
375:   lambda = 1.0;
376:   tolr   = 1.0;
377:   target = 1.0E-20;
378:   uvs[0] = (range[0] + range[1]) / 2.;
379:   uvs[1] = (range[2] + range[3]) / 2.;

381:   while (tolr >= target) {
382:     if (islite) PetscCallEGADS(EGlite_evaluate, obj, uvs, eval);
383:     else PetscCallEGADS(EG_evaluate, obj, uvs, eval);

385:     dx      = coords[v * dE + 0] - eval[0];
386:     dy      = coords[v * dE + 1] - eval[1];
387:     dz      = coords[v * dE + 2] - eval[2];
388:     obj_old = dx * dx + dy * dy + dz * dz;

390:     if (obj_old < target) {
391:       tolr = obj_old;
392:       break;
393:     }

395:     A[0] = (eval[3] * eval[3] + eval[4] * eval[4] + eval[5] * eval[5]) * (1.0 + lambda);
396:     A[1] = eval[3] * eval[6] + eval[4] * eval[7] + eval[5] * eval[8];
397:     A[2] = A[1];
398:     A[3] = (eval[6] * eval[6] + eval[7] * eval[7] + eval[8] * eval[8]) * (1.0 + lambda);

400:     b[0] = eval[3] * dx + eval[4] * dy + eval[5] * dz;
401:     b[1] = eval[6] * dx + eval[7] * dy + eval[8] * dz;

403:     /* Solve A*delta = b using Cramer's Rule */
404:     denom = A[0] * A[3] - A[2] * A[1];
405:     if (denom == 0.0) PetscCall(PetscPrintf(PETSC_COMM_SELF, "denom = 0.0 \n"));
406:     delta[0] = (b[0] * A[3] - b[1] * A[1]) / denom;
407:     delta[1] = (A[0] * b[1] - A[2] * b[0]) / denom;

409:     /* Find a temp (u,v) and associated objective function */
410:     uvt[0] = uvs[0] + delta[0];
411:     uvt[1] = uvs[1] + delta[1];

413:     if (uvt[0] < range[0]) {
414:       uvt[0]   = range[0];
415:       delta[0] = uvt[0] - uvs[0];
416:     }
417:     if (uvt[0] > range[1]) {
418:       uvt[0]   = range[1];
419:       delta[0] = uvt[0] - uvs[0];
420:     }
421:     if (uvt[1] < range[2]) {
422:       uvt[1]   = range[2];
423:       delta[1] = uvt[1] - uvs[1];
424:     }
425:     if (uvt[1] > range[3]) {
426:       uvt[1]   = range[3];
427:       delta[1] = uvt[1] - uvs[1];
428:     }

430:     if (islite) PetscCall(EGlite_evaluate(obj, uvt, data));
431:     else PetscCall(EG_evaluate(obj, uvt, data));

433:     obj_tmp = (coords[v * dE + 0] - data[0]) * (coords[v * dE + 0] - data[0]) + (coords[v * dE + 1] - data[1]) * (coords[v * dE + 1] - data[1]) + (coords[v * dE + 2] - data[2]) * (coords[v * dE + 2] - data[2]);

435:     /* If step is better, accept it and halve lambda (making it more Newton-like) */
436:     if (obj_tmp < obj_old) {
437:       obj_old = obj_tmp;
438:       uvs[0]  = uvt[0];
439:       uvs[1]  = uvt[1];
440:       for (int jj = 0; jj < 18; ++jj) eval[jj] = data[jj];
441:       lambda /= 2.0;
442:       if (lambda < 1.0E-14) lambda = 1.0E-14;
443:       if (obj_old < target) {
444:         tolr = obj_old;
445:         break;
446:       }
447:     } else {
448:       /* Otherwise reject it and double lambda (making it more gradient-descent like) */
449:       lambda *= 2.0;
450:     }

452:     if (sqrt(delta[0] * delta[0] + delta[1] * delta[1]) < target) {
453:       tolr = obj_old;
454:       break;
455:     }

457:     tolr = obj_old;

459:     loopCntr += 1;
460:     if (loopCntr > 100) break;
461:   }
462:   paramsV[v * 3 + 0] = uvs[0];
463:   paramsV[v * 3 + 1] = uvs[1];
464:   PetscFunctionReturn(PETSC_SUCCESS);
465: }

467: PetscErrorCode DMSnapToGeomModel_EGADS_Internal(DM dm, PetscInt p, ego model, PetscInt bodyID, PetscInt faceID, PetscInt edgeID, const PetscScalar mcoords[], PetscScalar gcoords[], PetscBool islite)
468: {
469:   /* PETSc Variables */
470:   DM   cdm;
471:   ego *bodies;
472:   ego  geom, body, obj;
473:   /* result has to hold derivatives, along with the value */
474:   double       params[3], result[18], paramsV[16 * 3], range[4];
475:   int          Nb, oclass, mtype, *senses, peri;
476:   Vec          coordinatesLocal;
477:   PetscScalar *coords = NULL;
478:   PetscInt     Nv, v, Np = 0, pm;
479:   PetscInt     dE, d;
480:   PetscReal    pTolr = 1.0e-14;

482:   PetscFunctionBeginHot;
483:   PetscCall(DMGetCoordinateDM(dm, &cdm));
484:   PetscCall(DMGetCoordinateDim(dm, &dE));
485:   PetscCall(DMGetCoordinatesLocal(dm, &coordinatesLocal));

487:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
488:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));

490:   PetscCheck(bodyID < Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Body %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", bodyID, Nb);
491:   body = bodies[bodyID];

493:   if (edgeID >= 0) {
494:     if (islite) {
495:       PetscCall(EGlite_objectBodyTopo(body, EDGE, edgeID, &obj));
496:       Np = 1;
497:     } else {
498:       PetscCall(EG_objectBodyTopo(body, EDGE, edgeID, &obj));
499:       Np = 1;
500:     }
501:   } else if (faceID >= 0) {
502:     if (islite) {
503:       PetscCall(EGlite_objectBodyTopo(body, FACE, faceID, &obj));
504:       Np = 2;
505:     } else {
506:       PetscCall(EG_objectBodyTopo(body, FACE, faceID, &obj));
507:       Np = 2;
508:     }
509:   } else {
510:     for (d = 0; d < dE; ++d) gcoords[d] = mcoords[d];
511:     PetscFunctionReturn(PETSC_SUCCESS);
512:   }

514:   /* Calculate parameters (t or u,v) for vertices */
515:   PetscCall(DMPlexVecGetClosure(cdm, NULL, coordinatesLocal, p, &Nv, &coords));
516:   Nv /= dE;
517:   if (Nv == 1) {
518:     PetscCall(DMPlexVecRestoreClosure(cdm, NULL, coordinatesLocal, p, &Nv, &coords));
519:     for (d = 0; d < dE; ++d) gcoords[d] = mcoords[d];
520:     PetscFunctionReturn(PETSC_SUCCESS);
521:   }
522:   PetscCheck(Nv <= 16, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %" PetscInt_FMT " coordinates associated to point %" PetscInt_FMT, Nv, p);

524:   /* Correct EGADS/EGADSlite 2pi bug when calculating nearest point on Periodic Surfaces */
525:   if (islite) PetscCall(EGlite_getRange(obj, range, &peri));
526:   else PetscCall(EG_getRange(obj, range, &peri));

528:   for (v = 0; v < Nv; ++v) {
529:     if (edgeID > 0) {
530:       PetscCall(DMPlex_Geom_EDGE_XYZtoUV_Internal(coords, obj, range, v, dE, paramsV, islite));
531:     } else {
532:       PetscCall(DMPlex_Geom_FACE_XYZtoUV_Internal(coords, obj, range, v, dE, paramsV, islite));
533:     }
534:   }
535:   PetscCall(DMPlexVecRestoreClosure(cdm, NULL, coordinatesLocal, p, &Nv, &coords));

537:   /* Calculate parameters (t or u,v) for new vertex at edge midpoint */
538:   for (pm = 0; pm < Np; ++pm) {
539:     params[pm] = 0.;
540:     for (v = 0; v < Nv; ++v) params[pm] += paramsV[v * 3 + pm];
541:     params[pm] /= Nv;
542:   }
543:   PetscCheck((params[0] + pTolr >= range[0]) || (params[0] - pTolr <= range[1]), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %" PetscInt_FMT " had bad interpolation", p);
544:   PetscCheck(Np < 2 || ((params[1] + pTolr >= range[2]) || (params[1] - pTolr <= range[3])), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %d had bad interpolation on v", p);

546:   /* Put coordinates for new vertex in result[] */
547:   if (islite) PetscCall(EGlite_evaluate(obj, params, result));
548:   else PetscCall(EG_evaluate(obj, params, result));

550:   for (d = 0; d < dE; ++d) gcoords[d] = result[d];
551:   PetscFunctionReturn(PETSC_SUCCESS);
552: }
553: #endif

555: PetscErrorCode DMSnapToGeomModel_EGADS(DM dm, PetscInt p, PetscInt dE, const PetscScalar mcoords[], PetscScalar gcoords[])
556: {
557:   PetscFunctionBeginHot;
558: #if PetscDefined(HAVE_EGADS)
559:   DMLabel        bodyLabel, faceLabel, edgeLabel;
560:   PetscInt       bodyID, faceID, edgeID;
561:   PetscContainer modelObj;
562:   ego            model;
563:   PetscBool      islite = PETSC_FALSE;

565:   // FIXME: Change -dm_plex_refine_without_snap_to_geom to DM to shut off snapping
566:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
567:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
568:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
569:   PetscCheck(bodyLabel && faceLabel && edgeLabel, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "EGADS meshes must have body, face, and edge labels defined");
570:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
571:   if (!modelObj) {
572:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
573:     islite = PETSC_TRUE;
574:   }
575:   PetscCheck(modelObj, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "EGADS mesh missing model object");

577:   PetscCall(PetscContainerGetPointer(modelObj, &model));
578:   PetscCall(DMLabelGetValue(bodyLabel, p, &bodyID));
579:   PetscCall(DMLabelGetValue(faceLabel, p, &faceID));
580:   PetscCall(DMLabelGetValue(edgeLabel, p, &edgeID));
581:   /* Allows for "Connective" Plex Edges present in models with multiple non-touching Entities */
582:   if (bodyID < 0) {
583:     for (PetscInt d = 0; d < dE; ++d) gcoords[d] = mcoords[d];
584:     PetscFunctionReturn(PETSC_SUCCESS);
585:   }
586:   PetscCall(DMSnapToGeomModel_EGADS_Internal(dm, p, model, bodyID, faceID, edgeID, mcoords, gcoords, islite));
587: #endif
588:   PetscFunctionReturn(PETSC_SUCCESS);
589: }

591: #if PetscDefined(HAVE_EGADS)
592: PetscErrorCode DMPlexGeomPrintModel_Internal(ego model, PetscBool islite)
593: {
594:   /* PETSc Variables */
595:   ego geom, *bodies, *nobjs, *mobjs, *lobjs, *shobjs, *fobjs, *eobjs;
596:   int oclass, mtype, *senses, *shsenses, *fsenses, *lsenses, *esenses;
597:   int Nb, b;

599:   PetscFunctionBeginUser;
600:   /* test bodyTopo functions */
601:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
602:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
603:   PetscCall(PetscPrintf(PETSC_COMM_SELF, " Number of BODIES (nbodies): %" PetscInt_FMT " \n", Nb));

605:   for (b = 0; b < Nb; ++b) {
606:     ego body = bodies[b];
607:     int id, sh, Nsh, f, Nf, l, Nl, e, Ne, v, Nv;

609:     /* List Topology of Bodies */
610:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
611:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "   BODY %d TOPOLOGY SUMMARY \n", b));

613:     /* Output Basic Model Topology */
614:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, SHELL, &Nsh, &shobjs));
615:     else PetscCall(EG_getBodyTopos(body, NULL, SHELL, &Nsh, &shobjs));
616:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      Number of SHELLS: %d \n", Nsh));

618:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
619:     else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
620:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      Number of FACES: %d \n", Nf));

622:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
623:     else PetscCall(EG_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
624:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      Number of LOOPS: %d \n", Nl));

626:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
627:     else PetscCall(EG_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
628:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      Number of EDGES: %d \n", Ne));

630:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
631:     else PetscCall(EG_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
632:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      Number of NODES: %d \n", Nv));

634:     if (islite) {
635:       EGlite_free(shobjs);
636:       EGlite_free(fobjs);
637:       EGlite_free(lobjs);
638:       EGlite_free(eobjs);
639:       EGlite_free(nobjs);
640:     } else {
641:       EG_free(shobjs);
642:       EG_free(fobjs);
643:       EG_free(lobjs);
644:       EG_free(eobjs);
645:       EG_free(nobjs);
646:     }

648:     /* List Topology of Bodies */
649:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
650:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "      BODY %d TOPOLOGY DETAILS \n", b));

652:     /* Get SHELL info which associated with the current BODY */
653:     if (islite) PetscCall(EGlite_getTopology(body, &geom, &oclass, &mtype, NULL, &Nsh, &shobjs, &shsenses));
654:     else PetscCall(EG_getTopology(body, &geom, &oclass, &mtype, NULL, &Nsh, &shobjs, &shsenses));

656:     for (sh = 0; sh < Nsh; ++sh) {
657:       ego shell   = shobjs[sh];
658:       int shsense = shsenses[sh];

660:       if (islite) id = EGlite_indexBodyTopo(body, shell);
661:       else id = EG_indexBodyTopo(body, shell);
662:       PetscCall(PetscPrintf(PETSC_COMM_SELF, "         SHELL ID: %d :: sense = %d\n", id, shsense));

664:       /* Get FACE information associated with current SHELL */
665:       if (islite) PetscCall(EGlite_getTopology(shell, &geom, &oclass, &mtype, NULL, &Nf, &fobjs, &fsenses));
666:       else PetscCall(EG_getTopology(shell, &geom, &oclass, &mtype, NULL, &Nf, &fobjs, &fsenses));

668:       for (f = 0; f < Nf; ++f) {
669:         ego     face = fobjs[f];
670:         ego     gRef, gPrev, gNext;
671:         int     goclass, gmtype, *gpinfo;
672:         double *gprv;
673:         char   *gClass = (char *)"", *gType = (char *)"";
674:         double  fdata[4];
675:         ego     fRef, fPrev, fNext;
676:         int     foclass, fmtype;

678:         if (islite) id = EGlite_indexBodyTopo(body, face);
679:         else id = EG_indexBodyTopo(body, face);

681:         /* Get LOOP info associated with current FACE */
682:         if (islite) {
683:           PetscCall(EGlite_getTopology(face, &geom, &oclass, &mtype, fdata, &Nl, &lobjs, &lsenses));
684:           PetscCall(EGlite_getInfo(face, &foclass, &fmtype, &fRef, &fPrev, &fNext));
685:           PetscCall(EGlite_getGeometry(geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv));
686:           PetscCall(EGlite_getInfo(geom, &goclass, &gmtype, &gRef, &gPrev, &gNext));
687:         } else {
688:           PetscCall(EG_getTopology(face, &geom, &oclass, &mtype, fdata, &Nl, &lobjs, &lsenses));
689:           PetscCall(EG_getInfo(face, &foclass, &fmtype, &fRef, &fPrev, &fNext));
690:           PetscCall(EG_getGeometry(geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv));
691:           PetscCall(EG_getInfo(geom, &goclass, &gmtype, &gRef, &gPrev, &gNext));
692:         }

694:         PetscCall(DMPlex_EGADS_GeomDecode_Internal(goclass, gmtype, &gClass, &gType));
695:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "           FACE ID: %d :: sense = %d \n", id, fmtype));
696:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "             GEOMETRY CLASS: %s \n", gClass));
697:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "             GEOMETRY TYPE:  %s \n\n", gType));
698:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "             RANGE (umin, umax) = (%f, %f) \n", fdata[0], fdata[1]));
699:         PetscCall(PetscPrintf(PETSC_COMM_SELF, "                   (vmin, vmax) = (%f, %f) \n\n", fdata[2], fdata[3]));

701:         for (l = 0; l < Nl; ++l) {
702:           ego loop   = lobjs[l];
703:           int lsense = lsenses[l];

705:           if (islite) id = EGlite_indexBodyTopo(body, loop);
706:           else id = EG_indexBodyTopo(body, loop);

708:           PetscCall(PetscPrintf(PETSC_COMM_SELF, "             LOOP ID: %d :: sense = %d\n", id, lsense));

710:           /* Get EDGE info associated with the current LOOP */
711:           if (islite) PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &esenses));
712:           else PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &esenses));

714:           for (e = 0; e < Ne; ++e) {
715:             ego    edge = eobjs[e];
716:             ego    topRef, prev, next;
717:             int    esense   = esenses[e];
718:             double range[4] = {0., 0., 0., 0.};
719:             int    peri;
720:             ego    gEref, gEprev, gEnext;
721:             int    gEoclass, gEmtype;
722:             char  *gEclass = (char *)"", *gEtype = (char *)"";

724:             if (islite) {
725:               PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
726:               if (mtype != DEGENERATE) PetscCall(EGlite_getInfo(geom, &gEoclass, &gEmtype, &gEref, &gEprev, &gEnext));
727:             } else {
728:               PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
729:               PetscCall(EG_getInfo(geom, &gEoclass, &gEmtype, &gEref, &gEprev, &gEnext));
730:             }

732:             if (mtype != DEGENERATE) PetscCall(DMPlex_EGADS_GeomDecode_Internal(gEoclass, gEmtype, &gEclass, &gEtype));

734:             if (islite) {
735:               id = EGlite_indexBodyTopo(body, edge);
736:               PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
737:             } else {
738:               id = EG_indexBodyTopo(body, edge);
739:               PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
740:             }

742:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "               EDGE ID: %d :: sense = %d\n", id, esense));
743:             if (mtype != DEGENERATE) {
744:               PetscCall(PetscPrintf(PETSC_COMM_SELF, "                 GEOMETRY CLASS: %s \n", gEclass));
745:               PetscCall(PetscPrintf(PETSC_COMM_SELF, "                 GEOMETRY TYPE:  %s \n", gEtype));
746:             }

748:             if (mtype == DEGENERATE) PetscCall(PetscPrintf(PETSC_COMM_SELF, "                 EDGE %d is DEGENERATE \n", id));

750:             if (islite) PetscCall(EGlite_getRange(edge, range, &peri));
751:             else PetscCall(EG_getRange(edge, range, &peri));

753:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "                 Peri = %d :: Range = %lf, %lf, %lf, %lf \n", peri, range[0], range[1], range[2], range[3]));

755:             /* Get NODE info associated with the current EDGE */
756:             if (islite) PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
757:             else PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));

759:             for (v = 0; v < Nv; ++v) {
760:               ego    vertex = nobjs[v];
761:               double limits[4];
762:               int    unused;

764:               if (islite) {
765:                 PetscCall(EGlite_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
766:                 id = EGlite_indexBodyTopo(body, vertex);
767:               } else {
768:                 PetscCall(EG_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
769:                 id = EG_indexBodyTopo(body, vertex);
770:               }
771:               PetscCall(PetscPrintf(PETSC_COMM_SELF, "                 NODE ID: %d \n", id));
772:               PetscCall(PetscPrintf(PETSC_COMM_SELF, "                    (x, y, z) = (%lf, %lf, %lf) \n", limits[0], limits[1], limits[2]));
773:             }
774:           }
775:         }
776:       }
777:     }
778:   }
779:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n\n"));
780:   PetscFunctionReturn(PETSC_SUCCESS);
781: }

783: static PetscErrorCode DMPlexEGADSDestroy_Private(PetscCtxRt context)
784: {
785:   if (*(void **)context) EG_deleteObject((ego) * (void **)context);
786:   return PETSC_SUCCESS;
787: }

789: static PetscErrorCode DMPlexEGADSClose_Private(PetscCtxRt context)
790: {
791:   if (*(void **)context) EG_close((ego) * (void **)context);
792:   return PETSC_SUCCESS;
793: }

795: PetscErrorCode DMPlexEGADSliteDestroy_Private(PetscCtxRt context)
796: {
797:   if (*(void **)context) EGlite_deleteObject((ego) * (void **)context);
798:   return PETSC_SUCCESS;
799: }

801: PetscErrorCode DMPlexEGADSliteClose_Private(PetscCtxRt context)
802: {
803:   if (*(void **)context) EGlite_close((ego) * (void **)context);
804:   return PETSC_SUCCESS;
805: }

807: PetscErrorCode DMPlexCreateGeom_Internal(MPI_Comm comm, ego context, ego model, DM *newdm, PetscBool islite)
808: {
809:   /* EGADS variables */
810:   ego geom, *bodies, *objs, *nobjs, *mobjs, *lobjs;
811:   int oclass, mtype, nbodies, *senses;
812:   int b;
813:   /* PETSc variables */
814:   DM          dm;
815:   DMLabel     bodyLabel, faceLabel, edgeLabel, vertexLabel;
816:   PetscHMapI  edgeMap = NULL;
817:   PetscInt    cStart, cEnd, c;
818:   PetscInt    dim = -1, cdim = -1, numCorners = 0, maxCorners = 0, numVertices = 0, newVertices = 0, numEdges = 0, numCells = 0, newCells = 0, numQuads = 0, cOff = 0, fOff = 0;
819:   PetscInt   *cells = NULL, *cone = NULL;
820:   PetscReal  *coords = NULL;
821:   PetscMPIInt rank;

823:   PetscFunctionBegin;
824:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
825:   if (rank == 0) {
826:     const PetscInt debug = 0;

828:     /*
829:       Generate PETSc DMPlex
830:       Get all Nodes in model, record coordinates in a correctly formatted array
831:       Cycle through bodies, cycle through loops, recorde NODE IDs in a correctly formatted array
832:       We need to uniformly refine the initial geometry to guarantee a valid mesh
833:     */

835:     /* Calculate cell and vertex sizes */
836:     if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));
837:     else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));

839:     PetscCall(PetscHMapICreate(&edgeMap));
840:     numEdges = 0;
841:     for (b = 0; b < nbodies; ++b) {
842:       ego body = bodies[b];
843:       int id, Nl, l, Nv, v;

845:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
846:       else PetscCall(EG_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));

848:       for (l = 0; l < Nl; ++l) {
849:         ego loop = lobjs[l];
850:         int Ner  = 0, Ne, e, Nc;

852:         if (islite) PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
853:         else PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));

855:         for (e = 0; e < Ne; ++e) {
856:           ego           edge = objs[e];
857:           int           Nv, id;
858:           PetscHashIter iter;
859:           PetscBool     found;

861:           if (islite) PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
862:           else PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));

864:           if (mtype == DEGENERATE) continue;

866:           if (islite) {
867:             id = EGlite_indexBodyTopo(body, edge);
868:           } else {
869:             id = EG_indexBodyTopo(body, edge);
870:           }

872:           PetscCall(PetscHMapIFind(edgeMap, id - 1, &iter, &found));
873:           if (!found) PetscCall(PetscHMapISet(edgeMap, id - 1, numEdges++));
874:           ++Ner;
875:         }
876:         if (Ner == 2) {
877:           Nc = 2;
878:         } else if (Ner == 3) {
879:           Nc = 4;
880:         } else if (Ner == 4) {
881:           Nc = 8;
882:           ++numQuads;
883:         } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot support loop with %d edges", Ner);
884:         numCells += Nc;
885:         newCells += Nc - 1;
886:         maxCorners = PetscMax(Ner * 2 + 1, maxCorners);
887:       }
888:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
889:       else PetscCall(EG_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));

891:       for (v = 0; v < Nv; ++v) {
892:         ego vertex = nobjs[v];

894:         if (islite) {
895:           id = EGlite_indexBodyTopo(body, vertex);
896:         } else {
897:           id = EG_indexBodyTopo(body, vertex);
898:         }
899:         /* TODO: Instead of assuming contiguous ids, we could use a hash table */
900:         numVertices = PetscMax(id, numVertices);
901:       }
902:       if (islite) {
903:         EGlite_free(lobjs);
904:         EGlite_free(nobjs);
905:       } else {
906:         EG_free(lobjs);
907:         EG_free(nobjs);
908:       }
909:     }
910:     PetscCall(PetscHMapIGetSize(edgeMap, &numEdges));
911:     newVertices = numEdges + numQuads;
912:     numVertices += newVertices;

914:     dim        = 2; /* Assume 3D Models :: Need to update to handle 2D Models in the future */
915:     cdim       = 3; /* Assume 3D Models :: Need to update to handle 2D Models in the future */
916:     numCorners = 3; /* Split cells into triangles */
917:     PetscCall(PetscMalloc3(numVertices * cdim, &coords, numCells * numCorners, &cells, maxCorners, &cone));

919:     /* Get vertex coordinates */
920:     for (b = 0; b < nbodies; ++b) {
921:       ego body = bodies[b];
922:       int id, Nv, v;

924:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
925:       else PetscCall(EG_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));

927:       for (v = 0; v < Nv; ++v) {
928:         ego    vertex = nobjs[v];
929:         double limits[4];
930:         int    unused;

932:         if (islite) {
933:           PetscCall(EGlite_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
934:           id = EGlite_indexBodyTopo(body, vertex);
935:         } else {
936:           PetscCall(EG_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
937:           id = EG_indexBodyTopo(body, vertex);
938:         }

940:         coords[(id - 1) * cdim + 0] = limits[0];
941:         coords[(id - 1) * cdim + 1] = limits[1];
942:         coords[(id - 1) * cdim + 2] = limits[2];
943:       }
944:       if (islite) {
945:         EGlite_free(nobjs);
946:       } else {
947:         EG_free(nobjs);
948:       }
949:     }
950:     PetscCall(PetscHMapIClear(edgeMap));
951:     fOff     = numVertices - newVertices + numEdges;
952:     numEdges = 0;
953:     numQuads = 0;
954:     for (b = 0; b < nbodies; ++b) {
955:       ego body = bodies[b];
956:       int Nl, l;

958:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
959:       else PetscCall(EG_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));

961:       for (l = 0; l < Nl; ++l) {
962:         ego loop = lobjs[l];
963:         int lid, Ner = 0, Ne, e;

965:         if (islite) {
966:           lid = EGlite_indexBodyTopo(body, loop);
967:           PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
968:         } else {
969:           lid = EG_indexBodyTopo(body, loop);
970:           PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
971:         }

973:         for (e = 0; e < Ne; ++e) {
974:           ego           edge = objs[e];
975:           int           eid, Nv;
976:           PetscHashIter iter;
977:           PetscBool     found;

979:           if (islite) PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
980:           else PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));

982:           if (mtype == DEGENERATE) continue;
983:           ++Ner;

985:           if (islite) {
986:             eid = EGlite_indexBodyTopo(body, edge);
987:           } else {
988:             eid = EG_indexBodyTopo(body, edge);
989:           }

991:           PetscCall(PetscHMapIFind(edgeMap, eid - 1, &iter, &found));
992:           if (!found) {
993:             PetscInt v = numVertices - newVertices + numEdges;
994:             double   range[4], params[3] = {0., 0., 0.}, result[18];
995:             int      periodic[2];

997:             PetscCall(PetscHMapISet(edgeMap, eid - 1, numEdges++));

999:             if (islite) {
1000:               PetscCall(EGlite_getRange(edge, range, periodic));
1001:             } else {
1002:               PetscCall(EG_getRange(edge, range, periodic));
1003:             }

1005:             params[0] = 0.5 * (range[0] + range[1]);
1006:             if (islite) {
1007:               PetscCall(EGlite_evaluate(edge, params, result));
1008:             } else {
1009:               PetscCall(EG_evaluate(edge, params, result));
1010:             }
1011:             coords[v * cdim + 0] = result[0];
1012:             coords[v * cdim + 1] = result[1];
1013:             coords[v * cdim + 2] = result[2];
1014:           }
1015:         }
1016:         if (Ner == 4) {
1017:           PetscInt v = fOff + numQuads++;
1018:           ego     *fobjs, face;
1019:           double   range[4], params[3] = {0., 0., 0.}, result[18];
1020:           int      Nf, fid, periodic[2];

1022:           if (islite) PetscCall(EGlite_getBodyTopos(body, loop, FACE, &Nf, &fobjs));
1023:           else PetscCall(EG_getBodyTopos(body, loop, FACE, &Nf, &fobjs));
1024:           face = fobjs[0];

1026:           if (islite) {
1027:             fid = EGlite_indexBodyTopo(body, face);
1028:           } else {
1029:             fid = EG_indexBodyTopo(body, face);
1030:           }

1032:           PetscCheck(Nf != 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Loop %d has %" PetscInt_FMT " faces, instead of 1 (%" PetscInt_FMT ")", lid - 1, Nf, fid);
1033:           if (islite) {
1034:             PetscCall(EGlite_getRange(face, range, periodic));
1035:           } else {
1036:             PetscCall(EG_getRange(face, range, periodic));
1037:           }
1038:           params[0] = 0.5 * (range[0] + range[1]);
1039:           params[1] = 0.5 * (range[2] + range[3]);
1040:           if (islite) {
1041:             PetscCall(EGlite_evaluate(face, params, result));
1042:           } else {
1043:             PetscCall(EG_evaluate(face, params, result));
1044:           }
1045:           coords[v * cdim + 0] = result[0];
1046:           coords[v * cdim + 1] = result[1];
1047:           coords[v * cdim + 2] = result[2];
1048:         }
1049:       }
1050:     }
1051:     PetscCheck(numEdges + numQuads == newVertices, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of new vertices %d != %d previous count", numEdges + numQuads, newVertices);

1053:     /* Get cell vertices by traversing loops */
1054:     numQuads = 0;
1055:     cOff     = 0;
1056:     for (b = 0; b < nbodies; ++b) {
1057:       ego body = bodies[b];
1058:       int id, Nl, l;

1060:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
1061:       else PetscCall(EG_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
1062:       for (l = 0; l < Nl; ++l) {
1063:         ego loop = lobjs[l];
1064:         int lid, Ner = 0, Ne, e, nc = 0, c, Nt, t;

1066:         if (islite) {
1067:           lid = EGlite_indexBodyTopo(body, loop);
1068:           PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
1069:         } else {
1070:           lid = EG_indexBodyTopo(body, loop);
1071:           PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
1072:         }

1074:         for (e = 0; e < Ne; ++e) {
1075:           ego edge = objs[e];
1076:           int points[3];
1077:           int eid, Nv, v, tmp;

1079:           if (islite) {
1080:             eid = EGlite_indexBodyTopo(body, edge);
1081:             PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
1082:           } else {
1083:             eid = EG_indexBodyTopo(body, edge);
1084:             PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
1085:           }

1087:           if (mtype == DEGENERATE) continue;
1088:           else ++Ner;
1089:           PetscCheck(Nv == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Edge %" PetscInt_FMT " has %" PetscInt_FMT " vertices != 2", eid, Nv);

1091:           for (v = 0; v < Nv; ++v) {
1092:             ego vertex = nobjs[v];

1094:             if (islite) {
1095:               id = EGlite_indexBodyTopo(body, vertex);
1096:             } else {
1097:               id = EG_indexBodyTopo(body, vertex);
1098:             }
1099:             points[v * 2] = id - 1;
1100:           }
1101:           {
1102:             PetscInt edgeNum;

1104:             PetscCall(PetscHMapIGet(edgeMap, eid - 1, &edgeNum));
1105:             points[1] = numVertices - newVertices + edgeNum;
1106:           }
1107:           /* EGADS loops are not oriented, but seem to be in order, so we must piece them together */
1108:           if (!nc) {
1109:             for (v = 0; v < Nv + 1; ++v) cone[nc++] = points[v];
1110:           } else {
1111:             if (cone[nc - 1] == points[0]) {
1112:               cone[nc++] = points[1];
1113:               if (cone[0] != points[2]) cone[nc++] = points[2];
1114:             } else if (cone[nc - 1] == points[2]) {
1115:               cone[nc++] = points[1];
1116:               if (cone[0] != points[0]) cone[nc++] = points[0];
1117:             } else if (cone[nc - 3] == points[0]) {
1118:               tmp          = cone[nc - 3];
1119:               cone[nc - 3] = cone[nc - 1];
1120:               cone[nc - 1] = tmp;
1121:               cone[nc++]   = points[1];
1122:               if (cone[0] != points[2]) cone[nc++] = points[2];
1123:             } else if (cone[nc - 3] == points[2]) {
1124:               tmp          = cone[nc - 3];
1125:               cone[nc - 3] = cone[nc - 1];
1126:               cone[nc - 1] = tmp;
1127:               cone[nc++]   = points[1];
1128:               if (cone[0] != points[0]) cone[nc++] = points[0];
1129:             } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Edge %d does not match its predecessor", eid);
1130:           }
1131:         }
1132:         PetscCheck(nc == 2 * Ner, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of corners %" PetscInt_FMT " != %" PetscInt_FMT, nc, 2 * Ner);
1133:         if (Ner == 4) cone[nc++] = numVertices - newVertices + numEdges + numQuads++;
1134:         PetscCheck(nc <= maxCorners, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of corners %" PetscInt_FMT " > %" PetscInt_FMT " max", nc, maxCorners);
1135:         /* Triangulate the loop */
1136:         switch (Ner) {
1137:         case 2: /* Bi-Segment -> 2 triangles */
1138:           Nt                           = 2;
1139:           cells[cOff * numCorners + 0] = cone[0];
1140:           cells[cOff * numCorners + 1] = cone[1];
1141:           cells[cOff * numCorners + 2] = cone[2];
1142:           ++cOff;
1143:           cells[cOff * numCorners + 0] = cone[0];
1144:           cells[cOff * numCorners + 1] = cone[2];
1145:           cells[cOff * numCorners + 2] = cone[3];
1146:           ++cOff;
1147:           break;
1148:         case 3: /* Triangle   -> 4 triangles */
1149:           Nt                           = 4;
1150:           cells[cOff * numCorners + 0] = cone[0];
1151:           cells[cOff * numCorners + 1] = cone[1];
1152:           cells[cOff * numCorners + 2] = cone[5];
1153:           ++cOff;
1154:           cells[cOff * numCorners + 0] = cone[1];
1155:           cells[cOff * numCorners + 1] = cone[2];
1156:           cells[cOff * numCorners + 2] = cone[3];
1157:           ++cOff;
1158:           cells[cOff * numCorners + 0] = cone[5];
1159:           cells[cOff * numCorners + 1] = cone[3];
1160:           cells[cOff * numCorners + 2] = cone[4];
1161:           ++cOff;
1162:           cells[cOff * numCorners + 0] = cone[1];
1163:           cells[cOff * numCorners + 1] = cone[3];
1164:           cells[cOff * numCorners + 2] = cone[5];
1165:           ++cOff;
1166:           break;
1167:         case 4: /* Quad       -> 8 triangles */
1168:           Nt                           = 8;
1169:           cells[cOff * numCorners + 0] = cone[0];
1170:           cells[cOff * numCorners + 1] = cone[1];
1171:           cells[cOff * numCorners + 2] = cone[7];
1172:           ++cOff;
1173:           cells[cOff * numCorners + 0] = cone[1];
1174:           cells[cOff * numCorners + 1] = cone[2];
1175:           cells[cOff * numCorners + 2] = cone[3];
1176:           ++cOff;
1177:           cells[cOff * numCorners + 0] = cone[3];
1178:           cells[cOff * numCorners + 1] = cone[4];
1179:           cells[cOff * numCorners + 2] = cone[5];
1180:           ++cOff;
1181:           cells[cOff * numCorners + 0] = cone[5];
1182:           cells[cOff * numCorners + 1] = cone[6];
1183:           cells[cOff * numCorners + 2] = cone[7];
1184:           ++cOff;
1185:           cells[cOff * numCorners + 0] = cone[8];
1186:           cells[cOff * numCorners + 1] = cone[1];
1187:           cells[cOff * numCorners + 2] = cone[3];
1188:           ++cOff;
1189:           cells[cOff * numCorners + 0] = cone[8];
1190:           cells[cOff * numCorners + 1] = cone[3];
1191:           cells[cOff * numCorners + 2] = cone[5];
1192:           ++cOff;
1193:           cells[cOff * numCorners + 0] = cone[8];
1194:           cells[cOff * numCorners + 1] = cone[5];
1195:           cells[cOff * numCorners + 2] = cone[7];
1196:           ++cOff;
1197:           cells[cOff * numCorners + 0] = cone[8];
1198:           cells[cOff * numCorners + 1] = cone[7];
1199:           cells[cOff * numCorners + 2] = cone[1];
1200:           ++cOff;
1201:           break;
1202:         default:
1203:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Loop %d has %d edges, which we do not support", lid, Ner);
1204:         }
1205:         if (debug) {
1206:           for (t = 0; t < Nt; ++t) {
1207:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "  LOOP Corner NODEs Triangle %d (", t));
1208:             for (c = 0; c < numCorners; ++c) {
1209:               if (c > 0) PetscCall(PetscPrintf(PETSC_COMM_SELF, ", "));
1210:               PetscCall(PetscPrintf(PETSC_COMM_SELF, "%d", cells[(cOff - Nt + t) * numCorners + c]));
1211:             }
1212:             PetscCall(PetscPrintf(PETSC_COMM_SELF, ")\n"));
1213:           }
1214:         }
1215:       }
1216:       if (islite) {
1217:         EGlite_free(lobjs);
1218:       } else {
1219:         EG_free(lobjs);
1220:       }
1221:     }
1222:   }
1223:   PetscCheck(cOff == numCells, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Count of total cells %d != %d previous count", cOff, numCells);
1224:   PetscCall(DMPlexCreateFromCellListPetsc(PETSC_COMM_WORLD, dim, numCells, numVertices, numCorners, PETSC_TRUE, cells, cdim, coords, &dm));
1225:   PetscCall(PetscFree3(coords, cells, cone));
1226:   PetscCall(PetscInfo(dm, " Total Number of Unique Cells    = %d (%d)\n", numCells, newCells));
1227:   PetscCall(PetscInfo(dm, " Total Number of Unique Vertices = %d (%d)\n", numVertices, newVertices));
1228:   /* Embed EGADS model in DM */
1229:   {
1230:     PetscContainer modelObj, contextObj;

1232:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &modelObj));
1233:     PetscCall(PetscContainerSetPointer(modelObj, model));
1234:     PetscCall(PetscContainerSetCtxDestroy(modelObj, (PetscCtxDestroyFn *)DMPlexEGADSDestroy_Private));
1235:     PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Model", (PetscObject)modelObj));
1236:     PetscCall(PetscContainerDestroy(&modelObj));

1238:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &contextObj));
1239:     PetscCall(PetscContainerSetPointer(contextObj, context));
1240:     PetscCall(PetscContainerSetCtxDestroy(contextObj, (PetscCtxDestroyFn *)DMPlexEGADSClose_Private));
1241:     PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Context", (PetscObject)contextObj));
1242:     PetscCall(PetscContainerDestroy(&contextObj));
1243:   }
1244:   /* Label points */
1245:   PetscCall(DMCreateLabel(dm, "EGADS Body ID"));
1246:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
1247:   PetscCall(DMCreateLabel(dm, "EGADS Face ID"));
1248:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
1249:   PetscCall(DMCreateLabel(dm, "EGADS Edge ID"));
1250:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
1251:   PetscCall(DMCreateLabel(dm, "EGADS Vertex ID"));
1252:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));
1253:   cOff = 0;
1254:   for (b = 0; b < nbodies; ++b) {
1255:     ego body = bodies[b];
1256:     int id, Nl, l;

1258:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
1259:     else PetscCall(EG_getBodyTopos(body, NULL, LOOP, &Nl, &lobjs));
1260:     for (l = 0; l < Nl; ++l) {
1261:       ego  loop = lobjs[l];
1262:       ego *fobjs;
1263:       int  lid, Nf, fid, Ner = 0, Ne, e, Nt = 0, t;

1265:       if (islite) {
1266:         lid = EGlite_indexBodyTopo(body, loop);
1267:         PetscCall(EGlite_getBodyTopos(body, loop, FACE, &Nf, &fobjs));
1268:       } else {
1269:         lid = EG_indexBodyTopo(body, loop);
1270:         PetscCall(EG_getBodyTopos(body, loop, FACE, &Nf, &fobjs));
1271:       }

1273:       PetscCheck(Nf <= 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "Loop %d has %d > 1 faces, which is not supported", lid, Nf);
1274:       if (islite) {
1275:         fid = EGlite_indexBodyTopo(body, fobjs[0]);
1276:         EGlite_free(fobjs);
1277:         PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
1278:       } else {
1279:         fid = EG_indexBodyTopo(body, fobjs[0]);
1280:         EG_free(fobjs);
1281:         PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &objs, &senses));
1282:       }

1284:       for (e = 0; e < Ne; ++e) {
1285:         ego             edge = objs[e];
1286:         int             eid, Nv, v;
1287:         PetscInt        points[3], support[2], numEdges, edgeNum;
1288:         const PetscInt *edges;

1290:         if (islite) {
1291:           eid = EGlite_indexBodyTopo(body, edge);
1292:           PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
1293:         } else {
1294:           eid = EG_indexBodyTopo(body, edge);
1295:           PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
1296:         }

1298:         if (mtype == DEGENERATE) continue;
1299:         else ++Ner;
1300:         for (v = 0; v < Nv; ++v) {
1301:           ego vertex = nobjs[v];

1303:           if (islite) {
1304:             id = EGlite_indexBodyTopo(body, vertex);
1305:           } else {
1306:             id = EG_indexBodyTopo(body, vertex);
1307:           }

1309:           PetscCall(DMLabelSetValue(edgeLabel, numCells + id - 1, eid));
1310:           points[v * 2] = numCells + id - 1;
1311:         }
1312:         PetscCall(PetscHMapIGet(edgeMap, eid - 1, &edgeNum));
1313:         points[1] = numCells + numVertices - newVertices + edgeNum;

1315:         PetscCall(DMLabelSetValue(edgeLabel, points[1], eid));
1316:         support[0] = points[0];
1317:         support[1] = points[1];
1318:         PetscCall(DMPlexGetJoin(dm, 2, support, &numEdges, &edges));
1319:         PetscCheck(numEdges == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Vertices (%d, %d) should only bound 1 edge, not %d", support[0], support[1], numEdges);
1320:         PetscCall(DMLabelSetValue(edgeLabel, edges[0], eid));
1321:         PetscCall(DMPlexRestoreJoin(dm, 2, support, &numEdges, &edges));
1322:         support[0] = points[1];
1323:         support[1] = points[2];
1324:         PetscCall(DMPlexGetJoin(dm, 2, support, &numEdges, &edges));
1325:         PetscCheck(numEdges == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Vertices (%d, %d) should only bound 1 edge, not %d", support[0], support[1], numEdges);
1326:         PetscCall(DMLabelSetValue(edgeLabel, edges[0], eid));
1327:         PetscCall(DMPlexRestoreJoin(dm, 2, support, &numEdges, &edges));
1328:       }
1329:       switch (Ner) {
1330:       case 2:
1331:         Nt = 2;
1332:         break;
1333:       case 3:
1334:         Nt = 4;
1335:         break;
1336:       case 4:
1337:         Nt = 8;
1338:         break;
1339:       default:
1340:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Loop with %d edges is unsupported", Ner);
1341:       }
1342:       for (t = 0; t < Nt; ++t) {
1343:         PetscCall(DMLabelSetValue(bodyLabel, cOff + t, b));
1344:         PetscCall(DMLabelSetValue(faceLabel, cOff + t, fid));
1345:       }
1346:       cOff += Nt;
1347:     }
1348:     if (islite) {
1349:       EGlite_free(lobjs);
1350:     } else {
1351:       EG_free(lobjs);
1352:     }
1353:   }
1354:   PetscCall(PetscHMapIDestroy(&edgeMap));
1355:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1356:   for (c = cStart; c < cEnd; ++c) {
1357:     PetscInt *closure = NULL;
1358:     PetscInt  clSize, cl, bval, fval;

1360:     PetscCall(DMPlexGetTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
1361:     PetscCall(DMLabelGetValue(bodyLabel, c, &bval));
1362:     PetscCall(DMLabelGetValue(faceLabel, c, &fval));
1363:     for (cl = 0; cl < clSize * 2; cl += 2) {
1364:       PetscCall(DMLabelSetValue(bodyLabel, closure[cl], bval));
1365:       PetscCall(DMLabelSetValue(faceLabel, closure[cl], fval));
1366:     }
1367:     PetscCall(DMPlexRestoreTransitiveClosure(dm, c, PETSC_TRUE, &clSize, &closure));
1368:   }
1369:   *newdm = dm;
1370:   PetscFunctionReturn(PETSC_SUCCESS);
1371: }

1373: PetscErrorCode DMPlexCreateGeom(MPI_Comm comm, ego context, ego model, DM *newdm, PetscBool islite)
1374: {
1375:   // EGADS variables
1376:   ego geom, *bodies, *mobjs, *fobjs, *lobjs, *eobjs, *nobjs;
1377:   ego topRef, prev, next;
1378:   int oclass, mtype, nbodies, *senses, *lSenses, *eSenses;
1379:   int b;
1380:   // PETSc variables
1381:   DM              dm;
1382:   DMLabel         bodyLabel, faceLabel, edgeLabel, vertexLabel;
1383:   PetscHMapI      edgeMap = NULL, bodyIndexMap = NULL, bodyVertexMap = NULL, bodyEdgeMap = NULL, bodyFaceMap = NULL, bodyEdgeGlobalMap = NULL;
1384:   PetscInt        dim = -1, cdim = -1, numCorners = 0, numVertices = 0, numEdges = 0, numFaces = 0, numCells = 0, edgeCntr = 0;
1385:   PetscInt        cellCntr = 0, numPoints = 0;
1386:   PetscInt       *cells  = NULL;
1387:   const PetscInt *cone   = NULL;
1388:   PetscReal      *coords = NULL;
1389:   PetscMPIInt     rank;

1391:   PetscFunctionBeginUser;
1392:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1393:   if (rank == 0) {
1394:     // Generate PETSc DMPlex
1395:     //  Get all Nodes in model, record coordinates in a correctly formatted array
1396:     //  Cycle through bodies, cycle through loops, recorde NODE IDs in a correctly formatted array
1397:     //  We need to uniformly refine the initial geometry to guarantee a valid mesh

1399:     // Calculate cell and vertex sizes
1400:     if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));
1401:     else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));
1402:     PetscCall(PetscHMapICreate(&edgeMap));
1403:     PetscCall(PetscHMapICreate(&bodyIndexMap));
1404:     PetscCall(PetscHMapICreate(&bodyVertexMap));
1405:     PetscCall(PetscHMapICreate(&bodyEdgeMap));
1406:     PetscCall(PetscHMapICreate(&bodyEdgeGlobalMap));
1407:     PetscCall(PetscHMapICreate(&bodyFaceMap));

1409:     for (b = 0; b < nbodies; ++b) {
1410:       ego           body = bodies[b];
1411:       int           Nf, Ne, Nv;
1412:       PetscHashIter BIiter, BViter, BEiter, BEGiter, BFiter, EMiter;
1413:       PetscBool     BIfound, BVfound, BEfound, BEGfound, BFfound, EMfound;

1415:       PetscCall(PetscHMapIFind(bodyIndexMap, b, &BIiter, &BIfound));
1416:       PetscCall(PetscHMapIFind(bodyVertexMap, b, &BViter, &BVfound));
1417:       PetscCall(PetscHMapIFind(bodyEdgeMap, b, &BEiter, &BEfound));
1418:       PetscCall(PetscHMapIFind(bodyEdgeGlobalMap, b, &BEGiter, &BEGfound));
1419:       PetscCall(PetscHMapIFind(bodyFaceMap, b, &BFiter, &BFfound));

1421:       if (!BIfound) PetscCall(PetscHMapISet(bodyIndexMap, b, numFaces + numEdges + numVertices));
1422:       if (!BVfound) PetscCall(PetscHMapISet(bodyVertexMap, b, numVertices));
1423:       if (!BEfound) PetscCall(PetscHMapISet(bodyEdgeMap, b, numEdges));
1424:       if (!BEGfound) PetscCall(PetscHMapISet(bodyEdgeGlobalMap, b, edgeCntr));
1425:       if (!BFfound) PetscCall(PetscHMapISet(bodyFaceMap, b, numFaces));

1427:       if (islite) {
1428:         PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1429:         PetscCall(EGlite_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
1430:         PetscCall(EGlite_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
1431:         EGlite_free(fobjs);
1432:         EGlite_free(eobjs);
1433:         EGlite_free(nobjs);
1434:       } else {
1435:         PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1436:         PetscCall(EG_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
1437:         PetscCall(EG_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
1438:         EG_free(fobjs);
1439:         EG_free(eobjs);
1440:         EG_free(nobjs);
1441:       }

1443:       // Remove DEGENERATE EDGES from Edge count
1444:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
1445:       else PetscCall(EG_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));

1447:       int Netemp = 0;
1448:       for (int e = 0; e < Ne; ++e) {
1449:         ego edge = eobjs[e];
1450:         int eid;

1452:         if (islite) {
1453:           PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1454:           eid = EGlite_indexBodyTopo(body, edge);
1455:         } else {
1456:           PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1457:           eid = EG_indexBodyTopo(body, edge);
1458:         }

1460:         PetscCall(PetscHMapIFind(edgeMap, edgeCntr + eid - 1, &EMiter, &EMfound));
1461:         if (mtype == DEGENERATE) {
1462:           if (!EMfound) PetscCall(PetscHMapISet(edgeMap, edgeCntr + eid - 1, -1));
1463:         } else {
1464:           ++Netemp;
1465:           if (!EMfound) PetscCall(PetscHMapISet(edgeMap, edgeCntr + eid - 1, Netemp));
1466:         }
1467:       }
1468:       if (islite) {
1469:         EGlite_free(eobjs);
1470:       } else {
1471:         EG_free(eobjs);
1472:       }

1474:       // Determine Number of Cells
1475:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1476:       else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));

1478:       for (int f = 0; f < Nf; ++f) {
1479:         ego face     = fobjs[f];
1480:         int edgeTemp = 0;

1482:         if (islite) PetscCall(EGlite_getBodyTopos(body, face, EDGE, &Ne, &eobjs));
1483:         else PetscCall(EG_getBodyTopos(body, face, EDGE, &Ne, &eobjs));

1485:         for (int e = 0; e < Ne; ++e) {
1486:           ego edge = eobjs[e];

1488:           if (islite) {
1489:             PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1490:           } else {
1491:             PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1492:           }
1493:           if (mtype != DEGENERATE) ++edgeTemp;
1494:         }
1495:         numCells += (2 * edgeTemp);
1496:         if (islite) {
1497:           EGlite_free(eobjs);
1498:         } else {
1499:           EG_free(eobjs);
1500:         }
1501:       }
1502:       if (islite) {
1503:         EGlite_free(fobjs);
1504:       } else {
1505:         EG_free(fobjs);
1506:       }

1508:       numFaces += Nf;
1509:       numEdges += Netemp;
1510:       numVertices += Nv;
1511:       edgeCntr += Ne;
1512:     }

1514:     // Set up basic DMPlex parameters
1515:     dim        = 2;                                 // Assumes 3D Models :: Need to handle 2D models in the future
1516:     cdim       = 3;                                 // Assumes 3D Models :: Need to update to handle 2D models in future
1517:     numCorners = 3;                                 // Split Faces into triangles
1518:     numPoints  = numVertices + numEdges + numFaces; // total number of coordinate points

1520:     PetscCall(PetscMalloc2(numPoints * cdim, &coords, numCells * numCorners, &cells));

1522:     // Get Vertex Coordinates and Set up Cells
1523:     for (b = 0; b < nbodies; ++b) {
1524:       ego           body = bodies[b];
1525:       int           Nf, Ne, Nv;
1526:       PetscInt      bodyVertexIndexStart, bodyEdgeIndexStart, bodyEdgeGlobalIndexStart, bodyFaceIndexStart;
1527:       PetscHashIter BViter, BEiter, BEGiter, BFiter, EMiter;
1528:       PetscBool     BVfound, BEfound, BEGfound, BFfound, EMfound;

1530:       // Vertices on Current Body
1531:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));
1532:       else PetscCall(EG_getBodyTopos(body, NULL, NODE, &Nv, &nobjs));

1534:       PetscCall(PetscHMapIFind(bodyVertexMap, b, &BViter, &BVfound));
1535:       PetscCheck(BVfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %" PetscInt_FMT " not found in bodyVertexMap", b);
1536:       PetscCall(PetscHMapIGet(bodyVertexMap, b, &bodyVertexIndexStart));

1538:       for (int v = 0; v < Nv; ++v) {
1539:         ego    vertex = nobjs[v];
1540:         double limits[4];
1541:         int    id, unused;

1543:         if (islite) {
1544:           PetscCall(EGlite_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
1545:           id = EGlite_indexBodyTopo(body, vertex);
1546:         } else {
1547:           PetscCall(EG_getTopology(vertex, &geom, &oclass, &mtype, limits, &unused, &mobjs, &senses));
1548:           id = EG_indexBodyTopo(body, vertex);
1549:         }

1551:         coords[(bodyVertexIndexStart + id - 1) * cdim + 0] = limits[0];
1552:         coords[(bodyVertexIndexStart + id - 1) * cdim + 1] = limits[1];
1553:         coords[(bodyVertexIndexStart + id - 1) * cdim + 2] = limits[2];
1554:       }
1555:       if (islite) {
1556:         EGlite_free(nobjs);
1557:       } else {
1558:         EG_free(nobjs);
1559:       }

1561:       // Edge Midpoint Vertices on Current Body
1562:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));
1563:       else PetscCall(EG_getBodyTopos(body, NULL, EDGE, &Ne, &eobjs));

1565:       PetscCall(PetscHMapIFind(bodyEdgeMap, b, &BEiter, &BEfound));
1566:       PetscCheck(BEfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %" PetscInt_FMT " not found in bodyEdgeMap", b);
1567:       PetscCall(PetscHMapIGet(bodyEdgeMap, b, &bodyEdgeIndexStart));

1569:       PetscCall(PetscHMapIFind(bodyEdgeGlobalMap, b, &BEGiter, &BEGfound));
1570:       PetscCheck(BEGfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %" PetscInt_FMT " not found in bodyEdgeGlobalMap", b);
1571:       PetscCall(PetscHMapIGet(bodyEdgeGlobalMap, b, &bodyEdgeGlobalIndexStart));

1573:       for (int e = 0; e < Ne; ++e) {
1574:         ego    edge = eobjs[e];
1575:         double range[2], avgt[1], cntrPnt[9];
1576:         int    eid, eOffset;
1577:         int    periodic;

1579:         if (islite) {
1580:           PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1581:         } else {
1582:           PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1583:         }
1584:         if (mtype == DEGENERATE) continue;

1586:         if (islite) {
1587:           eid = EGlite_indexBodyTopo(body, edge);
1588:         } else {
1589:           eid = EG_indexBodyTopo(body, edge);
1590:         }
1591:         // get relative offset from globalEdgeID Vector
1592:         PetscCall(PetscHMapIFind(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &EMiter, &EMfound));
1593:         PetscCheck(EMfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Edge %" PetscInt_FMT " not found in edgeMap", bodyEdgeGlobalIndexStart + eid - 1);
1594:         PetscCall(PetscHMapIGet(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &eOffset));

1596:         if (islite) {
1597:           PetscCall(EGlite_getRange(edge, range, &periodic));
1598:         } else {
1599:           PetscCall(EG_getRange(edge, range, &periodic));
1600:         }
1601:         avgt[0] = (range[0] + range[1]) / 2.;

1603:         if (islite) {
1604:           PetscCall(EGlite_evaluate(edge, avgt, cntrPnt));
1605:         } else {
1606:           PetscCall(EG_evaluate(edge, avgt, cntrPnt));
1607:         }
1608:         coords[(numVertices + bodyEdgeIndexStart + eOffset - 1) * cdim + 0] = cntrPnt[0];
1609:         coords[(numVertices + bodyEdgeIndexStart + eOffset - 1) * cdim + 1] = cntrPnt[1];
1610:         coords[(numVertices + bodyEdgeIndexStart + eOffset - 1) * cdim + 2] = cntrPnt[2];
1611:       }
1612:       if (islite) {
1613:         EGlite_free(eobjs);
1614:       } else {
1615:         EG_free(eobjs);
1616:       }
1617:       // Face Midpoint Vertices on Current Body
1618:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1619:       else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1620:       PetscCall(PetscHMapIFind(bodyFaceMap, b, &BFiter, &BFfound));
1621:       PetscCheck(BFfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %d not found in bodyFaceMap", b);
1622:       PetscCall(PetscHMapIGet(bodyFaceMap, b, &bodyFaceIndexStart));

1624:       for (int f = 0; f < Nf; ++f) {
1625:         ego    face = fobjs[f];
1626:         double range[4], avgUV[2], cntrPnt[18];
1627:         int    peri, id;

1629:         if (islite) {
1630:           id = EGlite_indexBodyTopo(body, face);
1631:           PetscCall(EGlite_getRange(face, range, &peri));
1632:         } else {
1633:           id = EG_indexBodyTopo(body, face);
1634:           PetscCall(EG_getRange(face, range, &peri));
1635:         }

1637:         avgUV[0] = (range[0] + range[1]) / 2.;
1638:         avgUV[1] = (range[2] + range[3]) / 2.;

1640:         if (islite) {
1641:           PetscCall(EGlite_evaluate(face, avgUV, cntrPnt));
1642:         } else {
1643:           PetscCall(EG_evaluate(face, avgUV, cntrPnt));
1644:         }

1646:         coords[(numVertices + numEdges + bodyFaceIndexStart + id - 1) * cdim + 0] = cntrPnt[0];
1647:         coords[(numVertices + numEdges + bodyFaceIndexStart + id - 1) * cdim + 1] = cntrPnt[1];
1648:         coords[(numVertices + numEdges + bodyFaceIndexStart + id - 1) * cdim + 2] = cntrPnt[2];
1649:       }
1650:       if (islite) {
1651:         EGlite_free(fobjs);
1652:       } else {
1653:         EG_free(fobjs);
1654:       }

1656:       // Define Cells :: Note - This could be incorporated in the Face Midpoint Vertices Loop but was kept separate for clarity
1657:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1658:       else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1659:       for (int f = 0; f < Nf; ++f) {
1660:         ego face = fobjs[f];
1661:         int fID, midFaceID, midPntID, startID, endID, Nl;

1663:         if (islite) {
1664:           fID = EGlite_indexBodyTopo(body, face);
1665:         } else {
1666:           fID = EG_indexBodyTopo(body, face);
1667:         }

1669:         midFaceID = numVertices + numEdges + bodyFaceIndexStart + fID - 1;
1670:         // Must Traverse Loop to ensure we have all necessary information like the sense (+/- 1) of the edges.
1671:         // TODO :: Only handles single loop faces (No holes). The choices for handling multiloop faces are:
1672:         //            1) Use the DMPlexCreateGeomFromFile() with the -dm_plex_geom_with_tess = 1 option.
1673:         //               This will use a default EGADS tessellation as an initial surface mesh.
1674:         //            2) Create the initial surface mesh via a 2D mesher :: Currently not available (?future?)
1675:         //               May I suggest the XXXX as a starting point?

1677:         if (islite) PetscCall(EGlite_getTopology(face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lSenses));
1678:         else PetscCall(EG_getTopology(face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lSenses));

1680:         PetscCheck(Nl == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Face has %" PetscInt_FMT " Loops. Can only handle Faces with 1 Loop. Please use --dm_plex_geom_with_tess = 1 Option", Nl);
1681:         for (int l = 0; l < Nl; ++l) {
1682:           ego loop = lobjs[l];

1684:           if (islite) PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &eSenses));
1685:           else PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &eSenses));

1687:           for (int e = 0; e < Ne; ++e) {
1688:             ego edge = eobjs[e];
1689:             int eid, eOffset;

1691:             if (islite) {
1692:               PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1693:               eid = EGlite_indexBodyTopo(body, edge);
1694:             } else {
1695:               PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1696:               eid = EG_indexBodyTopo(body, edge);
1697:             }
1698:             if (mtype == DEGENERATE) continue;

1700:             // get relative offset from globalEdgeID Vector
1701:             PetscCall(PetscHMapIFind(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &EMiter, &EMfound));
1702:             PetscCheck(EMfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Edge %" PetscInt_FMT " of Body %" PetscInt_FMT " not found in edgeMap. Global Edge ID :: %" PetscInt_FMT, eid, b, bodyEdgeGlobalIndexStart + eid - 1);
1703:             PetscCall(PetscHMapIGet(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &eOffset));

1705:             midPntID = numVertices + bodyEdgeIndexStart + eOffset - 1;

1707:             if (islite) PetscCall(EGlite_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));
1708:             else PetscCall(EG_getTopology(edge, &geom, &oclass, &mtype, NULL, &Nv, &nobjs, &senses));

1710:             if (eSenses[e] > 0) {
1711:               if (islite) {
1712:                 startID = EGlite_indexBodyTopo(body, nobjs[0]);
1713:                 endID   = EGlite_indexBodyTopo(body, nobjs[1]);
1714:               } else {
1715:                 startID = EG_indexBodyTopo(body, nobjs[0]);
1716:                 endID   = EG_indexBodyTopo(body, nobjs[1]);
1717:               }
1718:             } else {
1719:               if (islite) {
1720:                 startID = EGlite_indexBodyTopo(body, nobjs[1]);
1721:                 endID   = EGlite_indexBodyTopo(body, nobjs[0]);
1722:               } else {
1723:                 startID = EG_indexBodyTopo(body, nobjs[1]);
1724:                 endID   = EG_indexBodyTopo(body, nobjs[0]);
1725:               }
1726:             }

1728:             // Define 2 Cells per Edge with correct orientation
1729:             cells[cellCntr * numCorners + 0] = midFaceID;
1730:             cells[cellCntr * numCorners + 1] = bodyVertexIndexStart + startID - 1;
1731:             cells[cellCntr * numCorners + 2] = midPntID;

1733:             cells[cellCntr * numCorners + 3] = midFaceID;
1734:             cells[cellCntr * numCorners + 4] = midPntID;
1735:             cells[cellCntr * numCorners + 5] = bodyVertexIndexStart + endID - 1;

1737:             cellCntr = cellCntr + 2;
1738:           }
1739:         }
1740:       }
1741:       if (islite) {
1742:         EGlite_free(fobjs);
1743:       } else {
1744:         EG_free(fobjs);
1745:       }
1746:     }
1747:   }

1749:   // Generate DMPlex
1750:   PetscCall(DMPlexCreateFromCellListPetsc(PETSC_COMM_WORLD, dim, numCells, numPoints, numCorners, PETSC_TRUE, cells, cdim, coords, &dm));
1751:   PetscCall(PetscFree2(coords, cells));
1752:   PetscCall(PetscInfo(dm, " Total Number of Unique Cells    = %" PetscInt_FMT " \n", numCells));
1753:   PetscCall(PetscInfo(dm, " Total Number of Unique Vertices = %" PetscInt_FMT " \n", numVertices));

1755:   // Embed EGADS model in DM
1756:   {
1757:     PetscContainer modelObj, contextObj;

1759:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &modelObj));
1760:     PetscCall(PetscContainerSetPointer(modelObj, model));
1761:     if (islite) {
1762:       PetscCall(PetscContainerSetCtxDestroy(modelObj, DMPlexEGADSliteDestroy_Private));
1763:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADSlite Model", (PetscObject)modelObj));
1764:     } else {
1765:       PetscCall(PetscContainerSetCtxDestroy(modelObj, DMPlexEGADSDestroy_Private));
1766:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Model", (PetscObject)modelObj));
1767:     }
1768:     PetscCall(PetscContainerDestroy(&modelObj));

1770:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &contextObj));
1771:     PetscCall(PetscContainerSetPointer(contextObj, context));

1773:     if (islite) {
1774:       PetscCall(PetscContainerSetCtxDestroy(contextObj, DMPlexEGADSliteClose_Private));
1775:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADSlite Context", (PetscObject)contextObj));
1776:     } else {
1777:       PetscCall(PetscContainerSetCtxDestroy(contextObj, DMPlexEGADSClose_Private));
1778:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Context", (PetscObject)contextObj));
1779:     }
1780:     PetscCall(PetscContainerDestroy(&contextObj));
1781:   }
1782:   // Label points
1783:   PetscInt nStart, nEnd;

1785:   PetscCall(DMCreateLabel(dm, "EGADS Body ID"));
1786:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
1787:   PetscCall(DMCreateLabel(dm, "EGADS Face ID"));
1788:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
1789:   PetscCall(DMCreateLabel(dm, "EGADS Edge ID"));
1790:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
1791:   PetscCall(DMCreateLabel(dm, "EGADS Vertex ID"));
1792:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

1794:   PetscCall(DMPlexGetHeightStratum(dm, 2, &nStart, &nEnd));

1796:   cellCntr = 0;
1797:   for (b = 0; b < nbodies; ++b) {
1798:     ego           body = bodies[b];
1799:     int           Nv, Ne, Nf;
1800:     PetscInt      bodyVertexIndexStart, bodyEdgeIndexStart, bodyEdgeGlobalIndexStart, bodyFaceIndexStart;
1801:     PetscHashIter BViter, BEiter, BEGiter, BFiter, EMiter;
1802:     PetscBool     BVfound, BEfound, BEGfound, BFfound, EMfound;

1804:     PetscCall(PetscHMapIFind(bodyVertexMap, b, &BViter, &BVfound));
1805:     PetscCheck(BVfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %d not found in bodyVertexMap", b);
1806:     PetscCall(PetscHMapIGet(bodyVertexMap, b, &bodyVertexIndexStart));

1808:     PetscCall(PetscHMapIFind(bodyEdgeMap, b, &BEiter, &BEfound));
1809:     PetscCheck(BEfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %d not found in bodyEdgeMap", b);
1810:     PetscCall(PetscHMapIGet(bodyEdgeMap, b, &bodyEdgeIndexStart));

1812:     PetscCall(PetscHMapIFind(bodyFaceMap, b, &BFiter, &BFfound));
1813:     PetscCheck(BFfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %d not found in bodyFaceMap", b);
1814:     PetscCall(PetscHMapIGet(bodyFaceMap, b, &bodyFaceIndexStart));

1816:     PetscCall(PetscHMapIFind(bodyEdgeGlobalMap, b, &BEGiter, &BEGfound));
1817:     PetscCheck(BEGfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %d not found in bodyEdgeGlobalMap", b);
1818:     PetscCall(PetscHMapIGet(bodyEdgeGlobalMap, b, &bodyEdgeGlobalIndexStart));

1820:     if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
1821:     else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));

1823:     for (int f = 0; f < Nf; ++f) {
1824:       ego face = fobjs[f];
1825:       int fID, Nl;

1827:       if (islite) {
1828:         fID = EGlite_indexBodyTopo(body, face);
1829:         PetscCall(EGlite_getBodyTopos(body, face, LOOP, &Nl, &lobjs));
1830:       } else {
1831:         fID = EG_indexBodyTopo(body, face);
1832:         PetscCall(EG_getBodyTopos(body, face, LOOP, &Nl, &lobjs));
1833:       }

1835:       for (int l = 0; l < Nl; ++l) {
1836:         ego loop = lobjs[l];
1837:         int lid;

1839:         if (islite) {
1840:           lid = EGlite_indexBodyTopo(body, loop);
1841:         } else {
1842:           lid = EG_indexBodyTopo(body, loop);
1843:         }

1845:         PetscCheck(Nl == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "Loop %" PetscInt_FMT " has %" PetscInt_FMT " > 1 faces, which is not supported", lid, Nf);

1847:         if (islite) PetscCall(EGlite_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &eSenses));
1848:         else PetscCall(EG_getTopology(loop, &geom, &oclass, &mtype, NULL, &Ne, &eobjs, &eSenses));

1850:         for (int e = 0; e < Ne; ++e) {
1851:           ego edge = eobjs[e];
1852:           int eid, eOffset;

1854:           // Skip DEGENERATE Edges
1855:           if (islite) {
1856:             PetscCall(EGlite_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1857:           } else {
1858:             PetscCall(EG_getInfo(edge, &oclass, &mtype, &topRef, &prev, &next));
1859:           }

1861:           if (mtype == DEGENERATE) continue;

1863:           if (islite) {
1864:             eid = EGlite_indexBodyTopo(body, edge);
1865:           } else {
1866:             eid = EG_indexBodyTopo(body, edge);
1867:           }

1869:           // get relative offset from globalEdgeID Vector
1870:           PetscCall(PetscHMapIFind(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &EMiter, &EMfound));
1871:           PetscCheck(EMfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Edge %" PetscInt_FMT " of Body %" PetscInt_FMT " not found in edgeMap. Global Edge ID :: %" PetscInt_FMT, eid, b, bodyEdgeGlobalIndexStart + eid - 1);
1872:           PetscCall(PetscHMapIGet(edgeMap, bodyEdgeGlobalIndexStart + eid - 1, &eOffset));

1874:           if (islite) PetscCall(EGlite_getBodyTopos(body, edge, NODE, &Nv, &nobjs));
1875:           else PetscCall(EG_getBodyTopos(body, edge, NODE, &Nv, &nobjs));

1877:           for (int v = 0; v < Nv; ++v) {
1878:             ego vertex = nobjs[v];
1879:             int vID;

1881:             if (islite) {
1882:               vID = EGlite_indexBodyTopo(body, vertex);
1883:             } else {
1884:               vID = EG_indexBodyTopo(body, vertex);
1885:             }

1887:             PetscCall(DMLabelSetValue(bodyLabel, nStart + bodyVertexIndexStart + vID - 1, b));
1888:             PetscCall(DMLabelSetValue(vertexLabel, nStart + bodyVertexIndexStart + vID - 1, vID));
1889:           }
1890:           if (islite) {
1891:             EGlite_free(nobjs);
1892:           } else {
1893:             EG_free(nobjs);
1894:           }

1896:           PetscCall(DMLabelSetValue(bodyLabel, nStart + numVertices + bodyEdgeIndexStart + eOffset - 1, b));
1897:           PetscCall(DMLabelSetValue(edgeLabel, nStart + numVertices + bodyEdgeIndexStart + eOffset - 1, eid));

1899:           // Define Cell faces
1900:           for (int jj = 0; jj < 2; ++jj) {
1901:             PetscCall(DMLabelSetValue(bodyLabel, cellCntr, b));
1902:             PetscCall(DMLabelSetValue(faceLabel, cellCntr, fID));
1903:             PetscCall(DMPlexGetCone(dm, cellCntr, &cone));

1905:             PetscCall(DMLabelSetValue(bodyLabel, cone[0], b));
1906:             PetscCall(DMLabelSetValue(faceLabel, cone[0], fID));

1908:             PetscCall(DMLabelSetValue(bodyLabel, cone[1], b));
1909:             PetscCall(DMLabelSetValue(edgeLabel, cone[1], eid));

1911:             PetscCall(DMLabelSetValue(bodyLabel, cone[2], b));
1912:             PetscCall(DMLabelSetValue(faceLabel, cone[2], fID));

1914:             cellCntr = cellCntr + 1;
1915:           }
1916:         }
1917:       }
1918:       if (islite) {
1919:         EGlite_free(lobjs);
1920:       } else {
1921:         EG_free(lobjs);
1922:       }

1924:       PetscCall(DMLabelSetValue(bodyLabel, nStart + numVertices + numEdges + bodyFaceIndexStart + fID - 1, b));
1925:       PetscCall(DMLabelSetValue(faceLabel, nStart + numVertices + numEdges + bodyFaceIndexStart + fID - 1, fID));
1926:     }
1927:     if (islite) {
1928:       EGlite_free(fobjs);
1929:     } else {
1930:       EG_free(fobjs);
1931:     }
1932:   }

1934:   PetscCall(PetscHMapIDestroy(&edgeMap));
1935:   PetscCall(PetscHMapIDestroy(&bodyIndexMap));
1936:   PetscCall(PetscHMapIDestroy(&bodyVertexMap));
1937:   PetscCall(PetscHMapIDestroy(&bodyEdgeMap));
1938:   PetscCall(PetscHMapIDestroy(&bodyEdgeGlobalMap));
1939:   PetscCall(PetscHMapIDestroy(&bodyFaceMap));

1941:   *newdm = dm;
1942:   PetscFunctionReturn(PETSC_SUCCESS);
1943: }

1945: PetscErrorCode DMPlexCreateGeom_Tess_Internal(MPI_Comm comm, ego context, ego model, DM *newdm, PetscBool islite)
1946: {
1947:   /* EGADSlite variables */
1948:   ego    geom, *bodies, *fobjs;
1949:   int    b, oclass, mtype, nbodies, *senses;
1950:   int    totalNumTris = 0, totalNumPoints = 0;
1951:   double boundBox[6] = {0., 0., 0., 0., 0., 0.}, tessSize;
1952:   /* PETSc variables */
1953:   DM              dm;
1954:   DMLabel         bodyLabel, faceLabel, edgeLabel, vertexLabel;
1955:   PetscHMapI      pointIndexStartMap = NULL, triIndexStartMap = NULL, pTypeLabelMap = NULL, pIndexLabelMap = NULL;
1956:   PetscHMapI      pBodyIndexLabelMap = NULL, triFaceIDLabelMap = NULL, triBodyIDLabelMap = NULL;
1957:   PetscInt        dim = -1, cdim = -1, numCorners = 0, counter = 0;
1958:   PetscInt       *cells  = NULL;
1959:   const PetscInt *cone   = NULL;
1960:   PetscReal      *coords = NULL;
1961:   PetscMPIInt     rank;

1963:   PetscFunctionBeginUser;
1964:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1965:   if (rank == 0) {
1966:     // Generate PETSc DMPlex from EGADSlite created Tessellation of geometry

1968:     // Calculate cell and vertex sizes
1969:     if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));
1970:     else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &nbodies, &bodies, &senses));

1972:     PetscCall(PetscHMapICreate(&pointIndexStartMap));
1973:     PetscCall(PetscHMapICreate(&triIndexStartMap));
1974:     PetscCall(PetscHMapICreate(&pTypeLabelMap));
1975:     PetscCall(PetscHMapICreate(&pIndexLabelMap));
1976:     PetscCall(PetscHMapICreate(&pBodyIndexLabelMap));
1977:     PetscCall(PetscHMapICreate(&triFaceIDLabelMap));
1978:     PetscCall(PetscHMapICreate(&triBodyIDLabelMap));

1980:     /* Create Tessellation of Bodies */
1981:     ego *tessArray;

1983:     PetscCall(PetscMalloc1(nbodies, &tessArray));
1984:     for (b = 0; b < nbodies; ++b) {
1985:       ego           body      = bodies[b];
1986:       double        params[3] = {0.0, 0.0, 0.0}; // Parameters for Tessellation
1987:       int           Nf, bodyNumPoints = 0, bodyNumTris = 0;
1988:       PetscHashIter PISiter, TISiter;
1989:       PetscBool     PISfound, TISfound;

1991:       /* Store Start Index for each Body's Point and Tris */
1992:       PetscCall(PetscHMapIFind(pointIndexStartMap, b, &PISiter, &PISfound));
1993:       PetscCall(PetscHMapIFind(triIndexStartMap, b, &TISiter, &TISfound));

1995:       if (!PISfound) PetscCall(PetscHMapISet(pointIndexStartMap, b, totalNumPoints));
1996:       if (!TISfound) PetscCall(PetscHMapISet(triIndexStartMap, b, totalNumTris));

1998:       /* Calculate Tessellation parameters based on Bounding Box */
1999:       /* Get Bounding Box Dimensions of the BODY */
2000:       if (islite) PetscCall(EGlite_getBoundingBox(body, boundBox));
2001:       else PetscCall(EG_getBoundingBox(body, boundBox));

2003:       tessSize = boundBox[3] - boundBox[0];
2004:       if (tessSize < boundBox[4] - boundBox[1]) tessSize = boundBox[4] - boundBox[1];
2005:       if (tessSize < boundBox[5] - boundBox[2]) tessSize = boundBox[5] - boundBox[2];

2007:       // TODO :: May want to give users tessellation parameter options //
2008:       params[0] = 0.0250 * tessSize;
2009:       params[1] = 0.0075 * tessSize;
2010:       params[2] = 15.0;

2012:       if (islite) {
2013:         PetscCall(EGlite_makeTessBody(body, params, &tessArray[b]));
2014:         PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
2015:       } else {
2016:         PetscCall(EG_makeTessBody(body, params, &tessArray[b]));
2017:         PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
2018:       }

2020:       for (int f = 0; f < Nf; ++f) {
2021:         ego           face = fobjs[f];
2022:         int           len, fID, ntris;
2023:         const int    *ptype, *pindex, *ptris, *ptric;
2024:         const double *pxyz, *puv;

2026:         // Get Face ID //
2027:         if (islite) {
2028:           fID = EGlite_indexBodyTopo(body, face);
2029:         } else {
2030:           fID = EG_indexBodyTopo(body, face);
2031:         }

2033:         // Checkout the Surface Tessellation //
2034:         if (islite) {
2035:           PetscCall(EGlite_getTessFace(tessArray[b], fID, &len, &pxyz, &puv, &ptype, &pindex, &ntris, &ptris, &ptric));
2036:         } else {
2037:           PetscCall(EG_getTessFace(tessArray[b], fID, &len, &pxyz, &puv, &ptype, &pindex, &ntris, &ptris, &ptric));
2038:         }

2040:         // Determine total number of triangle cells in the tessellation //
2041:         bodyNumTris += (int)ntris;

2043:         // Check out the point index and coordinate //
2044:         for (int p = 0; p < len; ++p) {
2045:           int global;

2047:           if (islite) {
2048:             PetscCall(EGlite_localToGlobal(tessArray[b], fID, p + 1, &global));
2049:           } else {
2050:             PetscCall(EG_localToGlobal(tessArray[b], fID, p + 1, &global));
2051:           }

2053:           // Determine the total number of points in the tessellation //
2054:           bodyNumPoints = PetscMax(bodyNumPoints, global);
2055:         }
2056:       }
2057:       if (islite) {
2058:         EGlite_free(fobjs);
2059:       } else {
2060:         EG_free(fobjs);
2061:       }

2063:       totalNumPoints += bodyNumPoints;
2064:       totalNumTris += bodyNumTris;
2065:     }

2067:     dim        = 2;
2068:     cdim       = 3;
2069:     numCorners = 3;

2071:     /* NEED TO DEFINE MATRICES/VECTORS TO STORE GEOM REFERENCE DATA   */
2072:     /* Fill in below and use to define DMLabels after DMPlex creation */
2073:     PetscCall(PetscMalloc2(totalNumPoints * cdim, &coords, totalNumTris * numCorners, &cells));

2075:     for (b = 0; b < nbodies; ++b) {
2076:       ego           body = bodies[b];
2077:       int           Nf;
2078:       PetscInt      pointIndexStart;
2079:       PetscHashIter PISiter;
2080:       PetscBool     PISfound;

2082:       PetscCall(PetscHMapIFind(pointIndexStartMap, b, &PISiter, &PISfound));
2083:       PetscCheck(PISfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "Body %" PetscInt_FMT " not found in pointIndexStartMap", b);
2084:       PetscCall(PetscHMapIGet(pointIndexStartMap, b, &pointIndexStart));

2086:       if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
2087:       else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));

2089:       for (int f = 0; f < Nf; ++f) {
2090:         /* Get Face Object */
2091:         ego           face = fobjs[f];
2092:         int           len, fID, ntris;
2093:         const int    *ptype, *pindex, *ptris, *ptric;
2094:         const double *pxyz, *puv;

2096:         /* Get Face ID */
2097:         if (islite) {
2098:           fID = EGlite_indexBodyTopo(body, face);
2099:         } else {
2100:           fID = EG_indexBodyTopo(body, face);
2101:         }

2103:         /* Checkout the Surface Tessellation */
2104:         if (islite) {
2105:           PetscCall(EGlite_getTessFace(tessArray[b], fID, &len, &pxyz, &puv, &ptype, &pindex, &ntris, &ptris, &ptric));
2106:         } else {
2107:           PetscCall(EG_getTessFace(tessArray[b], fID, &len, &pxyz, &puv, &ptype, &pindex, &ntris, &ptris, &ptric));
2108:         }

2110:         /* Check out the point index and coordinate */
2111:         for (int p = 0; p < len; ++p) {
2112:           int           global;
2113:           PetscHashIter PTLiter, PILiter, PBLiter;
2114:           PetscBool     PTLfound, PILfound, PBLfound;

2116:           if (islite) {
2117:             PetscCall(EGlite_localToGlobal(tessArray[b], fID, p + 1, &global));
2118:           } else {
2119:             PetscCall(EG_localToGlobal(tessArray[b], fID, p + 1, &global));
2120:           }

2122:           /* Set the coordinates array for DAG */
2123:           coords[((global - 1 + pointIndexStart) * 3) + 0] = pxyz[(p * 3) + 0];
2124:           coords[((global - 1 + pointIndexStart) * 3) + 1] = pxyz[(p * 3) + 1];
2125:           coords[((global - 1 + pointIndexStart) * 3) + 2] = pxyz[(p * 3) + 2];

2127:           /* Store Geometry Label Information for DMLabel assignment later */
2128:           PetscCall(PetscHMapIFind(pTypeLabelMap, global - 1 + pointIndexStart, &PTLiter, &PTLfound));
2129:           PetscCall(PetscHMapIFind(pIndexLabelMap, global - 1 + pointIndexStart, &PILiter, &PILfound));
2130:           PetscCall(PetscHMapIFind(pBodyIndexLabelMap, global - 1 + pointIndexStart, &PBLiter, &PBLfound));

2132:           if (!PTLfound) PetscCall(PetscHMapISet(pTypeLabelMap, global - 1 + pointIndexStart, ptype[p]));
2133:           if (!PILfound) PetscCall(PetscHMapISet(pIndexLabelMap, global - 1 + pointIndexStart, pindex[p]));
2134:           if (!PBLfound) PetscCall(PetscHMapISet(pBodyIndexLabelMap, global - 1 + pointIndexStart, b));

2136:           if (ptype[p] < 0) PetscCall(PetscHMapISet(pIndexLabelMap, global - 1 + pointIndexStart, fID));
2137:         }

2139:         for (int t = 0; t < (int)ntris; ++t) {
2140:           int           global, globalA, globalB;
2141:           PetscHashIter TFLiter, TBLiter;
2142:           PetscBool     TFLfound, TBLfound;

2144:           if (islite) {
2145:             PetscCall(EGlite_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 0], &global));
2146:           } else {
2147:             PetscCall(EG_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 0], &global));
2148:           }
2149:           cells[(counter * 3) + 0] = global - 1 + pointIndexStart;

2151:           if (islite) {
2152:             PetscCall(EGlite_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 1], &globalA));
2153:           } else {
2154:             PetscCall(EG_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 1], &globalA));
2155:           }
2156:           cells[(counter * 3) + 1] = globalA - 1 + pointIndexStart;

2158:           if (islite) {
2159:             PetscCall(EGlite_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 2], &globalB));
2160:           } else {
2161:             PetscCall(EG_localToGlobal(tessArray[b], fID, ptris[(t * 3) + 2], &globalB));
2162:           }
2163:           cells[(counter * 3) + 2] = globalB - 1 + pointIndexStart;

2165:           PetscCall(PetscHMapIFind(triFaceIDLabelMap, counter, &TFLiter, &TFLfound));
2166:           PetscCall(PetscHMapIFind(triBodyIDLabelMap, counter, &TBLiter, &TBLfound));

2168:           if (!TFLfound) PetscCall(PetscHMapISet(triFaceIDLabelMap, counter, fID));
2169:           if (!TBLfound) PetscCall(PetscHMapISet(triBodyIDLabelMap, counter, b));

2171:           counter += 1;
2172:         }
2173:       }
2174:       if (islite) {
2175:         EGlite_free(fobjs);
2176:       } else {
2177:         EG_free(fobjs);
2178:       }
2179:     }
2180:     PetscCall(PetscFree(tessArray));
2181:   }

2183:   //Build DMPlex
2184:   PetscCall(DMPlexCreateFromCellListPetsc(PETSC_COMM_WORLD, dim, totalNumTris, totalNumPoints, numCorners, PETSC_TRUE, cells, cdim, coords, &dm));
2185:   PetscCall(PetscFree2(coords, cells));

2187:   // Embed EGADS model in DM
2188:   {
2189:     PetscContainer modelObj, contextObj;

2191:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &modelObj));
2192:     PetscCall(PetscContainerSetPointer(modelObj, model));
2193:     if (islite) {
2194:       PetscCall(PetscContainerSetCtxDestroy(modelObj, DMPlexEGADSliteDestroy_Private));
2195:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADSlite Model", (PetscObject)modelObj));
2196:     } else {
2197:       PetscCall(PetscContainerSetCtxDestroy(modelObj, DMPlexEGADSDestroy_Private));
2198:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Model", (PetscObject)modelObj));
2199:     }
2200:     PetscCall(PetscContainerDestroy(&modelObj));

2202:     PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &contextObj));
2203:     PetscCall(PetscContainerSetPointer(contextObj, context));

2205:     if (islite) {
2206:       PetscCall(PetscContainerSetCtxDestroy(contextObj, DMPlexEGADSliteClose_Private));
2207:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADSlite Context", (PetscObject)contextObj));
2208:     } else {
2209:       PetscCall(PetscContainerSetCtxDestroy(contextObj, DMPlexEGADSClose_Private));
2210:       PetscCall(PetscObjectCompose((PetscObject)dm, "EGADS Context", (PetscObject)contextObj));
2211:     }
2212:     PetscCall(PetscContainerDestroy(&contextObj));
2213:   }

2215:   // Label Points
2216:   PetscCall(DMCreateLabel(dm, "EGADS Body ID"));
2217:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
2218:   PetscCall(DMCreateLabel(dm, "EGADS Face ID"));
2219:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
2220:   PetscCall(DMCreateLabel(dm, "EGADS Edge ID"));
2221:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
2222:   PetscCall(DMCreateLabel(dm, "EGADS Vertex ID"));
2223:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

2225:   /* Get Number of DAG Nodes at each level */
2226:   int fStart, fEnd, eStart, eEnd, nStart, nEnd;

2228:   PetscCall(DMPlexGetHeightStratum(dm, 0, &fStart, &fEnd));
2229:   PetscCall(DMPlexGetHeightStratum(dm, 1, &eStart, &eEnd));
2230:   PetscCall(DMPlexGetHeightStratum(dm, 2, &nStart, &nEnd));

2232:   /* Set DMLabels for NODES */
2233:   for (int n = nStart; n < nEnd; ++n) {
2234:     int           pTypeVal, pIndexVal, pBodyVal;
2235:     PetscHashIter PTLiter, PILiter, PBLiter;
2236:     PetscBool     PTLfound, PILfound, PBLfound;

2238:     //Converted to Hash Tables
2239:     PetscCall(PetscHMapIFind(pTypeLabelMap, n - nStart, &PTLiter, &PTLfound));
2240:     PetscCheck(PTLfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "DAG Point %" PetscInt_FMT " not found in pTypeLabelMap", n);
2241:     PetscCall(PetscHMapIGet(pTypeLabelMap, n - nStart, &pTypeVal));

2243:     PetscCall(PetscHMapIFind(pIndexLabelMap, n - nStart, &PILiter, &PILfound));
2244:     PetscCheck(PILfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "DAG Point %" PetscInt_FMT " not found in pIndexLabelMap", n);
2245:     PetscCall(PetscHMapIGet(pIndexLabelMap, n - nStart, &pIndexVal));

2247:     PetscCall(PetscHMapIFind(pBodyIndexLabelMap, n - nStart, &PBLiter, &PBLfound));
2248:     PetscCheck(PBLfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "DAG Point %" PetscInt_FMT " not found in pBodyLabelMap", n);
2249:     PetscCall(PetscHMapIGet(pBodyIndexLabelMap, n - nStart, &pBodyVal));

2251:     PetscCall(DMLabelSetValue(bodyLabel, n, pBodyVal));
2252:     if (pTypeVal == 0) PetscCall(DMLabelSetValue(vertexLabel, n, pIndexVal));
2253:     if (pTypeVal > 0) PetscCall(DMLabelSetValue(edgeLabel, n, pIndexVal));
2254:     if (pTypeVal < 0) PetscCall(DMLabelSetValue(faceLabel, n, pIndexVal));
2255:   }

2257:   /* Set DMLabels for Edges - Based on the DMLabels of the EDGE's NODES */
2258:   for (int e = eStart; e < eEnd; ++e) {
2259:     int bodyID_0, vertexID_0, vertexID_1, edgeID_0, edgeID_1, faceID_0, faceID_1;

2261:     PetscCall(DMPlexGetCone(dm, e, &cone));
2262:     PetscCall(DMLabelGetValue(bodyLabel, cone[0], &bodyID_0)); // Do I need to check the other end?
2263:     PetscCall(DMLabelGetValue(vertexLabel, cone[0], &vertexID_0));
2264:     PetscCall(DMLabelGetValue(vertexLabel, cone[1], &vertexID_1));
2265:     PetscCall(DMLabelGetValue(edgeLabel, cone[0], &edgeID_0));
2266:     PetscCall(DMLabelGetValue(edgeLabel, cone[1], &edgeID_1));
2267:     PetscCall(DMLabelGetValue(faceLabel, cone[0], &faceID_0));
2268:     PetscCall(DMLabelGetValue(faceLabel, cone[1], &faceID_1));

2270:     PetscCall(DMLabelSetValue(bodyLabel, e, bodyID_0));

2272:     if (edgeID_0 == edgeID_1) PetscCall(DMLabelSetValue(edgeLabel, e, edgeID_0));
2273:     else if (vertexID_0 > 0 && edgeID_1 > 0) PetscCall(DMLabelSetValue(edgeLabel, e, edgeID_1));
2274:     else if (vertexID_1 > 0 && edgeID_0 > 0) PetscCall(DMLabelSetValue(edgeLabel, e, edgeID_0));
2275:     else { /* Do Nothing */ }
2276:   }

2278:   /* Set DMLabels for Cells */
2279:   for (int f = fStart; f < fEnd; ++f) {
2280:     int           edgeID_0;
2281:     PetscInt      triBodyVal, triFaceVal;
2282:     PetscHashIter TFLiter, TBLiter;
2283:     PetscBool     TFLfound, TBLfound;

2285:     // Convert to Hash Table
2286:     PetscCall(PetscHMapIFind(triFaceIDLabelMap, f - fStart, &TFLiter, &TFLfound));
2287:     PetscCheck(TFLfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "DAG Point %" PetscInt_FMT " not found in triFaceIDLabelMap", f);
2288:     PetscCall(PetscHMapIGet(triFaceIDLabelMap, f - fStart, &triFaceVal));

2290:     PetscCall(PetscHMapIFind(triBodyIDLabelMap, f - fStart, &TBLiter, &TBLfound));
2291:     PetscCheck(TBLfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "DAG Point %" PetscInt_FMT " not found in triBodyIDLabelMap", f);
2292:     PetscCall(PetscHMapIGet(triBodyIDLabelMap, f - fStart, &triBodyVal));

2294:     PetscCall(DMLabelSetValue(bodyLabel, f, triBodyVal));
2295:     PetscCall(DMLabelSetValue(faceLabel, f, triFaceVal));

2297:     /* Finish Labeling previously unlabeled DMPlex Edges - Assumes Triangular Cell (3 Edges Max) */
2298:     PetscCall(DMPlexGetCone(dm, f, &cone));

2300:     for (int jj = 0; jj < 3; ++jj) {
2301:       PetscCall(DMLabelGetValue(edgeLabel, cone[jj], &edgeID_0));

2303:       if (edgeID_0 < 0) {
2304:         PetscCall(DMLabelSetValue(bodyLabel, cone[jj], triBodyVal));
2305:         PetscCall(DMLabelSetValue(faceLabel, cone[jj], triFaceVal));
2306:       }
2307:     }
2308:   }

2310:   *newdm = dm;
2311:   PetscFunctionReturn(PETSC_SUCCESS);
2312: }
2313: #endif

2315: /*@
2316:   DMPlexInflateToGeomModelUseXYZ - Snaps the vertex coordinates of a `DMPLEX` object representing the mesh to its geometry if some vertices depart from the model.
2317:   This usually happens with non-conforming refinement.

2319:   Collective

2321:   Input Parameter:
2322: . dm - The uninflated `DM` object representing the mesh

2324:   Level: intermediate

2326: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMPlexCreateEGADS()`
2327: @*/
2328: PetscErrorCode DMPlexInflateToGeomModelUseXYZ(DM dm) PeNS
2329: {
2330:   // please don't fucking write code like this with #ifdef all of the place!
2331: #if PetscDefined(HAVE_EGADS)
2332:   /* EGADS Variables */
2333:   ego    model, geom, body, face, edge, vertex;
2334:   ego   *bodies;
2335:   int    Nb, oclass, mtype, *senses;
2336:   double result[4];
2337:   /* PETSc Variables */
2338:   DM             cdm;
2339:   PetscContainer modelObj;
2340:   DMLabel        bodyLabel, faceLabel, edgeLabel, vertexLabel;
2341:   Vec            coordinates;
2342:   PetscScalar   *coords;
2343:   PetscInt       bodyID, faceID, edgeID, vertexID;
2344:   PetscInt       cdim, d, vStart, vEnd, v;
2345:   PetscBool      islite = PETSC_FALSE;
2346: #endif

2348:   PetscFunctionBegin;
2349: #if PetscDefined(HAVE_EGADS)
2350:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
2351:   if (!modelObj) {
2352:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
2353:     islite = PETSC_TRUE;
2354:   }
2355:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);
2356:   PetscCall(DMGetCoordinateDim(dm, &cdim));
2357:   PetscCall(DMGetCoordinateDM(dm, &cdm));
2358:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
2359:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
2360:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
2361:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
2362:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

2364:   PetscCall(PetscContainerGetPointer(modelObj, &model));

2366:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
2367:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));

2369:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
2370:   PetscCall(VecGetArrayWrite(coordinates, &coords));
2371:   for (v = vStart; v < vEnd; ++v) {
2372:     PetscScalar *vcoords;

2374:     PetscCall(DMLabelGetValue(bodyLabel, v, &bodyID));
2375:     PetscCall(DMLabelGetValue(faceLabel, v, &faceID));
2376:     PetscCall(DMLabelGetValue(edgeLabel, v, &edgeID));
2377:     PetscCall(DMLabelGetValue(vertexLabel, v, &vertexID));

2379:     PetscCheck(bodyID < Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Body %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", bodyID, Nb);
2380:     body = bodies[bodyID];

2382:     PetscCall(DMPlexPointLocalRef(cdm, v, coords, (void *)&vcoords));
2383:     if (vertexID > 0) {
2384:       if (islite) {
2385:         PetscCall(EGlite_objectBodyTopo(body, NODE, vertexID, &vertex));
2386:         PetscCall(EGlite_evaluate(vertex, NULL, result));
2387:       } else {
2388:         PetscCall(EG_objectBodyTopo(body, NODE, vertexID, &vertex));
2389:         PetscCall(EG_evaluate(vertex, NULL, result));
2390:       }
2391:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
2392:     } else if (edgeID > 0) {
2393:       /* Snap to EDGE at nearest location */
2394:       double params[1];
2395:       if (islite) {
2396:         PetscCall(EGlite_objectBodyTopo(body, EDGE, edgeID, &edge));
2397:         PetscCall(EGlite_invEvaluate(edge, vcoords, params, result));
2398:       } // Get (x,y,z) of nearest point on EDGE
2399:       else {
2400:         PetscCall(EG_objectBodyTopo(body, EDGE, edgeID, &edge));
2401:         PetscCall(EG_invEvaluate(edge, vcoords, params, result));
2402:       }
2403:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
2404:     } else if (faceID > 0) {
2405:       /* Snap to FACE at nearest location */
2406:       double params[2];
2407:       if (islite) {
2408:         PetscCall(EGlite_objectBodyTopo(body, FACE, faceID, &face));
2409:         PetscCall(EGlite_invEvaluate(face, vcoords, params, result));
2410:       } // Get (x,y,z) of nearest point on FACE
2411:       else {
2412:         PetscCall(EG_objectBodyTopo(body, FACE, faceID, &face));
2413:         PetscCall(EG_invEvaluate(face, vcoords, params, result));
2414:       }
2415:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
2416:     }
2417:   }
2418:   PetscCall(VecRestoreArrayWrite(coordinates, &coords));
2419:   /* Clear out global coordinates */
2420:   PetscCall(VecDestroy(&dm->coordinates[0].x));
2421: #endif
2422:   PetscFunctionReturn(PETSC_SUCCESS);
2423: }

2425: #if PetscDefined(HAVE_EGADS)
2426: // This replaces the model in-place
2427: PetscErrorCode ConvertGeomModelToAllBSplines(PetscBool islite, ego *model) PeNS
2428: {
2429:   /* EGADS/EGADSlite Variables */
2430:   ego  context = NULL, geom, *bodies, *fobjs;
2431:   int  oclass, mtype;
2432:   int *senses;
2433:   int  Nb, Nf;

2435:   PetscFunctionBegin;
2436:   // Get the number of bodies and body objects in the model
2437:   if (islite) PetscCallEGADS(EGlite_getTopology, *model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);
2438:   else PetscCallEGADS(EG_getTopology, *model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);

2440:   // Get all Faces on the body    <-- Only working with 1 body at the moment.
2441:   ego body = bodies[0];
2442:   if (islite) PetscCallEGADS(EGlite_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);
2443:   else PetscCallEGADS(EG_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);
2444:   ego newGeom[Nf];
2445:   ego newFaces[Nf];

2447:   // Convert the 1st Face to a BSpline Geometry
2448:   for (int ii = 0; ii < Nf; ++ii) {
2449:     ego     face = fobjs[ii];
2450:     ego     gRef, gPrev, gNext, *lobjs;
2451:     int     goclass, gmtype, *gpinfo;
2452:     int     Nl, *lsenses;
2453:     double *gprv;
2454:     char   *gClass = (char *)"", *gType = (char *)"";

2456:     /* Shape Optimization is NOT available for EGADSlite geometry files. */
2457:     /*     Note :: islite options are left below in case future versions of EGADSlite includes this capability */
2458:     PetscCheck(!islite, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot convert geometric entities to all BSplines for geometries defined by EGADSlite (.egadslite)! Please use another geometry file format STEP, IGES, EGADS or BRep");

2460:     if (islite) {
2461:       PetscCallEGADS(EGlite_getTopology, face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses); // Get FACES Geometry object (geom_
2462:       PetscCallEGADS(EGlite_getGeometry, geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv);            // Get geometry object info
2463:       PetscCallEGADS(EGlite_getInfo, geom, &goclass, &gmtype, &gRef, &gPrev, &gNext);
2464:     } // Get geometry info
2465:     else {
2466:       PetscCallEGADS(EG_getTopology, face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses); // Get FACES Geometry object (geom_
2467:       PetscCallEGADS(EG_getGeometry, geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv);            // Get geometry object info
2468:       PetscCallEGADS(EG_getInfo, geom, &goclass, &gmtype, &gRef, &gPrev, &gNext);
2469:     } // Get geometry info

2471:     PetscCall(DMPlex_EGADS_GeomDecode_Internal(goclass, gmtype, &gClass, &gType)); // Decode Geometry integers

2473:     // Convert current FACE to a BSpline Surface
2474:     ego     bspline;
2475:     ego     bRef, bPrev, bNext;
2476:     int     boclass, bmtype, *bpinfo;
2477:     double *bprv;
2478:     char   *bClass = (char *)"", *bType = (char *)"";

2480:     PetscCallEGADS(EG_convertToBSpline, face, &bspline); // Does not have an EGlite_ version

2482:     if (islite) {
2483:       PetscCallEGADS(EGlite_getGeometry, bspline, &boclass, &bmtype, &bRef, &bpinfo, &bprv); // Get geometry object info
2484:       PetscCallEGADS(EGlite_getInfo, bspline, &boclass, &bmtype, &bRef, &bPrev, &bNext);
2485:     } // Get geometry info
2486:     else {
2487:       PetscCallEGADS(EG_getGeometry, bspline, &boclass, &bmtype, &bRef, &bpinfo, &bprv); // Get geometry object info
2488:       PetscCallEGADS(EG_getInfo, bspline, &boclass, &bmtype, &bRef, &bPrev, &bNext);
2489:     } // Get geometry info

2491:     PetscCall(DMPlex_EGADS_GeomDecode_Internal(boclass, bmtype, &bClass, &bType)); // Decode Geometry integers

2493:     // Get Context from FACE
2494:     context = NULL;
2495:     PetscCallEGADS(EG_getContext, face, &context); // Does not have an EGlite_ version

2497:     // Silence WARNING Regarding OPENCASCADE 7.5
2498:     if (islite) PetscCallEGADS(EGlite_setOutLevel, context, 0);
2499:     else PetscCallEGADS(EG_setOutLevel, context, 0);

2501:     ego newgeom;
2502:     PetscCallEGADS(EG_makeGeometry, context, SURFACE, BSPLINE, NULL, bpinfo, bprv, &newgeom); // Does not have an EGlite_ version

2504:     PetscCallEGADS(EG_deleteObject, bspline);

2506:     // Create new FACE based on new SURFACE geometry
2507:     double data[4];
2508:     int    periodic;
2509:     if (islite) PetscCallEGADS(EGlite_getRange, newgeom, data, &periodic);
2510:     else PetscCallEGADS(EG_getRange, newgeom, data, &periodic);

2512:     ego newface;
2513:     PetscCallEGADS(EG_makeFace, newgeom, SFORWARD, data, &newface); // Does not have an EGlite_ version
2514:     //PetscCallEGADS(EG_deleteObject, newgeom);
2515:     //PetscCallEGADS(EG_deleteObject, newface);
2516:     newFaces[ii] = newface;
2517:     newGeom[ii]  = newgeom;

2519:     // Reinstate WARNING Regarding OPENCASCADE 7.5
2520:     if (islite) PetscCallEGADS(EGlite_setOutLevel, context, 1);
2521:     else PetscCallEGADS(EG_setOutLevel, context, 1);
2522:   }

2524:   // Sew New Faces together to get a new model
2525:   ego newmodel;
2526:   PetscCallEGADS(EG_sewFaces, Nf, newFaces, 0.0, 0, &newmodel); // Does not have an EGlite_ version
2527:   for (int ii = 0; ii < Nf; ++ii) {
2528:     PetscCallEGADS(EG_deleteObject, newFaces[ii]);
2529:     PetscCallEGADS(EG_deleteObject, newGeom[ii]);
2530:   }
2531:   PetscCallEGADS(EG_deleteObject, *model);
2532:   *model = newmodel;
2533:   PetscFunctionReturn(PETSC_SUCCESS);
2534: }
2535: #endif

2537: /*@
2538:   DMPlexCreateGeomFromFile - Create a `DMPLEX` mesh from an EGADS, IGES, or STEP file.

2540:   Collective

2542:   Input Parameters:
2543: + comm     - The MPI communicator
2544: . filename - The name of the EGADS, IGES, or STEP file
2545: - islite   - Flag for EGADSlite support

2547:   Output Parameter:
2548: . dm - The `DM` object representing the mesh

2550:   Level: beginner

2552: .seealso: [](ch_unstructured), `DM`, `DMPLEX`, `DMCreate()`, `DMPlexCreateEGADS()`, `DMPlexCreateEGADSliteFromFile()`
2553: @*/
2554: PetscErrorCode DMPlexCreateGeomFromFile(MPI_Comm comm, const char filename[], DM *dm, PetscBool islite) PeNS
2555: {
2556:   /* PETSc Variables */
2557:   PetscMPIInt rank;
2558:   PetscBool   printModel = PETSC_FALSE, tessModel = PETSC_FALSE, newModel = PETSC_FALSE;
2559:   PetscBool   shapeOpt = PETSC_FALSE;

2561: #if PetscDefined(HAVE_EGADS)
2562:   ego context = NULL, model = NULL;
2563: #endif

2565:   PetscFunctionBegin;
2566:   PetscAssertPointer(filename, 2);
2567:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-dm_plex_geom_print_model", &printModel, NULL));
2568:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-dm_plex_geom_tess_model", &tessModel, NULL));
2569:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-dm_plex_geom_new_model", &newModel, NULL));
2570:   PetscCall(PetscOptionsGetBool(NULL, NULL, "-dm_plex_geom_shape_opt", &shapeOpt, NULL));
2571:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
2572: #if PetscDefined(HAVE_EGADS)
2573:   if (rank == 0) {
2574:     /* EGADSlite files cannot be used for Shape Optimization Work. It lacks the ability to make new geometry. */
2575:     /* Must use EGADS, STEP, IGES or BRep files to perform this work.                                         */
2576:     if (islite) {
2577:       PetscCallEGADS(EGlite_open, &context);
2578:       PetscCallEGADS(EGlite_loadModel, context, 0, filename, &model);
2579:       if (shapeOpt) PetscCall(ConvertGeomModelToAllBSplines(islite, &model));
2580:       if (printModel) PetscCall(DMPlexGeomPrintModel_Internal(model, islite));
2581:     } else {
2582:       PetscCallEGADS(EG_open, &context);
2583:       PetscCallEGADS(EG_loadModel, context, 0, filename, &model);
2584:       if (shapeOpt) PetscCall(ConvertGeomModelToAllBSplines(islite, &model));
2585:       if (printModel) PetscCall(DMPlexGeomPrintModel_Internal(model, islite));
2586:     }
2587:   }
2588:   if (tessModel) PetscCall(DMPlexCreateGeom_Tess_Internal(comm, context, model, dm, islite));
2589:   else if (newModel) PetscCall(DMPlexCreateGeom_Internal(comm, context, model, dm, islite));
2590:   else PetscCall(DMPlexCreateGeom(comm, context, model, dm, islite));
2591:   PetscFunctionReturn(PETSC_SUCCESS);
2592: #else
2593:   SETERRQ(comm, PETSC_ERR_SUP, "This method requires EGADS support. Reconfigure using --download-egads");
2594: #endif
2595: }

2597: #if PetscDefined(HAVE_EGADS)
2598: static PetscErrorCode DestroyHashMap(PetscCtxRt p)
2599: {
2600:   PetscFunctionBegin;
2601:   PetscCall(PetscHMapIDestroy((PetscHMapI *)p));
2602:   PetscFunctionReturn(PETSC_SUCCESS);
2603: }
2604: #endif

2606: /*@
2607:   DMPlexGeomDataAndGrads - Exposes Control Points and Control Point Weights defining the underlying geometry allowing user manipulation of the geometry.

2609:   Collective

2611:   Input Parameters:
2612: + dm           - The `DM` object representing the mesh with `PetscContainer` containing an EGADS geometry model
2613: - fullGeomGrad - Determines how the Surface Area and Volume Gradients wrt to Control Points and Control Point Weights are calculated.
2614: .vb
2615:                       PETSC_FALSE :: Surface Area Gradient wrt Control Points and Control Point Weights are calculated using the change in the local
2616:                                      FACE changes (not the entire body). Volume Gradients are not calculated. Faster computations.
2617:                       PETSC_TRUE  :: Surface Area Gradietn wrt to Control Points and Control Point Weights are calculated using the change observed in
2618:                                      the entire solid body. Volume Gradients are calculated. Slower computation due to the need to generate a new solid
2619:                                      body geometry for every Control Point and Control Point Weight change.
2620: .ve

2622:   Output Parameter:
2623: . dm - The updated `DM` object representing the mesh with `PetscContainer`s containing the Control Point, Control Point Weight and Gradient Data.

2625:   Level: intermediate

2627:   Note:
2628:   Calculates the `DM` Point location, surface area and volume gradients wrt to Control Point and Control Point Weights using Finite Difference
2629:   (small perturbation of Control Point coordinates or Control Point Weight value).

2631: .seealso: `DMPLEX`, `DMCreate()`, `DMPlexCreateGeom()`, `DMPlexCreateGeomFromFile()`, `DMPlexModifyGeomModel()`
2632: @*/
2633: PetscErrorCode DMPlexGeomDataAndGrads(DM dm, PetscBool fullGeomGrad) PeNS
2634: {
2635: #if PetscDefined(HAVE_EGADS)
2636:   /* PETSc Variables */
2637:   PetscContainer modelObj;
2638:   PetscHMapI     faceCntrlPtRow_Start = NULL, faceCPWeightsRow_Start = NULL;
2639:   PetscHMapI     pointSurfGradRow_Start = NULL;
2640:   Mat            pointSurfGrad, cpEquiv;
2641:   IS             faceLabelValues, edgeLabelValues, vertexLabelValues;
2642:   PetscInt       faceLabelSize, edgeLabelSize, vertexLabelSize;
2643:   PetscBool      islite = PETSC_FALSE;
2644:   /* EGADS Variables */
2645:   ego model, geom, *bodies, *fobjs = NULL;
2646:   int oclass, mtype, *senses;
2647:   int Nb, Nf;
2648: #endif

2650:   PetscFunctionBegin;
2651: #if PetscDefined(HAVE_EGADS)

2653:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
2654:   if (!modelObj) {
2655:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
2656:     PetscCheck(modelObj, PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Input DM must have attached EGADS Geometry Model");
2657:     islite = PETSC_TRUE;
2658:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Cannot provide geometric data or associated calculated gradients for geometries defined by EGADSlite (.egadslite)!\nPlease use another geometry file format STEP, IGES, EGADS or BRep");
2659:   }

2661:   // Get attached EGADS model (pointer)
2662:   PetscCall(PetscContainerGetPointer(modelObj, &model));

2664:   // Get the bodies in the model
2665:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
2666:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));

2668:   ego body = bodies[0]; // Only operate on 1st body. Model should only have 1 body.

2670:   // Get the total number of FACEs in the model
2671:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));
2672:   else PetscCall(EG_getBodyTopos(body, NULL, FACE, &Nf, &fobjs));

2674:   // Get the total number of points and IDs in the DMPlex with a "EGADS Face Label"
2675:   // This will provide the total number of DMPlex points on the boundary of the geometry
2676:   PetscCall(DMGetLabelIdIS(dm, "EGADS Face ID", &faceLabelValues));
2677:   PetscCall(DMGetLabelSize(dm, "EGADS Face ID", &faceLabelSize));

2679:   PetscCall(DMGetLabelIdIS(dm, "EGADS Edge ID", &edgeLabelValues));
2680:   PetscCall(DMGetLabelSize(dm, "EGADS Edge ID", &edgeLabelSize));

2682:   PetscCall(DMGetLabelIdIS(dm, "EGADS Vertex ID", &vertexLabelValues));
2683:   PetscCall(DMGetLabelSize(dm, "EGADS Vertex ID", &vertexLabelSize));

2685:   const PetscInt *faceIndices, *edgeIndices, *vertexIndices;
2686:   PetscCall(ISGetIndices(faceLabelValues, &faceIndices));
2687:   PetscCall(ISGetIndices(edgeLabelValues, &edgeIndices));
2688:   PetscCall(ISGetIndices(vertexLabelValues, &vertexIndices));

2690:   // Get the points associated with each FACE, EDGE and VERTEX label in the DM
2691:   PetscInt totalNumPoints = 0;
2692:   for (int f = 0; f < faceLabelSize; ++f) {
2693:     // Cycle through FACE labels
2694:     PetscInt size;
2695:     PetscCall(DMGetStratumSize(dm, "EGADS Face ID", faceIndices[f], &size));
2696:     totalNumPoints += size;
2697:   }
2698:   PetscCall(ISRestoreIndices(faceLabelValues, &faceIndices));
2699:   PetscCall(ISDestroy(&faceLabelValues));

2701:   for (int e = 0; e < edgeLabelSize; ++e) {
2702:     // Cycle Through EDGE Labels
2703:     PetscInt size;
2704:     PetscCall(DMGetStratumSize(dm, "EGADS Edge ID", edgeIndices[e], &size));
2705:     totalNumPoints += size;
2706:   }
2707:   PetscCall(ISRestoreIndices(edgeLabelValues, &edgeIndices));
2708:   PetscCall(ISDestroy(&edgeLabelValues));

2710:   for (int ii = 0; ii < vertexLabelSize; ++ii) {
2711:     // Cycle Through VERTEX Labels
2712:     PetscInt size;
2713:     PetscCall(DMGetStratumSize(dm, "EGADS Vertex ID", vertexIndices[ii], &size));
2714:     totalNumPoints += size;
2715:   }
2716:   PetscCall(ISRestoreIndices(vertexLabelValues, &vertexIndices));
2717:   PetscCall(ISDestroy(&vertexLabelValues));

2719:   int     maxNumCPs   = 0;
2720:   int     totalNumCPs = 0;
2721:   ego     bRef, bPrev, bNext, fgeom, *lobjs;
2722:   int     id, boclass, bmtype, *bpinfo;
2723:   int     foclass, fmtype, Nl, *lsenses;
2724:   double *bprv;
2725:   double  fdata[4];

2727:   // Create Hash Tables
2728:   PetscInt cntr = 0, wcntr = 0, vcntr = 0;
2729:   PetscCall(PetscHMapICreate(&faceCntrlPtRow_Start));
2730:   PetscCall(PetscHMapICreate(&faceCPWeightsRow_Start));

2732:   for (int f = 0; f < Nf; ++f) {
2733:     // Need to get the maximum number of Control Points defining the FACEs
2734:     ego face = fobjs[f];
2735:     int maxNumCPs_temp;

2737:     if (islite) {
2738:       id = EGlite_indexBodyTopo(body, face);
2739:       PetscCall(EGlite_getTopology(face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses));
2740:       PetscCall(EGlite_getGeometry(fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv));
2741:       PetscCall(EGlite_getInfo(fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext));
2742:     } else {
2743:       id = EG_indexBodyTopo(body, face);
2744:       PetscCall(EG_getTopology(face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses));
2745:       PetscCall(EG_getGeometry(fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv));
2746:       PetscCall(EG_getInfo(fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext));
2747:     }
2748:     maxNumCPs_temp = bpinfo[2] * bpinfo[5];
2749:     totalNumCPs += bpinfo[2] * bpinfo[5];

2751:     if (maxNumCPs_temp > maxNumCPs) maxNumCPs = maxNumCPs_temp;
2752:   }

2754:   PetscInt *cpCoordDataLengthPtr, *wDataLengthPtr;
2755:   PetscInt  cpCoordDataLength = 3 * totalNumCPs;
2756:   PetscInt  wDataLength       = totalNumCPs;
2757:   cpCoordDataLengthPtr        = &cpCoordDataLength;
2758:   wDataLengthPtr              = &wDataLength;

2760:   Vec          cntrlPtCoordsVec, cntrlPtWeightsVec;
2761:   PetscScalar *cntrlPtCoords, *cntrlPtWeights;
2762:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, cpCoordDataLength, &cntrlPtCoordsVec));
2763:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, wDataLength, &cntrlPtWeightsVec));

2765:   // For dSA/dCPi
2766:   Vec          gradSACPVec, gradSAWVec, gradVCPVec, gradVWVec;
2767:   PetscScalar *gradSACP, *gradSAW, *gradVCP, *gradVW;
2768:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, cpCoordDataLength, &gradSACPVec));
2769:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, wDataLength, &gradSAWVec));
2770:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, cpCoordDataLength, &gradVCPVec));
2771:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, wDataLength, &gradVWVec));

2773:   // Control Point - Vertex/Edge/Face Relationship
2774:   PetscInt *cp_vertex, *cp_edge, *cp_face;
2775:   PetscInt *w_vertex, *w_edge, *w_face;
2776:   PetscCall(PetscMalloc1(totalNumCPs, &cp_vertex));
2777:   PetscCall(PetscMalloc1(totalNumCPs, &cp_edge));
2778:   PetscCall(PetscMalloc1(totalNumCPs, &cp_face));
2779:   PetscCall(PetscMalloc1(wDataLength, &w_vertex));
2780:   PetscCall(PetscMalloc1(wDataLength, &w_edge));
2781:   PetscCall(PetscMalloc1(wDataLength, &w_face));

2783:   for (int f = 0; f < Nf; ++f) {
2784:     // Need to Populate Control Point Coordinates and Weight Vectors
2785:     ego           face = fobjs[f];
2786:     ego          *vobjs, *eobjs;
2787:     int           offsetCoord, offsetWeight;
2788:     PetscInt      Nv, Ne, wRowStart = 0;
2789:     PetscHashIter hashKeyIter, wHashKeyIter;
2790:     PetscBool     hashKeyFound, wHashKeyFound;

2792:     if (islite) {
2793:       id = EGlite_indexBodyTopo(body, face);
2794:       PetscCallEGADS(EGlite_getTopology, face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses);
2795:       PetscCallEGADS(EGlite_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
2796:       PetscCallEGADS(EGlite_getInfo, fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext);
2797:       PetscCallEGADS(EGlite_getBodyTopos, body, face, NODE, &Nv, &vobjs);
2798:     } else {
2799:       id = EG_indexBodyTopo(body, face);
2800:       PetscCallEGADS(EG_getTopology, face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses);
2801:       PetscCallEGADS(EG_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
2802:       PetscCallEGADS(EG_getInfo, fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext);
2803:       PetscCallEGADS(EG_getBodyTopos, body, face, NODE, &Nv, &vobjs);
2804:     }

2806:     // Store Face ID to 1st Row of Control Point Vector
2807:     PetscCall(PetscHMapIFind(faceCntrlPtRow_Start, id, &hashKeyIter, &hashKeyFound));

2809:     if (!hashKeyFound) PetscCall(PetscHMapISet(faceCntrlPtRow_Start, id, cntr));

2811:     PetscCall(VecGetArrayWrite(cntrlPtCoordsVec, &cntrlPtCoords));
2812:     offsetCoord = bpinfo[3] + bpinfo[6];
2813:     for (int jj = 0; jj < 3 * bpinfo[2] * bpinfo[5]; ++jj) {
2814:       cntrlPtCoords[cntr] = bprv[offsetCoord + jj];
2815:       cntr += 1;
2816:     }

2818:     // Store Face ID to 1st Row of Control Point Weight Vector
2819:     PetscCall(PetscHMapIFind(faceCPWeightsRow_Start, id, &wHashKeyIter, &wHashKeyFound));

2821:     if (!wHashKeyFound) {
2822:       PetscCall(PetscHMapISet(faceCPWeightsRow_Start, id, wcntr));
2823:       wRowStart = wcntr;
2824:     }

2826:     PetscCall(VecGetArrayWrite(cntrlPtWeightsVec, &cntrlPtWeights));
2827:     offsetWeight = bpinfo[3] + bpinfo[6] + (3 * bpinfo[2] * bpinfo[5]);
2828:     for (int jj = 0; jj < bpinfo[2] * bpinfo[5]; ++jj) {
2829:       cntrlPtWeights[wcntr] = bprv[offsetWeight + jj];
2830:       cp_face[wcntr]        = id;
2831:       w_face[wcntr]         = id;
2832:       wcntr += 1;
2833:     }
2834:     PetscCall(VecRestoreArrayWrite(cntrlPtWeightsVec, &cntrlPtWeights));

2836:     // Associate Control Points with Vertex IDs
2837:     PetscScalar xcp, ycp, zcp;
2838:     offsetCoord = bpinfo[3] + bpinfo[6];
2839:     for (int jj = 0; jj < 3 * bpinfo[2] * bpinfo[5]; jj += 3) {
2840:       xcp = bprv[offsetCoord + jj + 0];
2841:       ycp = bprv[offsetCoord + jj + 1];
2842:       zcp = bprv[offsetCoord + jj + 2];

2844:       //Initialize Control Point and Weight to Vertex ID relationship to -1
2845:       cp_vertex[vcntr] = -1;
2846:       w_vertex[vcntr]  = -1;
2847:       cp_edge[vcntr]   = -1;
2848:       w_edge[vcntr]    = -1;

2850:       for (int kk = 0; kk < Nv; ++kk) {
2851:         int         vid;
2852:         double      vCoords[3];
2853:         PetscScalar vDelta;
2854:         ego         vertex = vobjs[kk];

2856:         if (islite) {
2857:           vid = EGlite_indexBodyTopo(body, vertex);
2858:           PetscCallEGADS(EGlite_evaluate, vertex, NULL, vCoords);
2859:         } else {
2860:           vid = EG_indexBodyTopo(body, vertex);
2861:           PetscCallEGADS(EG_evaluate, vertex, NULL, vCoords);
2862:         }
2863:         vDelta = PetscSqrtReal(PetscSqr(vCoords[0] - xcp) + PetscSqr(vCoords[1] - ycp) + PetscSqr(vCoords[2] - zcp));

2865:         if (vDelta < 1.0E-15) {
2866:           cp_vertex[vcntr] = vid;
2867:           w_vertex[vcntr]  = vid;
2868:         }
2869:       }
2870:       vcntr += 1;
2871:     }
2872:     // These two line could be replaced with DMPlexFreeGeomObject()
2873:     if (islite) EGlite_free(vobjs);
2874:     else EG_free(vobjs);

2876:     // Associate Control Points with Edge IDs
2877:     if (islite) PetscCallEGADS(EGlite_getBodyTopos, body, face, EDGE, &Ne, &eobjs);
2878:     else PetscCallEGADS(EG_getBodyTopos, body, face, EDGE, &Ne, &eobjs);

2880:     int cpV1, cpV2;
2881:     int minID, maxID;

2883:     // Along vmin axis
2884:     minID = wRowStart;
2885:     maxID = wRowStart + (bpinfo[2] - 1);
2886:     cpV1  = cp_vertex[minID];
2887:     cpV2  = cp_vertex[maxID];
2888:     for (int jj = 0; jj < Ne; ++jj) {
2889:       ego edge = eobjs[jj];
2890:       ego egeom, *nobjs;
2891:       int eoclass, emtype, Nn, *nsenses;
2892:       int n1ID, n2ID, eid;

2894:       if (islite) {
2895:         eid = EGlite_indexBodyTopo(body, edge);
2896:         PetscCallEGADS(EGlite_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2897:       } else {
2898:         eid = EG_indexBodyTopo(body, edge);
2899:         PetscCallEGADS(EG_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2900:       }

2902:       if (emtype != DEGENERATE) {
2903:         // Get IDs for current Edge's End Vertices
2904:         if (islite) {
2905:           n1ID = EGlite_indexBodyTopo(body, nobjs[0]);
2906:           n2ID = EGlite_indexBodyTopo(body, nobjs[1]);
2907:         } else {
2908:           n1ID = EG_indexBodyTopo(body, nobjs[0]);
2909:           n2ID = EG_indexBodyTopo(body, nobjs[1]);
2910:         }

2912:         if ((cpV1 == n1ID || cpV1 == n2ID) && (cpV2 == n1ID || cpV2 == n2ID)) {
2913:           for (int kk = minID + 1; kk < maxID; ++kk) {
2914:             cp_edge[kk] = eid;
2915:             w_edge[kk]  = eid;
2916:           }
2917:         }
2918:       }
2919:     }

2921:     // Along vmax axis
2922:     minID = wRowStart + (bpinfo[2] * (bpinfo[5] - 1));
2923:     maxID = wRowStart + (bpinfo[2] * bpinfo[5] - 1);

2925:     cpV1 = cp_vertex[minID];
2926:     cpV2 = cp_vertex[maxID];
2927:     for (int jj = 0; jj < Ne; ++jj) {
2928:       ego edge = eobjs[jj];
2929:       ego egeom, *nobjs;
2930:       int eoclass, emtype, Nn, *nsenses;
2931:       int n1ID, n2ID, eid;

2933:       if (islite) {
2934:         eid = EGlite_indexBodyTopo(body, edge);
2935:         PetscCallEGADS(EGlite_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2936:       } else {
2937:         eid = EG_indexBodyTopo(body, edge);
2938:         PetscCallEGADS(EG_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2939:       }

2941:       if (emtype != DEGENERATE) {
2942:         // Get IDs for current Edge's End Vertices
2943:         if (islite) {
2944:           n1ID = EGlite_indexBodyTopo(body, nobjs[0]);
2945:           n2ID = EGlite_indexBodyTopo(body, nobjs[1]);
2946:         } else {
2947:           n1ID = EG_indexBodyTopo(body, nobjs[0]);
2948:           n2ID = EG_indexBodyTopo(body, nobjs[1]);
2949:         }

2951:         if ((cpV1 == n1ID || cpV1 == n2ID) && (cpV2 == n1ID || cpV2 == n2ID)) {
2952:           for (int kk = minID + 1; kk < maxID - 1; ++kk) {
2953:             cp_edge[kk] = eid;
2954:             w_edge[kk]  = eid;
2955:           }
2956:         }
2957:       }
2958:     }

2960:     // Along umin axis
2961:     minID = wRowStart;
2962:     maxID = wRowStart + (bpinfo[2] * (bpinfo[5] - 1));

2964:     cpV1 = cp_vertex[minID];
2965:     cpV2 = cp_vertex[maxID];
2966:     for (int jj = 0; jj < Ne; ++jj) {
2967:       ego edge = eobjs[jj];
2968:       ego egeom, *nobjs;
2969:       int eoclass, emtype, Nn, *nsenses;
2970:       int n1ID, n2ID, eid;

2972:       if (islite) {
2973:         eid = EGlite_indexBodyTopo(body, edge);
2974:         PetscCallEGADS(EGlite_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2975:       } else {
2976:         eid = EG_indexBodyTopo(body, edge);
2977:         PetscCallEGADS(EG_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
2978:       }

2980:       if (emtype != DEGENERATE) {
2981:         // Get IDs for current Edge's End Vertices
2982:         if (islite) {
2983:           n1ID = EGlite_indexBodyTopo(body, nobjs[0]);
2984:           n2ID = EGlite_indexBodyTopo(body, nobjs[1]);
2985:         } else {
2986:           n1ID = EG_indexBodyTopo(body, nobjs[0]);
2987:           n2ID = EG_indexBodyTopo(body, nobjs[1]);
2988:         }

2990:         if ((cpV1 == n1ID || cpV1 == n2ID) && (cpV2 == n1ID || cpV2 == n2ID)) {
2991:           for (int kk = minID + bpinfo[2]; kk < maxID; kk += bpinfo[2]) {
2992:             cp_edge[kk] = eid;
2993:             w_edge[kk]  = eid;
2994:           }
2995:         }
2996:       }
2997:     }

2999:     // Along umax axis
3000:     minID = wRowStart + (bpinfo[2] - 1);
3001:     maxID = wRowStart + (bpinfo[2] * bpinfo[5]) - 1;
3002:     cpV1  = cp_vertex[minID];
3003:     cpV2  = cp_vertex[maxID];
3004:     for (int jj = 0; jj < Ne; ++jj) {
3005:       ego edge = eobjs[jj];
3006:       ego egeom, *nobjs;
3007:       int eoclass, emtype, Nn, *nsenses;
3008:       int n1ID, n2ID, eid;

3010:       if (islite) {
3011:         eid = EGlite_indexBodyTopo(body, edge);
3012:         PetscCallEGADS(EGlite_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
3013:       } else {
3014:         eid = EG_indexBodyTopo(body, edge);
3015:         PetscCallEGADS(EG_getTopology, edge, &egeom, &eoclass, &emtype, NULL, &Nn, &nobjs, &nsenses);
3016:       }

3018:       if (emtype != DEGENERATE) {
3019:         // Get IDs for current Edge's End Vertices
3020:         if (islite) {
3021:           n1ID = EGlite_indexBodyTopo(body, nobjs[0]);
3022:           n2ID = EGlite_indexBodyTopo(body, nobjs[1]);
3023:         } else {
3024:           n1ID = EG_indexBodyTopo(body, nobjs[0]);
3025:           n2ID = EG_indexBodyTopo(body, nobjs[1]);
3026:         }

3028:         if ((cpV1 == n1ID || cpV1 == n2ID) && (cpV2 == n1ID || cpV2 == n2ID)) {
3029:           for (int kk = minID + bpinfo[2]; kk < maxID; kk += bpinfo[2]) {
3030:             cp_edge[kk] = eid;
3031:             w_edge[kk]  = eid;
3032:           }
3033:         }
3034:       }
3035:     }
3036:     // These two lines could be replaced with DMPlexFreeGeomObject()
3037:     if (islite) EGlite_free(eobjs);
3038:     else EG_free(eobjs);
3039:   }

3041:   // Determine Control Point Equivalence Matrix relating Control Points between Surfaces
3042:   //     Note: The Weights will also be tied together in the same manner
3043:   //           Also can use the Weight Hash Table for Row Start ID of each Face
3044:   const PetscInt cpRowSize = totalNumCPs;
3045:   const PetscInt cpColSize = cpRowSize;
3046:   PetscInt      *maxNumRelatePtr;
3047:   PetscInt       maxNumRelate = 0;

3049:   // Create Point Surface Gradient Matrix
3050:   PetscCall(MatCreate(PETSC_COMM_WORLD, &cpEquiv));
3051:   PetscCall(MatSetSizes(cpEquiv, PETSC_DECIDE, PETSC_DECIDE, cpRowSize, cpColSize));
3052:   PetscCall(MatSetType(cpEquiv, MATAIJ));
3053:   PetscCall(MatSetUp(cpEquiv));

3055:   for (int ii = 0; ii < totalNumCPs; ++ii) {
3056:     PetscScalar x1, y1, z1;
3057:     PetscInt    maxRelateTemp = 0;

3059:     x1 = cntrlPtCoords[(3 * ii) + 0];
3060:     y1 = cntrlPtCoords[(3 * ii) + 1];
3061:     z1 = cntrlPtCoords[(3 * ii) + 2];

3063:     for (int jj = 0; jj < totalNumCPs; ++jj) {
3064:       PetscScalar x2, y2, z2;
3065:       PetscScalar cpDelta, eqFactor;
3066:       x2 = cntrlPtCoords[(3 * jj) + 0];
3067:       y2 = cntrlPtCoords[(3 * jj) + 1];
3068:       z2 = cntrlPtCoords[(3 * jj) + 2];

3070:       cpDelta = PetscSqrtReal(PetscSqr(x2 - x1) + PetscSqr(y2 - y1) + PetscSqr(z2 - z1));
3071:       if (cpDelta < 1.0E-15) {
3072:         eqFactor = 1.0;
3073:         maxRelateTemp += 1;
3074:       } else {
3075:         eqFactor = 0.0;
3076:       }

3078:       // Store Results in PETSc Mat
3079:       PetscCall(MatSetValue(cpEquiv, ii, jj, eqFactor, INSERT_VALUES));
3080:     }
3081:     if (maxRelateTemp > maxNumRelate) maxNumRelate = maxRelateTemp;
3082:   }
3083:   maxNumRelatePtr = &maxNumRelate;
3084:   PetscCall(VecRestoreArrayWrite(cntrlPtCoordsVec, &cntrlPtCoords));

3086:   // Assemble Point Surface Grad Matrix
3087:   PetscCall(MatAssemblyBegin(cpEquiv, MAT_FINAL_ASSEMBLY));
3088:   PetscCall(MatAssemblyEnd(cpEquiv, MAT_FINAL_ASSEMBLY));

3090:   // Attach Control Point and Weight Data to DM
3091:   {
3092:     PetscContainer cpOrgObj, cpCoordLengthObj;
3093:     PetscContainer wOrgObj, wDataLengthObj;
3094:     PetscContainer cp_faceObj, cp_edgeObj, cp_vertexObj;
3095:     PetscContainer w_faceObj, w_edgeObj, w_vertexObj;
3096:     PetscContainer maxNumRelateObj;

3098:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Hash Table", (PetscObject *)&cpOrgObj));
3099:     if (!cpOrgObj) {
3100:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &cpOrgObj));
3101:       PetscCall(PetscContainerSetPointer(cpOrgObj, faceCntrlPtRow_Start));
3102:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Hash Table", (PetscObject)cpOrgObj));
3103:       PetscCall(PetscContainerDestroy(&cpOrgObj));
3104:     } else {
3105:       PetscCall(PetscContainerSetPointer(cpOrgObj, faceCntrlPtRow_Start));
3106:     }

3108:     PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Coordinates", (PetscObject)cntrlPtCoordsVec));
3109:     PetscCall(VecDestroy(&cntrlPtCoordsVec));

3111:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Coordinate Data Length", (PetscObject *)&cpCoordLengthObj));
3112:     if (!cpCoordLengthObj) {
3113:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &cpCoordLengthObj));
3114:       PetscCall(PetscContainerSetPointer(cpCoordLengthObj, cpCoordDataLengthPtr));
3115:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Coordinate Data Length", (PetscObject)cpCoordLengthObj));
3116:       PetscCall(PetscContainerDestroy(&cpCoordLengthObj));
3117:     } else {
3118:       PetscCall(PetscContainerSetPointer(cpCoordLengthObj, cpCoordDataLengthPtr));
3119:     }

3121:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weights Hash Table", (PetscObject *)&wOrgObj));
3122:     if (!wOrgObj) {
3123:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &wOrgObj));
3124:       PetscCall(PetscContainerSetPointer(wOrgObj, faceCPWeightsRow_Start));
3125:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weights Hash Table", (PetscObject)wOrgObj));
3126:       PetscCall(PetscContainerDestroy(&wOrgObj));
3127:     } else {
3128:       PetscCall(PetscContainerSetPointer(wOrgObj, faceCPWeightsRow_Start));
3129:     }

3131:     PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weight Data", (PetscObject)cntrlPtWeightsVec));
3132:     PetscCall(VecDestroy(&cntrlPtWeightsVec));

3134:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data Length", (PetscObject *)&wDataLengthObj));
3135:     if (!wDataLengthObj) {
3136:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &wDataLengthObj));
3137:       PetscCall(PetscContainerSetPointer(wDataLengthObj, wDataLengthPtr));
3138:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weight Data Length", (PetscObject)wDataLengthObj));
3139:       PetscCall(PetscContainerDestroy(&wDataLengthObj));
3140:     } else {
3141:       PetscCall(PetscContainerSetPointer(wDataLengthObj, wDataLengthPtr));
3142:     }

3144:     PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Equivalency Matrix", (PetscObject)cpEquiv));

3146:     PetscCall(PetscObjectQuery((PetscObject)dm, "Maximum Number Control Point Equivalency", (PetscObject *)&maxNumRelateObj));
3147:     if (!maxNumRelateObj) {
3148:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &maxNumRelateObj));
3149:       PetscCall(PetscContainerSetPointer(maxNumRelateObj, maxNumRelatePtr));
3150:       PetscCall(PetscObjectCompose((PetscObject)dm, "Maximum Number Control Point Equivalency", (PetscObject)maxNumRelateObj));
3151:       PetscCall(PetscContainerDestroy(&maxNumRelateObj));
3152:     } else {
3153:       PetscCall(PetscContainerSetPointer(maxNumRelateObj, maxNumRelatePtr));
3154:     }

3156:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Face Map", (PetscObject *)&cp_faceObj));
3157:     if (!cp_faceObj) {
3158:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &cp_faceObj));
3159:       PetscCall(PetscContainerSetPointer(cp_faceObj, cp_face));
3160:       PetscCall(PetscContainerSetCtxDestroy(cp_faceObj, PetscCtxDestroyDefault));
3161:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point - Face Map", (PetscObject)cp_faceObj));
3162:       PetscCall(PetscContainerDestroy(&cp_faceObj));
3163:     } else {
3164:       void *tmp;

3166:       PetscCall(PetscContainerGetPointer(cp_faceObj, &tmp));
3167:       PetscCall(PetscFree(tmp));
3168:       PetscCall(PetscContainerSetPointer(cp_faceObj, cp_face));
3169:     }

3171:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Face Map", (PetscObject *)&w_faceObj));
3172:     if (!w_faceObj) {
3173:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &w_faceObj));
3174:       PetscCall(PetscContainerSetPointer(w_faceObj, w_face));
3175:       PetscCall(PetscContainerSetCtxDestroy(w_faceObj, PetscCtxDestroyDefault));
3176:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weight - Face Map", (PetscObject)w_faceObj));
3177:       PetscCall(PetscContainerDestroy(&w_faceObj));
3178:     } else {
3179:       void *tmp;

3181:       PetscCall(PetscContainerGetPointer(w_faceObj, &tmp));
3182:       PetscCall(PetscFree(tmp));
3183:       PetscCall(PetscContainerSetPointer(w_faceObj, w_face));
3184:     }

3186:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Edge Map", (PetscObject *)&cp_edgeObj));
3187:     if (!cp_edgeObj) {
3188:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &cp_edgeObj));
3189:       PetscCall(PetscContainerSetPointer(cp_edgeObj, cp_edge));
3190:       PetscCall(PetscContainerSetCtxDestroy(cp_edgeObj, PetscCtxDestroyDefault));
3191:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point - Edge Map", (PetscObject)cp_edgeObj));
3192:       PetscCall(PetscContainerDestroy(&cp_edgeObj));
3193:     } else {
3194:       void *tmp;

3196:       PetscCall(PetscContainerGetPointer(cp_edgeObj, &tmp));
3197:       PetscCall(PetscFree(tmp));
3198:       PetscCall(PetscContainerSetPointer(cp_edgeObj, cp_edge));
3199:     }

3201:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Edge Map", (PetscObject *)&w_edgeObj));
3202:     if (!w_edgeObj) {
3203:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &w_edgeObj));
3204:       PetscCall(PetscContainerSetPointer(w_edgeObj, w_edge));
3205:       PetscCall(PetscContainerSetCtxDestroy(w_edgeObj, PetscCtxDestroyDefault));
3206:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weight - Edge Map", (PetscObject)w_edgeObj));
3207:       PetscCall(PetscContainerDestroy(&w_edgeObj));
3208:     } else {
3209:       void *tmp;

3211:       PetscCall(PetscContainerGetPointer(w_edgeObj, &tmp));
3212:       PetscCall(PetscFree(tmp));
3213:       PetscCall(PetscContainerSetPointer(w_edgeObj, w_edge));
3214:     }

3216:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Vertex Map", (PetscObject *)&cp_vertexObj));
3217:     if (!cp_vertexObj) {
3218:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &cp_vertexObj));
3219:       PetscCall(PetscContainerSetPointer(cp_vertexObj, cp_vertex));
3220:       PetscCall(PetscContainerSetCtxDestroy(cp_vertexObj, PetscCtxDestroyDefault));
3221:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point - Vertex Map", (PetscObject)cp_vertexObj));
3222:       PetscCall(PetscContainerDestroy(&cp_vertexObj));
3223:     } else {
3224:       void *tmp;

3226:       PetscCall(PetscContainerGetPointer(cp_vertexObj, &tmp));
3227:       PetscCall(PetscFree(tmp));
3228:       PetscCall(PetscContainerSetPointer(cp_vertexObj, cp_vertex));
3229:     }

3231:     PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Vertex Map", (PetscObject *)&w_vertexObj));
3232:     if (!w_vertexObj) {
3233:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &w_vertexObj));
3234:       PetscCall(PetscContainerSetPointer(w_vertexObj, w_vertex));
3235:       PetscCall(PetscContainerSetCtxDestroy(w_vertexObj, PetscCtxDestroyDefault));
3236:       PetscCall(PetscObjectCompose((PetscObject)dm, "Control Point Weight - Vertex Map", (PetscObject)w_vertexObj));
3237:       PetscCall(PetscContainerDestroy(&w_vertexObj));
3238:     } else {
3239:       void *tmp;

3241:       PetscCall(PetscContainerGetPointer(w_vertexObj, &tmp));
3242:       PetscCall(PetscFree(tmp));
3243:       PetscCall(PetscContainerSetPointer(w_vertexObj, w_vertex));
3244:     }
3245:   }

3247:   // Define Matrix to store  Geometry Gradient information dGeom_i/dCPj_i
3248:   PetscInt       gcntr   = 0;
3249:   const PetscInt rowSize = 3 * maxNumCPs * totalNumPoints;
3250:   const PetscInt colSize = 4 * Nf;

3252:   // Create Point Surface Gradient Matrix
3253:   PetscCall(MatCreate(PETSC_COMM_WORLD, &pointSurfGrad));
3254:   PetscCall(MatSetSizes(pointSurfGrad, PETSC_DECIDE, PETSC_DECIDE, rowSize, colSize));
3255:   PetscCall(MatSetType(pointSurfGrad, MATAIJ));
3256:   PetscCall(MatSetUp(pointSurfGrad));

3258:   // Create Hash Table to store Point's stare row in surfaceGrad[][]
3259:   PetscCall(PetscHMapICreate(&pointSurfGradRow_Start));

3261:   // Get Coordinates for the DMPlex point
3262:   DM           cdm;
3263:   PetscInt     dE, Nv;
3264:   Vec          coordinatesLocal;
3265:   PetscScalar *coords = NULL;

3267:   PetscCall(DMGetCoordinateDM(dm, &cdm));
3268:   PetscCall(DMGetCoordinateDim(dm, &dE));
3269:   PetscCall(DMGetCoordinatesLocal(dm, &coordinatesLocal));

3271:   // CYCLE THROUGH FACEs
3272:   PetscScalar maxGrad = 0.;
3273:   PetscCall(VecGetArrayWrite(gradSACPVec, &gradSACP));
3274:   PetscCall(VecGetArrayWrite(gradSAWVec, &gradSAW));
3275:   PetscCall(VecGetArrayWrite(gradVCPVec, &gradVCP));
3276:   PetscCall(VecGetArrayWrite(gradVWVec, &gradVW));
3277:   for (int f = 0; f < Nf; ++f) {
3278:     ego             face = fobjs[f];
3279:     ego            *eobjs, *nobjs;
3280:     PetscInt        fid, Ne, Nn;
3281:     DMLabel         faceLabel, edgeLabel, nodeLabel;
3282:     PetscHMapI      currFaceUniquePoints = NULL;
3283:     IS              facePoints, edgePoints, nodePoints;
3284:     const PetscInt *fIndices, *eIndices, *nIndices;
3285:     PetscInt        fSize, eSize, nSize;
3286:     PetscHashIter   fHashKeyIter, eHashKeyIter, nHashKeyIter, pHashKeyIter;
3287:     PetscBool       fHashKeyFound, eHashKeyFound, nHashKeyFound, pHashKeyFound;
3288:     PetscInt        cfCntr = 0;

3290:     // Get Geometry Object for the Current FACE
3291:     if (islite) {
3292:       PetscCall(EGlite_getTopology(face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses));
3293:       PetscCall(EGlite_getGeometry(fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv));
3294:     } else {
3295:       PetscCall(EG_getTopology(face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses));
3296:       PetscCall(EG_getGeometry(fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv));
3297:     }

3299:     // Get all EDGE and NODE objects attached to the current FACE
3300:     if (islite) {
3301:       PetscCall(EGlite_getBodyTopos(body, face, EDGE, &Ne, &eobjs));
3302:       PetscCall(EGlite_getBodyTopos(body, face, NODE, &Nn, &nobjs));
3303:     } else {
3304:       PetscCall(EG_getBodyTopos(body, face, EDGE, &Ne, &eobjs));
3305:       PetscCall(EG_getBodyTopos(body, face, NODE, &Nn, &nobjs));
3306:     }

3308:     // Get all DMPlex Points that have DMLabel "EGADS Face ID" and store them in a Hash Table for later use
3309:     if (islite) {
3310:       fid = EGlite_indexBodyTopo(body, face);
3311:     } else {
3312:       fid = EG_indexBodyTopo(body, face);
3313:     }

3315:     PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
3316:     PetscCall(DMLabelGetStratumIS(faceLabel, fid, &facePoints));
3317:     PetscCall(ISGetIndices(facePoints, &fIndices));
3318:     PetscCall(ISGetSize(facePoints, &fSize));

3320:     PetscCall(PetscHMapICreate(&currFaceUniquePoints));

3322:     for (int jj = 0; jj < fSize; ++jj) {
3323:       PetscCall(PetscHMapIFind(currFaceUniquePoints, fIndices[jj], &fHashKeyIter, &fHashKeyFound));

3325:       if (!fHashKeyFound) {
3326:         PetscCall(PetscHMapISet(currFaceUniquePoints, fIndices[jj], cfCntr));
3327:         cfCntr += 1;
3328:       }

3330:       PetscCall(PetscHMapIFind(pointSurfGradRow_Start, fIndices[jj], &pHashKeyIter, &pHashKeyFound));

3332:       if (!pHashKeyFound) {
3333:         PetscCall(PetscHMapISet(pointSurfGradRow_Start, fIndices[jj], gcntr));
3334:         gcntr += 3 * maxNumCPs;
3335:       }
3336:     }
3337:     PetscCall(ISRestoreIndices(facePoints, &fIndices));
3338:     PetscCall(ISDestroy(&facePoints));

3340:     // Get all DMPlex Points that have DMLable "EGADS Edge ID" attached to the current FACE and store them in a Hash Table for later use.
3341:     for (int jj = 0; jj < Ne; ++jj) {
3342:       ego       edge = eobjs[jj];
3343:       PetscBool containLabelValue;

3345:       if (islite) {
3346:         id = EGlite_indexBodyTopo(body, edge);
3347:       } else {
3348:         id = EG_indexBodyTopo(body, edge);
3349:       }

3351:       PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
3352:       PetscCall(DMLabelHasValue(edgeLabel, id, &containLabelValue));

3354:       if (containLabelValue) {
3355:         PetscCall(DMLabelGetStratumIS(edgeLabel, id, &edgePoints));
3356:         PetscCall(ISGetIndices(edgePoints, &eIndices));
3357:         PetscCall(ISGetSize(edgePoints, &eSize));

3359:         for (int kk = 0; kk < eSize; ++kk) {
3360:           PetscCall(PetscHMapIFind(currFaceUniquePoints, eIndices[kk], &eHashKeyIter, &eHashKeyFound));

3362:           if (!eHashKeyFound) {
3363:             PetscCall(PetscHMapISet(currFaceUniquePoints, eIndices[kk], cfCntr));
3364:             cfCntr += 1;
3365:           }

3367:           PetscCall(PetscHMapIFind(pointSurfGradRow_Start, eIndices[kk], &pHashKeyIter, &pHashKeyFound));

3369:           if (!pHashKeyFound) {
3370:             PetscCall(PetscHMapISet(pointSurfGradRow_Start, eIndices[kk], gcntr));
3371:             gcntr += 3 * maxNumCPs;
3372:           }
3373:         }
3374:         PetscCall(ISRestoreIndices(edgePoints, &eIndices));
3375:         PetscCall(ISDestroy(&edgePoints));
3376:       }
3377:     }

3379:     // Get all DMPlex Points that have DMLabel "EGADS Vertex ID" attached to the current FACE and store them in a Hash Table for later use.
3380:     for (int jj = 0; jj < Nn; ++jj) {
3381:       ego node = nobjs[jj];

3383:       if (islite) {
3384:         id = EGlite_indexBodyTopo(body, node);
3385:       } else {
3386:         id = EG_indexBodyTopo(body, node);
3387:       }

3389:       PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &nodeLabel));
3390:       PetscCall(DMLabelGetStratumIS(nodeLabel, id, &nodePoints));
3391:       PetscCall(ISGetIndices(nodePoints, &nIndices));
3392:       PetscCall(ISGetSize(nodePoints, &nSize));

3394:       for (int kk = 0; kk < nSize; ++kk) {
3395:         PetscCall(PetscHMapIFind(currFaceUniquePoints, nIndices[kk], &nHashKeyIter, &nHashKeyFound));

3397:         if (!nHashKeyFound) {
3398:           PetscCall(PetscHMapISet(currFaceUniquePoints, nIndices[kk], cfCntr));
3399:           cfCntr += 1;
3400:         }

3402:         PetscCall(PetscHMapIFind(pointSurfGradRow_Start, nIndices[kk], &pHashKeyIter, &pHashKeyFound));
3403:         if (!pHashKeyFound) {
3404:           PetscCall(PetscHMapISet(pointSurfGradRow_Start, nIndices[kk], gcntr));
3405:           gcntr += 3 * maxNumCPs;
3406:         }
3407:       }
3408:       PetscCall(ISRestoreIndices(nodePoints, &nIndices));
3409:       PetscCall(ISDestroy(&nodePoints));
3410:     }

3412:     // Get the Total Number of entries in the Hash Table
3413:     PetscInt currFaceUPSize;
3414:     PetscCall(PetscHMapIGetSize(currFaceUniquePoints, &currFaceUPSize));

3416:     // Get Keys
3417:     PetscInt currFaceUPKeys[currFaceUPSize], off = 0;
3418:     PetscCall(PetscHMapIGetKeys(currFaceUniquePoints, &off, currFaceUPKeys));
3419:     PetscCall(PetscHMapIDestroy(&currFaceUniquePoints));

3421:     // Get Current Face Surface Area
3422:     PetscScalar fSA, faceData[14];
3423:     PetscCall(EG_getMassProperties(face, faceData)); // This doesn't have an EGlite version. Will it work for EGADSlite files??  KNOWN_ISSUE
3424:     fSA = faceData[1];

3426:     // Get Start Row in cpEquiv Matrix
3427:     PetscHashIter Witer;
3428:     PetscBool     Wfound;
3429:     PetscInt      faceWStartRow;
3430:     PetscCall(PetscHMapIFind(faceCPWeightsRow_Start, fid, &Witer, &Wfound));
3431:     PetscCheck(Wfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Weights Hash Table");
3432:     PetscCall(PetscHMapIGet(faceCPWeightsRow_Start, fid, &faceWStartRow));

3434:     // Cycle through all points on the current FACE
3435:     for (int jj = 0; jj < currFaceUPSize; ++jj) {
3436:       PetscInt currPointID = currFaceUPKeys[jj];
3437:       PetscCall(DMPlexVecGetClosure(cdm, NULL, coordinatesLocal, currPointID, &Nv, &coords));

3439:       // Get UV position of FACE
3440:       double params[2], range[4], eval[18];
3441:       int    peri;

3443:       if (islite) PetscCall(EGlite_getRange(face, range, &peri));
3444:       else PetscCall(EG_getRange(face, range, &peri));

3446:       PetscCall(DMPlex_Geom_FACE_XYZtoUV_Internal(coords, face, range, 0, dE, params, islite));

3448:       if (islite) PetscCall(EGlite_evaluate(face, params, eval));
3449:       else PetscCall(EG_evaluate(face, params, eval));

3451:       // Make a new SURFACE Geometry by changing the location of the Control Points
3452:       int    prvSize = bpinfo[3] + bpinfo[6] + (4 * bpinfo[2] * bpinfo[5]);
3453:       double nbprv[prvSize];

3455:       // Cycle through each Control Point
3456:       double denomNew, denomOld;
3457:       double deltaCoord = 1.0E-4;
3458:       int    offset     = bpinfo[3] + bpinfo[6];
3459:       int    wOffset    = offset + (3 * bpinfo[2] * bpinfo[5]);
3460:       for (int ii = 0; ii < bpinfo[2] * bpinfo[5]; ++ii) {
3461:         PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d", f, jj, ii);
3462:   #if 0
3463:         // Cycle through each direction (x, then y, then z)
3464:         if (jj == 0) {
3465:           // Get the Number Control Points that are the same as the current points
3466:           //    We are looking for repeated Control Points
3467:           PetscInt commonCPcntr = 0;
3468:           for (int mm = 0; mm < bpinfo[2]*bpinfo[5]; ++mm) {
3469:             PetscScalar matValue;
3470:             PetscCall(MatGetValue(cpEquiv, faceWStartRow + ii, faceWStartRow + mm, &matValue));

3472:             if (matValue > 0.0) commonCPcntr += 1;
3473:           }
3474:         }
3475:   #endif

3477:         for (int kk = 0; kk < 4; ++kk) {
3478:           // Reinitialize nbprv[] values because we only want to change one value at a time
3479:           for (int mm = 0; mm < prvSize; ++mm) nbprv[mm] = bprv[mm];
3480:           PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d %d", f, jj, ii, kk);

3482:           if (kk == 0) { //X
3483:             nbprv[offset + 0] = bprv[offset + 0] + deltaCoord;
3484:             nbprv[offset + 1] = bprv[offset + 1];
3485:             nbprv[offset + 2] = bprv[offset + 2];
3486:             denomNew          = nbprv[offset + 0];
3487:             denomOld          = bprv[offset + 0];
3488:           } else if (kk == 1) { //Y
3489:             nbprv[offset + 0] = bprv[offset + 0];
3490:             nbprv[offset + 1] = bprv[offset + 1] + deltaCoord;
3491:             nbprv[offset + 2] = bprv[offset + 2];
3492:             denomNew          = nbprv[offset + 1];
3493:             denomOld          = bprv[offset + 1];
3494:           } else if (kk == 2) { //Z
3495:             nbprv[offset + 0] = bprv[offset + 0];
3496:             nbprv[offset + 1] = bprv[offset + 1];
3497:             nbprv[offset + 2] = bprv[offset + 2] + deltaCoord;
3498:             denomNew          = nbprv[offset + 2];
3499:             denomOld          = bprv[offset + 2];
3500:           } else if (kk == 3) { // Weights
3501:             nbprv[wOffset + ii] = bprv[wOffset + ii] + deltaCoord;
3502:             denomNew            = nbprv[wOffset + ii];
3503:             denomOld            = bprv[wOffset + ii];
3504:           } else {
3505:             // currently do nothing
3506:           }

3508:           // Create New Surface Based on New Control Points or Weights
3509:           ego newgeom, context;
3510:           PetscCallEGADS(EG_getContext, face, &context);                                             // This does not have an EGlite_ version KNOWN_ISSUE
3511:           PetscCallEGADS(EG_makeGeometry, context, SURFACE, BSPLINE, NULL, bpinfo, nbprv, &newgeom); // This does not have an EGlite_ version KNOWN_ISSUE
3512:           PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d %d", f, jj, ii, kk);

3514:           // Evaluate new (x, y, z) Point Position based on new Surface Definition
3515:           double newCoords[18];
3516:           if (islite) PetscCall(EGlite_getRange(newgeom, range, &peri));
3517:           else PetscCall(EG_getRange(newgeom, range, &peri));

3519:           PetscCall(DMPlex_Geom_FACE_XYZtoUV_Internal(coords, face, range, 0, dE, params, islite));
3520:           PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d %d", f, jj, ii, kk);

3522:           if (islite) PetscCall(EGlite_evaluate(newgeom, params, newCoords));
3523:           else PetscCall(EG_evaluate(newgeom, params, newCoords));

3525:           // Calculate Surface Area Gradients wrt Control Points and Weights using the local discrete FACE only
3526:           //      NOTE 1: Will not provide Volume Gradient wrt to Control Points and Weights.
3527:           //      NOTE 2: This is faster than below where an entire new solid geometry is created for each
3528:           //              Control Point and Weight gradient
3529:           if (!fullGeomGrad) {
3530:             // Create new FACE based on new SURFACE geometry
3531:             if (jj == 0) { // only for 1st DMPlex Point because we only per CP or Weight
3532:               double newFaceRange[4];
3533:               int    newFacePeri;
3534:               if (islite) PetscCall(EGlite_getRange(newgeom, newFaceRange, &newFacePeri));
3535:               else PetscCall(EG_getRange(newgeom, newFaceRange, &newFacePeri));

3537:               ego newface;
3538:               PetscCallEGADS(EG_makeFace, newgeom, SFORWARD, newFaceRange, &newface); // Does not have EGlite version KNOWN_ISSUE
3539:               PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d %d", f, jj, ii, kk);

3541:               // Get New Face Surface Area
3542:               PetscScalar newfSA, newFaceData[14];
3543:               PetscCall(EG_getMassProperties(newface, newFaceData)); // Does not have EGlite version KNOWN_ISSUE
3544:               newfSA = newFaceData[1];
3545:               PetscCallEGADS(EG_deleteObject, newface);
3546:               PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face %d is corrupted: %d %d %d", f, jj, ii, kk);

3548:               // Update Control Points
3549:               PetscHashIter CPiter, Witer;
3550:               PetscBool     CPfound, Wfound;
3551:               PetscInt      faceCPStartRow, faceWStartRow;

3553:               PetscScalar dSAdCPi;
3554:               dSAdCPi = (newfSA - fSA) / (denomNew - denomOld);

3556:               if (kk < 3) {
3557:                 PetscCall(PetscHMapIFind(faceCntrlPtRow_Start, fid, &CPiter, &CPfound));
3558:                 PetscCheck(CPfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Hash Table");
3559:                 PetscCall(PetscHMapIGet(faceCntrlPtRow_Start, fid, &faceCPStartRow));

3561:                 gradSACP[faceCPStartRow + (ii * 3) + kk] = dSAdCPi;

3563:                 if (PetscAbsReal(dSAdCPi) > maxGrad) maxGrad = PetscAbsReal(dSAdCPi);

3565:               } else if (kk == 3) {
3566:                 PetscCall(PetscHMapIFind(faceCPWeightsRow_Start, fid, &Witer, &Wfound));
3567:                 PetscCheck(Wfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Hash Table");
3568:                 PetscCall(PetscHMapIGet(faceCPWeightsRow_Start, fid, &faceWStartRow));

3570:                 gradSAW[faceWStartRow + ii] = dSAdCPi;

3572:               } else {
3573:                 // Do Nothing
3574:               }
3575:             }
3576:           }
3577:           PetscCallEGADS(EG_deleteObject, newgeom);

3579:           // Now Calculate the Surface Gradient for the change in x-component Control Point
3580:           PetscScalar dxdCx = (newCoords[0] - coords[0]) / deltaCoord;
3581:           PetscScalar dxdCy = (newCoords[1] - coords[1]) / deltaCoord;
3582:           PetscScalar dxdCz = (newCoords[2] - coords[2]) / deltaCoord;

3584:           // Store Gradient Information in surfaceGrad[][] Matrix
3585:           PetscInt startRow;
3586:           PetscCall(PetscHMapIGet(pointSurfGradRow_Start, currPointID, &startRow));

3588:           // Store Results in PETSc Mat
3589:           PetscCall(MatSetValue(pointSurfGrad, startRow + (ii * 3) + 0, ((fid - 1) * 4) + kk, dxdCx, INSERT_VALUES));
3590:           PetscCall(MatSetValue(pointSurfGrad, startRow + (ii * 3) + 1, ((fid - 1) * 4) + kk, dxdCy, INSERT_VALUES));
3591:           PetscCall(MatSetValue(pointSurfGrad, startRow + (ii * 3) + 2, ((fid - 1) * 4) + kk, dxdCz, INSERT_VALUES));

3593:           //PetscCallEGADS(EG_deleteObject, newgeom);
3594:           PetscCheck(face->blind, PETSC_COMM_SELF, PETSC_ERR_LIB, "Face is corrupted");
3595:         }
3596:         offset += 3;
3597:       }
3598:       PetscCall(DMPlexVecRestoreClosure(cdm, NULL, coordinatesLocal, currPointID, &Nv, &coords));
3599:     }
3600:   }

3602:   // Assemble Point Surface Grad Matrix
3603:   PetscCall(MatAssemblyBegin(pointSurfGrad, MAT_FINAL_ASSEMBLY));
3604:   PetscCall(MatAssemblyEnd(pointSurfGrad, MAT_FINAL_ASSEMBLY));

3606:   if (fullGeomGrad) {
3607:     // Calculate Surface Area and Volume Control Point and Control Point Weight Gradients
3608:     //    Note: This is much slower than above due to a new solid geometry being created for
3609:     //          each change in Control Point and Control Point Weight. However, this method
3610:     //          will provide the Volume Gradient.

3612:     // Get Current Face Surface Area
3613:     PetscScalar bodyVol, bodySA, bodyData[14];
3614:     PetscCall(EG_getMassProperties(body, bodyData)); // Does not have an EGlite version KNOWN_ISSUE
3615:     bodyVol = bodyData[0];
3616:     bodySA  = bodyData[1];

3618:     // Cycle through Control Points
3619:     for (int ii = 0; ii < totalNumCPs; ++ii) { // ii should also be the row in cpEquiv for the Control Point
3620:       // Cycle through X, Y, Z, W changes
3621:       for (int jj = 0; jj < 4; ++jj) {
3622:         // Cycle Through Faces
3623:         double denomNew = 0.0, denomOld = 0.0;
3624:         double deltaCoord = 1.0E-4;
3625:         ego    newGeom[Nf];
3626:         ego    newFaces[Nf];
3627:         for (int kk = 0; kk < Nf; ++kk) {
3628:           ego      face;
3629:           PetscInt currFID = kk + 1;

3631:           if (islite) {
3632:             // Get Current FACE
3633:             PetscCallEGADS(EGlite_objectBodyTopo, body, FACE, currFID, &face);

3635:             // Get Geometry Object for the Current FACE
3636:             PetscCallEGADS(EGlite_getTopology, face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses);
3637:             PetscCallEGADS(EGlite_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
3638:           } else {
3639:             // Get Current FACE
3640:             PetscCallEGADS(EG_objectBodyTopo, body, FACE, currFID, &face);

3642:             // Get Geometry Object for the Current FACE
3643:             PetscCallEGADS(EG_getTopology, face, &fgeom, &foclass, &fmtype, fdata, &Nl, &lobjs, &lsenses);
3644:             PetscCallEGADS(EG_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
3645:           }

3647:           // Make a new SURFACE Geometry by changing the location of the Control Points
3648:           int    prvSize = bpinfo[3] + bpinfo[6] + (4 * bpinfo[2] * bpinfo[5]);
3649:           double nbprv[prvSize];

3651:           // Reinitialize nbprv[] values because we only want to change one value at a time
3652:           for (int mm = 0; mm < prvSize; ++mm) nbprv[mm] = bprv[mm];

3654:           // Get Control Point Row and Column Start for cpEquiv
3655:           PetscHashIter Witer;
3656:           PetscBool     Wfound;
3657:           PetscInt      faceWStartRow;
3658:           PetscCall(PetscHMapIFind(faceCPWeightsRow_Start, currFID, &Witer, &Wfound));
3659:           PetscCheck(Wfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Weights Hash Table");
3660:           PetscCall(PetscHMapIGet(faceCPWeightsRow_Start, currFID, &faceWStartRow));

3662:           // Modify the Current Control Point on this FACE and All Other FACES
3663:           // IMPORTANT!!! If you do not move all identical Control Points on other FACES
3664:           //              you will not generate a solid body. You will generate a set of
3665:           //              disconnected surfaces that have gap(s) between them.
3666:           int offset  = bpinfo[3] + bpinfo[6];
3667:           int wOffset = offset + (3 * bpinfo[2] * bpinfo[5]);
3668:           for (int mm = 0; mm < bpinfo[2] * bpinfo[5]; ++mm) {
3669:             PetscScalar matValue;
3670:             PetscCall(MatGetValue(cpEquiv, ii, faceWStartRow + mm, &matValue));

3672:             if (matValue > 0.0) {
3673:               if (jj == 0) { //X
3674:                 nbprv[offset + (3 * mm) + 0] = bprv[offset + (3 * mm) + 0] + deltaCoord;
3675:                 nbprv[offset + (3 * mm) + 1] = bprv[offset + (3 * mm) + 1];
3676:                 nbprv[offset + (3 * mm) + 2] = bprv[offset + (3 * mm) + 2];
3677:                 denomNew                     = nbprv[offset + (3 * mm) + 0];
3678:                 denomOld                     = bprv[offset + (3 * mm) + 0];
3679:               } else if (jj == 1) { //Y
3680:                 nbprv[offset + (3 * mm) + 0] = bprv[offset + (3 * mm) + 0];
3681:                 nbprv[offset + (3 * mm) + 1] = bprv[offset + (3 * mm) + 1] + deltaCoord;
3682:                 nbprv[offset + (3 * mm) + 2] = bprv[offset + (3 * mm) + 2];
3683:                 denomNew                     = nbprv[offset + (3 * mm) + 1];
3684:                 denomOld                     = bprv[offset + (3 * mm) + 1];
3685:               } else if (jj == 2) { //Z
3686:                 nbprv[offset + (3 * mm) + 0] = bprv[offset + (3 * mm) + 0];
3687:                 nbprv[offset + (3 * mm) + 1] = bprv[offset + (3 * mm) + 1];
3688:                 nbprv[offset + (3 * mm) + 2] = bprv[offset + (3 * mm) + 2] + deltaCoord;
3689:                 denomNew                     = nbprv[offset + (3 * mm) + 2];
3690:                 denomOld                     = bprv[offset + (3 * mm) + 2];
3691:               } else if (jj == 3) { // Weights
3692:                 nbprv[wOffset + mm] = bprv[wOffset + mm] + deltaCoord;
3693:                 denomNew            = nbprv[wOffset + mm];
3694:                 denomOld            = bprv[wOffset + mm];
3695:               } else {
3696:                 // currently do nothing
3697:               }
3698:             }
3699:           }

3701:           // Create New Surface Based on New Control Points or Weights
3702:           ego newgeom, context;
3703:           PetscCallEGADS(EG_getContext, face, &context);                                             // Does not have an EGlite_ versions   KNOWN_ISSUE
3704:           PetscCallEGADS(EG_makeGeometry, context, SURFACE, BSPLINE, NULL, bpinfo, nbprv, &newgeom); // Does not have an EGlite_ version KNOWN_ISSUE

3706:           // Create New FACE based on modified geometry
3707:           double newFaceRange[4];
3708:           int    newFacePeri;
3709:           if (islite) PetscCallEGADS(EGlite_getRange, newgeom, newFaceRange, &newFacePeri);
3710:           else PetscCallEGADS(EG_getRange, newgeom, newFaceRange, &newFacePeri);

3712:           ego newface;
3713:           PetscCallEGADS(EG_makeFace, newgeom, SFORWARD, newFaceRange, &newface); // Does not have an EGlite_ version KNOWN_ISSUE

3715:           // store new face for later assembly
3716:           newGeom[kk]  = newgeom;
3717:           newFaces[kk] = newface;
3718:         }

3720:         // X-WANT TO BUILD THE NEW GEOMETRY, X-GET NEW SA AND PERFORM dSA/dCPi CALCS HERE <---
3721:         // Sew New Faces together to get a new model
3722:         ego newmodel;
3723:         PetscCall(EG_sewFaces(Nf, newFaces, 0.0, 0, &newmodel)); // Does not have an EGlite_ version KNOWN_ISSUE

3725:         // Get Surface Area and Volume of New/Updated Solid Body
3726:         PetscScalar newData[14];
3727:         if (islite) PetscCallEGADS(EGlite_getTopology, newmodel, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);
3728:         else PetscCallEGADS(EG_getTopology, newmodel, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);

3730:         ego nbody = bodies[0];
3731:         PetscCall(EG_getMassProperties(nbody, newData)); // Does not have an EGlite_ version   KNOWN_ISSUE

3733:         PetscScalar dSAdCPi, dVdCPi;
3734:         PetscScalar nbodyVol = newData[0], nbodySA = newData[1];

3736:         // Calculate Gradients wrt to Control Points and Control Points Weights depending on jj value
3737:         dSAdCPi = (nbodySA - bodySA) / (denomNew - denomOld);
3738:         dVdCPi  = (nbodyVol - bodyVol) / (denomNew - denomOld);

3740:         if (jj < 3) {
3741:           // Gradienst wrt to Control Points
3742:           gradSACP[(ii * 3) + jj] = dSAdCPi;
3743:           gradVCP[(ii * 3) + jj]  = dVdCPi;
3744:         } else if (jj == 3) {
3745:           // Gradients wrt to Control Point Weights
3746:           gradSAW[ii] = dSAdCPi;
3747:           gradVW[ii]  = dVdCPi;
3748:         } else {
3749:           // Do Nothing
3750:         }
3751:         PetscCallEGADS(EG_deleteObject, newmodel);
3752:         for (int kk = 0; kk < Nf; ++kk) {
3753:           PetscCallEGADS(EG_deleteObject, newFaces[kk]);
3754:           PetscCallEGADS(EG_deleteObject, newGeom[kk]);
3755:         }
3756:       }
3757:     }
3758:   }
3759:   PetscCall(VecRestoreArrayWrite(gradSACPVec, &gradSACP));
3760:   PetscCall(VecRestoreArrayWrite(gradSAWVec, &gradSAW));
3761:   PetscCall(VecRestoreArrayWrite(gradVCPVec, &gradVCP));
3762:   PetscCall(VecRestoreArrayWrite(gradVWVec, &gradVW));
3763:   PetscCall(MatDestroy(&cpEquiv));

3765:   // Attach Surface Gradient Hash Table and Matrix to DM
3766:   {
3767:     PetscContainer surfGradOrgObj;

3769:     PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Gradient Hash Table", (PetscObject *)&surfGradOrgObj));
3770:     if (!surfGradOrgObj) {
3771:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &surfGradOrgObj));
3772:       PetscCall(PetscContainerSetPointer(surfGradOrgObj, pointSurfGradRow_Start));
3773:       PetscCall(PetscContainerSetCtxDestroy(surfGradOrgObj, DestroyHashMap));
3774:       PetscCall(PetscObjectCompose((PetscObject)dm, "Surface Gradient Hash Table", (PetscObject)surfGradOrgObj));
3775:       PetscCall(PetscContainerDestroy(&surfGradOrgObj));
3776:     } else {
3777:       PetscCall(PetscContainerSetPointer(surfGradOrgObj, pointSurfGradRow_Start));
3778:     }

3780:     PetscCall(PetscObjectCompose((PetscObject)dm, "Surface Gradient Matrix", (PetscObject)pointSurfGrad));
3781:     PetscCall(MatDestroy(&pointSurfGrad));

3783:     PetscCall(PetscObjectCompose((PetscObject)dm, "Surface Area Control Point Gradient", (PetscObject)gradSACPVec));
3784:     PetscCall(VecDestroy(&gradSACPVec));

3786:     PetscCall(PetscObjectCompose((PetscObject)dm, "Surface Area Weights Gradient", (PetscObject)gradSAWVec));
3787:     PetscCall(VecDestroy(&gradSAWVec));

3789:     if (fullGeomGrad) {
3790:       PetscCall(PetscObjectCompose((PetscObject)dm, "Volume Control Point Gradient", (PetscObject)gradVCPVec));
3791:       PetscCall(PetscObjectCompose((PetscObject)dm, "Volume Weights Gradient", (PetscObject)gradVWVec));
3792:     }
3793:     PetscCall(VecDestroy(&gradVCPVec));
3794:     PetscCall(VecDestroy(&gradVWVec));
3795:   }

3797:   // Could be replaced with DMPlexFreeGeomObject()
3798:   if (islite) EGlite_free(fobjs);
3799:   else EG_free(fobjs);
3800:   PetscFunctionReturn(PETSC_SUCCESS);
3801: #else
3802:   SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This method requires EGADS support. Reconfigure using --download-egads");
3803: #endif
3804: }

3806: /*@
3807:   DMPlexModifyGeomModel - Generates a new EGADS geometry model based in user provided Control Points and Control Points Weights.
3808:   Optionally, the function will inflate the `DM` to the new geometry and save the new geometry to a file.

3810:   Collective

3812:   Input Parameters:
3813: + dm          - The `DM` object representing the mesh with `PetscContainer` containing an EGADS geometry model
3814: . comm        - Used to generate `IS` in the function
3815: . newCP       - Array of [x, y, z] New/Updated Control Point Coordinates defining the geometry (See `DMPlexGeomDataAndGrads()` for format)
3816: . newW        - Array of New/Updated Control Point Weights associated with the Control Points defining the new geometry
3817: . autoInflate - Flag denoting if the user would like to inflate the DM points to the new geometry.
3818: . saveGeom    - Flag denoting if the user would like to save the new geometry to a file.
3819: - stpName     - Array indicating the name of the file to save the new geometry to. Extension must be included and will denote type of file written.
3820: .vb
3821:                       *.stp or *.step = STEP File
3822:                       *.igs or *.iges = IGES File
3823:                               *.egads = EGADS File
3824:                                *.brep = BRep File (OpenCASCADE File)
3825: .ve

3827:   Output Parameter:
3828: . dm - The updated DM object representing the mesh with `PetscContainer`s containing the updated/modified geometry

3830:   Level: intermediate

3832:   Notes:
3833:   Functionality not available for `DMPLEX`s with attached EGADSlite geometry files (.egadslite).

3835:   Requires `./configure` be run with `--download-egads`

3837:   Developer Note:
3838:   Why does this function take a `comm` argument? Why can't it use the MPI communicator in `dm`? This should be documented.

3840: .seealso: `DMPLEX`, `DMCreate()`, `DMPlexCreateGeom()`, `DMPlexCreateGeomFromFile()`, `DMPlexGeomDataAndGrads()`
3841: @*/
3842: PetscErrorCode DMPlexModifyGeomModel(DM dm, MPI_Comm comm, PetscScalar newCP[], PetscScalar newW[], PetscBool autoInflate, PetscBool saveGeom, const char *stpName) PeNS
3843: {
3844: #if PetscDefined(HAVE_EGADS)
3845:   /* EGADS/EGADSlite variables */
3846:   ego context, model, geom, *bodies, *lobjs, *fobjs;
3847:   int oclass, mtype, *senses, *lsenses;
3848:   int Nb, Nf, Nl, id;
3849:   /* PETSc variables */
3850:   DMLabel        bodyLabel, faceLabel, edgeLabel, vertexLabel;
3851:   PetscContainer modelObj, cpHashTableObj, wHashTableObj;
3852:   PetscHMapI     cpHashTable = NULL, wHashTable = NULL;
3853:   PetscBool      islite = PETSC_FALSE;
3854: #endif

3856: #if PetscDefined(HAVE_EGADS)
3857:   PetscFunctionBegin;
3858:   // Look to see if DM has a Container with either an EGADS or EGADSlite Model
3859:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
3860:   if (!modelObj) {
3861:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
3862:     islite = PETSC_TRUE;
3863:   }
3864:   PetscCheck(!islite, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot modify geometries defined by EGADSlite (.egadslite)! Please use another geometry file format STEP, IGES, EGADS or BRep");
3865:   PetscCheck(modelObj, PETSC_COMM_SELF, PETSC_ERR_SUP, "DM does not have an EGADS Geometry Model attached to it!");

3867:   // Get attached EGADS model (pointer)
3868:   PetscCall(PetscContainerGetPointer(modelObj, &model));

3870:   // Look to see if DM has Container for Geometry Control Point Data
3871:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Hash Table", (PetscObject *)&cpHashTableObj));
3872:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weights Hash Table", (PetscObject *)&wHashTableObj));

3874:   PetscCheck(cpHashTableObj && wHashTableObj, PETSC_COMM_SELF, PETSC_ERR_SUP, "DM does not have required Geometry Data attached! Please run DMPlexGeomDataAndGrads() Function first.");

3876:   // Get attached EGADS model Control Point and Weights Hash Tables and Data Arrays (pointer)
3877:   PetscCall(PetscContainerGetPointer(cpHashTableObj, &cpHashTable));
3878:   PetscCall(PetscContainerGetPointer(wHashTableObj, &wHashTable));

3880:   // Get the number of bodies and body objects in the model
3881:   if (islite) PetscCallEGADS(EGlite_getTopology, model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);
3882:   else PetscCallEGADS(EG_getTopology, model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses);

3884:   // Get all Faces on the body
3885:   ego body = bodies[0];
3886:   if (islite) PetscCallEGADS(EGlite_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);
3887:   else PetscCallEGADS(EG_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);

3889:   ego newGeom[Nf];
3890:   ego newFaces[Nf];

3892:   // Update Control Point and Weight definitions for each surface
3893:   for (int jj = 0; jj < Nf; ++jj) {
3894:     ego     face = fobjs[jj];
3895:     ego     bRef, bPrev, bNext;
3896:     ego     fgeom;
3897:     int     offset;
3898:     int     boclass, bmtype, *bpinfo;
3899:     double *bprv;

3901:     // Get FACE ID and other Geometry Data
3902:     if (islite) {
3903:       id = EGlite_indexBodyTopo(body, face);
3904:       PetscCallEGADS(EGlite_getTopology, face, &fgeom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses);
3905:       PetscCallEGADS(EGlite_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
3906:       PetscCallEGADS(EGlite_getInfo, fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext);
3907:     } else {
3908:       id = EG_indexBodyTopo(body, face);
3909:       PetscCallEGADS(EG_getTopology, face, &fgeom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses);
3910:       PetscCallEGADS(EG_getGeometry, fgeom, &boclass, &bmtype, &bRef, &bpinfo, &bprv);
3911:       PetscCallEGADS(EG_getInfo, fgeom, &boclass, &bmtype, &bRef, &bPrev, &bNext);
3912:     }

3914:     // Update Control Points
3915:     PetscHashIter CPiter, Witer;
3916:     PetscBool     CPfound, Wfound;
3917:     PetscInt      faceCPStartRow, faceWStartRow;

3919:     PetscCall(PetscHMapIFind(cpHashTable, id, &CPiter, &CPfound));
3920:     PetscCheck(CPfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Hash Table");
3921:     PetscCall(PetscHMapIGet(cpHashTable, id, &faceCPStartRow));

3923:     PetscCall(PetscHMapIFind(wHashTable, id, &Witer, &Wfound));
3924:     PetscCheck(Wfound, PETSC_COMM_SELF, PETSC_ERR_SUP, "FACE ID not found in Control Point Weights Hash Table");
3925:     PetscCall(PetscHMapIGet(wHashTable, id, &faceWStartRow));

3927:     // UPDATE CONTROL POINTS Locations
3928:     offset = bpinfo[3] + bpinfo[6];
3929:     for (int ii = 0; ii < 3 * bpinfo[2] * bpinfo[5]; ++ii) bprv[offset + ii] = newCP[faceCPStartRow + ii];

3931:     // UPDATE CONTROL POINT WEIGHTS
3932:     offset = bpinfo[3] + bpinfo[6] + 3 * bpinfo[2] * bpinfo[5];
3933:     for (int ii = 0; ii < bpinfo[2] * bpinfo[5]; ++ii) bprv[offset + ii] = newW[faceWStartRow + ii];

3935:     // Get Context from FACE
3936:     context = NULL;
3937:     PetscCallEGADS(EG_getContext, face, &context); // Does not have an EGlite_ version  KNOWN_ISSUE

3939:     // Create New Surface
3940:     ego newgeom;
3941:     PetscCallEGADS(EG_makeGeometry, context, SURFACE, BSPLINE, NULL, bpinfo, bprv, &newgeom); // Does not have an EGlite_ version KNOWN_ISSUE

3943:     // Create new FACE based on new SURFACE geometry
3944:     double data[4];
3945:     int    periodic;
3946:     if (islite) PetscCallEGADS(EGlite_getRange, newgeom, data, &periodic);
3947:     else PetscCallEGADS(EG_getRange, newgeom, data, &periodic);

3949:     ego newface;
3950:     PetscCallEGADS(EG_makeFace, newgeom, SFORWARD, data, &newface); // Does not have an EGlite_ version KNOWN_ISSUE
3951:     newGeom[jj]  = newgeom;
3952:     newFaces[jj] = newface;
3953:   }
3954:   // Could be replaced by DMPlexFreeGeomObject
3955:   if (islite) EGlite_free(fobjs);
3956:   else EG_free(fobjs);

3958:   // Sew New Faces together to get a new model
3959:   ego newmodel;
3960:   PetscCall(EG_sewFaces(Nf, newFaces, 0.0, 0, &newmodel)); // Does not have an EGlite_ version   KNOWN_ISSUE
3961:   for (PetscInt f = 0; f < Nf; ++f) {
3962:     PetscCallEGADS(EG_deleteObject, newFaces[f]);
3963:     PetscCallEGADS(EG_deleteObject, newGeom[f]);
3964:   }

3966:   // Get the total number of NODEs on the original geometry. (This will be the same for the new geometry)
3967:   int  totalNumNode;
3968:   ego *nobjTotal;
3969:   if (islite) {
3970:     PetscCallEGADS(EGlite_getBodyTopos, body, NULL, NODE, &totalNumNode, &nobjTotal);
3971:     EGlite_free(nobjTotal);
3972:   } else {
3973:     PetscCallEGADS(EG_getBodyTopos, body, NULL, NODE, &totalNumNode, &nobjTotal);
3974:     EG_free(nobjTotal);
3975:   } // Could be replaced with DMPlexFreeGeomObject

3977:   // Initialize vector to store equivalent NODE indices between the 2 geometries
3978:   // FORMAT :: vector index is the Original Geometry's NODE ID, the vector Value is the New Geometry's NODE ID
3979:   int nodeIDEquiv[totalNumNode + 1];

3981:   // Now we need to Map the NODE and EDGE IDs from each Model
3982:   if (islite) PetscCallEGADS(EGlite_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);
3983:   else PetscCallEGADS(EG_getBodyTopos, body, NULL, FACE, &Nf, &fobjs);

3985:   // New CAD
3986:   ego *newbodies, newgeomtest, *nfobjs;
3987:   int  nNf, newNb, newoclass, newmtype, *newsenses;
3988:   if (islite) PetscCallEGADS(EGlite_getTopology, newmodel, &newgeomtest, &newoclass, &newmtype, NULL, &newNb, &newbodies, &newsenses);
3989:   else PetscCallEGADS(EG_getTopology, newmodel, &newgeomtest, &newoclass, &newmtype, NULL, &newNb, &newbodies, &newsenses);

3991:   ego newbody = newbodies[0];
3992:   if (islite) PetscCallEGADS(EGlite_getBodyTopos, newbody, NULL, FACE, &nNf, &nfobjs);
3993:   else PetscCallEGADS(EG_getBodyTopos, newbody, NULL, FACE, &nNf, &nfobjs);

3995:   PetscCheck(newNb == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ERROR :: newNb > 1 || newNb = %d", newNb);

3997:   // Find Equivalent Nodes
3998:   for (int ii = 0; ii < Nf; ++ii) {
3999:     double fdata[4];
4000:     int    peri;

4002:     // Get Current FACE [u, v] Ranges
4003:     if (islite) PetscCallEGADS(EGlite_getRange, fobjs[ii], fdata, &peri);
4004:     else PetscCallEGADS(EG_getRange, fobjs[ii], fdata, &peri);

4006:     // Equate NODE IDs between 2 FACEs by working through (u, v) limits of FACE
4007:     for (int jj = 0; jj < 2; ++jj) {
4008:       for (int kk = 2; kk < 4; ++kk) {
4009:         double params[2] = {fdata[jj], fdata[kk]};
4010:         double eval[18];
4011:         if (islite) PetscCallEGADS(EGlite_evaluate, fobjs[ii], params, eval);
4012:         else PetscCallEGADS(EG_evaluate, fobjs[ii], params, eval);

4014:         // Original Body
4015:         ego *nobjsOrigFace;
4016:         int  origNn;
4017:         if (islite) PetscCallEGADS(EGlite_getBodyTopos, body, fobjs[ii], NODE, &origNn, &nobjsOrigFace);
4018:         else PetscCallEGADS(EG_getBodyTopos, body, fobjs[ii], NODE, &origNn, &nobjsOrigFace);

4020:         double minVal = 1.0E10;
4021:         double evalCheck[18];
4022:         int    equivOrigNodeID = -1;
4023:         for (int mm = 0; mm < origNn; ++mm) {
4024:           double delta = 1.0E10;
4025:           if (islite) PetscCallEGADS(EGlite_evaluate, nobjsOrigFace[mm], NULL, evalCheck);
4026:           else PetscCallEGADS(EG_evaluate, nobjsOrigFace[mm], NULL, evalCheck);

4028:           delta = PetscSqrtReal(PetscSqr(evalCheck[0] - eval[0]) + PetscSqr(evalCheck[1] - eval[1]) + PetscSqr(evalCheck[2] - eval[2]));

4030:           if (delta < minVal) {
4031:             if (islite) equivOrigNodeID = EGlite_indexBodyTopo(body, nobjsOrigFace[mm]);
4032:             else equivOrigNodeID = EG_indexBodyTopo(body, nobjsOrigFace[mm]);

4034:             minVal = delta;
4035:           }
4036:         }
4037:         // Could be replaced with DMPlexFreeGeomObject
4038:         if (islite) EGlite_free(nobjsOrigFace);
4039:         else EG_free(nobjsOrigFace);

4041:         // New Body
4042:         ego *nobjsNewFace;
4043:         int  newNn;
4044:         if (islite) PetscCallEGADS(EGlite_getBodyTopos, newbody, nfobjs[ii], NODE, &newNn, &nobjsNewFace);
4045:         else PetscCallEGADS(EG_getBodyTopos, newbody, nfobjs[ii], NODE, &newNn, &nobjsNewFace);

4047:         minVal             = 1.0E10;
4048:         int equivNewNodeID = -1;
4049:         for (int mm = 0; mm < newNn; ++mm) {
4050:           double delta = 1.0E10;
4051:           if (islite) PetscCallEGADS(EGlite_evaluate, nobjsNewFace[mm], NULL, evalCheck);
4052:           else PetscCallEGADS(EG_evaluate, nobjsNewFace[mm], NULL, evalCheck);

4054:           delta = PetscSqrtReal(PetscSqr(evalCheck[0] - eval[0]) + PetscSqr(evalCheck[1] - eval[1]) + PetscSqr(evalCheck[2] - eval[2]));

4056:           if (delta < minVal) {
4057:             if (islite) equivNewNodeID = EGlite_indexBodyTopo(newbody, nobjsNewFace[mm]);
4058:             else equivNewNodeID = EG_indexBodyTopo(newbody, nobjsNewFace[mm]);

4060:             minVal = delta;
4061:           }
4062:         }
4063:         if (islite) EGlite_free(nobjsNewFace);
4064:         else EG_free(nobjsNewFace);

4066:         // Store equivalent NODE IDs
4067:         nodeIDEquiv[equivOrigNodeID] = equivNewNodeID;
4068:       }
4069:     }
4070:   }

4072:   // Find Equivalent EDGEs
4073:   //   Get total number of EDGEs on Original Geometry
4074:   int  totalNumEdge;
4075:   ego *eobjsOrig;
4076:   if (islite) {
4077:     PetscCallEGADS(EGlite_getBodyTopos, body, NULL, EDGE, &totalNumEdge, &eobjsOrig);
4078:     EGlite_free(eobjsOrig);
4079:   } else {
4080:     PetscCallEGADS(EG_getBodyTopos, body, NULL, EDGE, &totalNumEdge, &eobjsOrig);
4081:     EG_free(eobjsOrig);
4082:   }

4084:   //   Get total number of EDGEs on New Geometry
4085:   int  totalNumEdgeNew;
4086:   ego *eobjsNew;
4087:   if (islite) {
4088:     PetscCallEGADS(EGlite_getBodyTopos, newbody, NULL, EDGE, &totalNumEdgeNew, &eobjsNew);
4089:     EGlite_free(eobjsNew);
4090:   } else {
4091:     PetscCallEGADS(EG_getBodyTopos, newbody, NULL, EDGE, &totalNumEdgeNew, &eobjsNew);
4092:     EG_free(eobjsNew);
4093:   }

4095:   // Initialize EDGE ID equivalent vector
4096:   // FORMAT :: vector index is the Original Geometry's EDGE ID, the vector Value is the New Geometry's EDGE ID
4097:   int edgeIDEquiv[totalNumEdge + 1];

4099:   // Find Equivalent EDGEs
4100:   for (int ii = 0; ii < Nf; ++ii) {
4101:     // Get Original Geometry EDGE's NODEs
4102:     int numOrigEdge, numNewEdge;
4103:     if (islite) {
4104:       PetscCallEGADS(EGlite_getBodyTopos, body, fobjs[ii], EDGE, &numOrigEdge, &eobjsOrig);
4105:       PetscCallEGADS(EGlite_getBodyTopos, newbody, nfobjs[ii], EDGE, &numNewEdge, &eobjsNew);
4106:     } else {
4107:       PetscCallEGADS(EG_getBodyTopos, body, fobjs[ii], EDGE, &numOrigEdge, &eobjsOrig);
4108:       PetscCallEGADS(EG_getBodyTopos, newbody, nfobjs[ii], EDGE, &numNewEdge, &eobjsNew);
4109:     }

4111:     // new loop below
4112:     for (int nn = 0; nn < numOrigEdge; ++nn) {
4113:       ego origEdge = eobjsOrig[nn];
4114:       ego geomEdgeOrig, *nobjsOrig;
4115:       int oclassEdgeOrig, mtypeEdgeOrig;
4116:       int NnOrig, *nsensesEdgeOrig;

4118:       if (islite) PetscCallEGADS(EGlite_getTopology, origEdge, &geomEdgeOrig, &oclassEdgeOrig, &mtypeEdgeOrig, NULL, &NnOrig, &nobjsOrig, &nsensesEdgeOrig);
4119:       else PetscCallEGADS(EG_getTopology, origEdge, &geomEdgeOrig, &oclassEdgeOrig, &mtypeEdgeOrig, NULL, &NnOrig, &nobjsOrig, &nsensesEdgeOrig);

4121:       PetscBool isSame = PETSC_FALSE;
4122:       for (int jj = 0; jj < numNewEdge; ++jj) {
4123:         ego newEdge = eobjsNew[jj];
4124:         ego geomEdgeNew, *nobjsNew;
4125:         int oclassEdgeNew, mtypeEdgeNew;
4126:         int NnNew, *nsensesEdgeNew;

4128:         if (islite) PetscCallEGADS(EGlite_getTopology, newEdge, &geomEdgeNew, &oclassEdgeNew, &mtypeEdgeNew, NULL, &NnNew, &nobjsNew, &nsensesEdgeNew);
4129:         else PetscCallEGADS(EG_getTopology, newEdge, &geomEdgeNew, &oclassEdgeNew, &mtypeEdgeNew, NULL, &NnNew, &nobjsNew, &nsensesEdgeNew);

4131:         if (mtypeEdgeOrig == mtypeEdgeNew) {
4132:           // Only operate if the EDGE types are the same
4133:           for (int kk = 0; kk < NnNew; ++kk) {
4134:             int nodeIDOrigGeom, nodeIDNewGeom;
4135:             if (islite) {
4136:               nodeIDOrigGeom = EGlite_indexBodyTopo(body, nobjsOrig[kk]);
4137:               nodeIDNewGeom  = EGlite_indexBodyTopo(newbody, nobjsNew[kk]);
4138:             } else {
4139:               nodeIDOrigGeom = EG_indexBodyTopo(body, nobjsOrig[kk]);
4140:               nodeIDNewGeom  = EG_indexBodyTopo(newbody, nobjsNew[kk]);
4141:             }

4143:             if (nodeIDNewGeom == nodeIDEquiv[nodeIDOrigGeom]) {
4144:               isSame = PETSC_TRUE;
4145:             } else {
4146:               isSame = PETSC_FALSE;
4147:               kk     = NnNew; // skip ahead because first NODE failed test and order is important
4148:             }
4149:           }

4151:           if (isSame == PETSC_TRUE) {
4152:             int edgeIDOrig, edgeIDNew;
4153:             if (islite) {
4154:               edgeIDOrig = EGlite_indexBodyTopo(body, origEdge);
4155:               edgeIDNew  = EGlite_indexBodyTopo(newbody, newEdge);
4156:             } else {
4157:               edgeIDOrig = EG_indexBodyTopo(body, origEdge);
4158:               edgeIDNew  = EG_indexBodyTopo(newbody, newEdge);
4159:             }

4161:             edgeIDEquiv[edgeIDOrig] = edgeIDNew;
4162:             jj                      = numNewEdge;
4163:           }
4164:         }
4165:       }
4166:     }
4167:     if (islite) {
4168:       EGlite_free(eobjsOrig);
4169:       EGlite_free(eobjsNew);
4170:     } else {
4171:       EG_free(eobjsOrig);
4172:       EG_free(eobjsNew);
4173:     }
4174:   }
4175:   if (islite) {
4176:     EGlite_free(fobjs);
4177:     EGlite_free(nfobjs);
4178:   } else {
4179:     EG_free(fobjs);
4180:     EG_free(nfobjs);
4181:   }

4183:   // Modify labels to point to the IDs on the new Geometry
4184:   IS isNodeID, isEdgeID;

4186:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
4187:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
4188:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
4189:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

4191:   PetscCall(ISCreateGeneral(comm, totalNumNode + 1, nodeIDEquiv, PETSC_COPY_VALUES, &isNodeID));
4192:   PetscCall(ISCreateGeneral(comm, totalNumEdge + 1, edgeIDEquiv, PETSC_COPY_VALUES, &isEdgeID));
4193:   /* Do not perform check. Np may != Nv due to Degenerate Geometry which is not stored in labels.               */
4194:   /* We do not know in advance which IDs have been omitted. This may also change due to geometry modifications. */
4195:   PetscCall(DMLabelRewriteValues(vertexLabel, isNodeID));
4196:   PetscCall(DMLabelRewriteValues(edgeLabel, isEdgeID));
4197:   PetscCall(ISDestroy(&isNodeID));
4198:   PetscCall(ISDestroy(&isEdgeID));

4200:   // Attempt to point to the new geometry
4201:   PetscCallEGADS(EG_deleteObject, model);
4202:   PetscCall(PetscContainerSetPointer(modelObj, newmodel));

4204:   // save updated model to file
4205:   if (saveGeom == PETSC_TRUE && stpName != NULL) PetscCall(EG_saveModel(newmodel, stpName));

4207:   // Inflate Mesh to EGADS Model
4208:   if (autoInflate == PETSC_TRUE) PetscCall(DMPlexInflateToGeomModel(dm, PETSC_TRUE));
4209:   PetscFunctionReturn(PETSC_SUCCESS);
4210: #else
4211:   SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This method requires EGADS support. Reconfigure using --download-egads");
4212: #endif
4213: }

4215: /*@
4216:   DMPlexGetGeomModelTUV - Gets the [t] (EDGES) and [u, v] (FACES) geometry parameters of DM points that are associated geometry relationships. Requires a DM with an EGADS model attached.

4218:   Collective

4220:   Input Parameter:
4221: . dm - The DM object representing the mesh with `PetscContainer` containing an EGADS geometry model

4223:   Level: intermediate

4225: .seealso: `DMPLEX`, `DMCreate()`, `DMPlexCreateGeom()`, `DMPlexCreateGeomFromFile()`, `DMPlexGeomDataAndGrads()`
4226: @*/
4227: PetscErrorCode DMPlexGetGeomModelTUV(DM dm) PeNS
4228: {
4229: #if PetscDefined(HAVE_EGADS)
4230:   /* EGADS Variables */
4231:   ego    model, geom, body, face, edge;
4232:   ego   *bodies;
4233:   int    Nb, oclass, mtype, *senses;
4234:   double result[4];
4235:   /* PETSc Variables */
4236:   DM             cdm;
4237:   PetscContainer modelObj;
4238:   DMLabel        bodyLabel, faceLabel, edgeLabel, vertexLabel;
4239:   Vec            coordinates;
4240:   PetscScalar   *coords;
4241:   PetscInt       bodyID, faceID, edgeID, vertexID;
4242:   PetscInt       cdim, vStart, vEnd, v;
4243:   PetscBool      islite = PETSC_FALSE;
4244: #endif

4246:   PetscFunctionBegin;
4247: #if PetscDefined(HAVE_EGADS)
4248:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4249:   if (!modelObj) {
4250:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4251:     islite = PETSC_TRUE;
4252:   }
4253:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);

4255:   PetscCall(DMGetCoordinateDim(dm, &cdim));
4256:   PetscCall(DMGetCoordinateDM(dm, &cdm));
4257:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
4258:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
4259:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
4260:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
4261:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

4263:   PetscCall(PetscContainerGetPointer(modelObj, &model));

4265:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
4266:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));

4268:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
4269:   PetscCall(VecGetArrayWrite(coordinates, &coords));

4271:   // Define t, u, v arrays to be stored in a PetscContainer after populated
4272:   PetscScalar *t_point, *u_point, *v_point;
4273:   PetscCall(PetscMalloc1(vEnd - vStart, &t_point));
4274:   PetscCall(PetscMalloc1(vEnd - vStart, &u_point));
4275:   PetscCall(PetscMalloc1(vEnd - vStart, &v_point));

4277:   for (v = vStart; v < vEnd; ++v) {
4278:     PetscScalar *vcoords;

4280:     PetscCall(DMLabelGetValue(bodyLabel, v, &bodyID));
4281:     PetscCall(DMLabelGetValue(faceLabel, v, &faceID));
4282:     PetscCall(DMLabelGetValue(edgeLabel, v, &edgeID));
4283:     PetscCall(DMLabelGetValue(vertexLabel, v, &vertexID));

4285:     // TODO Figure out why this is unknown sometimes
4286:     if (bodyID < 0 && Nb == 1) bodyID = 0;
4287:     PetscCheck(bodyID >= 0 && bodyID < Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Body %" PetscInt_FMT " for vertex %" PetscInt_FMT " is not in [0, %d)", bodyID, v, Nb);
4288:     body = bodies[bodyID];

4290:     PetscCall(DMPlexPointLocalRef(cdm, v, coords, (void *)&vcoords));
4291:     if (edgeID > 0) {
4292:       /* Snap to EDGE at nearest location */
4293:       double params[1];

4295:       if (islite) {
4296:         PetscCall(EGlite_objectBodyTopo(body, EDGE, edgeID, &edge));
4297:         PetscCall(EGlite_invEvaluate(edge, vcoords, params, result));
4298:       } // Get (t) of nearest point on EDGE
4299:       else {
4300:         PetscCall(EG_objectBodyTopo(body, EDGE, edgeID, &edge));
4301:         PetscCall(EG_invEvaluate(edge, vcoords, params, result));
4302:       } // Get (t) of nearest point on EDGE

4304:       t_point[v - vStart] = params[0];
4305:       u_point[v - vStart] = 0.0;
4306:       v_point[v - vStart] = 0.0;
4307:     } else if (faceID > 0) {
4308:       /* Snap to FACE at nearest location */
4309:       double params[2];

4311:       if (islite) {
4312:         PetscCall(EGlite_objectBodyTopo(body, FACE, faceID, &face));
4313:         PetscCall(EGlite_invEvaluate(face, vcoords, params, result));
4314:       } // Get (x,y,z) of nearest point on FACE
4315:       else {
4316:         PetscCall(EG_objectBodyTopo(body, FACE, faceID, &face));
4317:         PetscCall(EG_invEvaluate(face, vcoords, params, result));
4318:       } // Get (x,y,z) of nearest point on FACE

4320:       t_point[v - vStart] = 0.0;
4321:       u_point[v - vStart] = params[0];
4322:       v_point[v - vStart] = params[1];
4323:     } else {
4324:       t_point[v - vStart] = 0.0;
4325:       u_point[v - vStart] = 0.0;
4326:       v_point[v - vStart] = 0.0;
4327:     }
4328:   }
4329:   PetscCall(VecRestoreArrayWrite(coordinates, &coords));
4330:   /* Clear out global coordinates */
4331:   PetscCall(VecDestroy(&dm->coordinates[0].x));

4333:   /* Store in PetscContainers */
4334:   {
4335:     PetscContainer t_pointObj, u_pointObj, v_pointObj;

4337:     PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Edge t Parameter", (PetscObject *)&t_pointObj));
4338:     if (!t_pointObj) {
4339:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &t_pointObj));
4340:       PetscCall(PetscContainerSetPointer(t_pointObj, t_point));
4341:       PetscCall(PetscObjectCompose((PetscObject)dm, "Point - Edge t Parameter", (PetscObject)t_pointObj));
4342:       PetscCall(PetscContainerSetCtxDestroy(t_pointObj, PetscCtxDestroyDefault));
4343:       PetscCall(PetscContainerDestroy(&t_pointObj));
4344:     } else {
4345:       void *old;

4347:       PetscCall(PetscContainerGetPointer(t_pointObj, &old));
4348:       PetscCall(PetscFree(old));
4349:       PetscCall(PetscContainerSetPointer(t_pointObj, t_point));
4350:     }

4352:     PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Face u Parameter", (PetscObject *)&u_pointObj));
4353:     if (!u_pointObj) {
4354:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &u_pointObj));
4355:       PetscCall(PetscContainerSetPointer(u_pointObj, u_point));
4356:       PetscCall(PetscObjectCompose((PetscObject)dm, "Point - Face u Parameter", (PetscObject)u_pointObj));
4357:       PetscCall(PetscContainerSetCtxDestroy(u_pointObj, PetscCtxDestroyDefault));
4358:       PetscCall(PetscContainerDestroy(&u_pointObj));
4359:     } else {
4360:       void *old;

4362:       PetscCall(PetscContainerGetPointer(u_pointObj, &old));
4363:       PetscCall(PetscFree(old));
4364:       PetscCall(PetscContainerSetPointer(u_pointObj, u_point));
4365:     }

4367:     PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Face v Parameter", (PetscObject *)&v_pointObj));
4368:     if (!v_pointObj) {
4369:       PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &v_pointObj));
4370:       PetscCall(PetscContainerSetPointer(v_pointObj, v_point));
4371:       PetscCall(PetscObjectCompose((PetscObject)dm, "Point - Face v Parameter", (PetscObject)v_pointObj));
4372:       PetscCall(PetscContainerSetCtxDestroy(v_pointObj, PetscCtxDestroyDefault));
4373:       PetscCall(PetscContainerDestroy(&v_pointObj));
4374:     } else {
4375:       void *old;

4377:       PetscCall(PetscContainerGetPointer(v_pointObj, &old));
4378:       PetscCall(PetscFree(old));
4379:       PetscCall(PetscContainerSetPointer(v_pointObj, v_point));
4380:     }
4381:   }
4382: #endif
4383:   PetscFunctionReturn(PETSC_SUCCESS);
4384: }

4386: /*@
4387:   DMPlexInflateToGeomModelUseTUV - Inflates the `DM` to the associated underlying geometry using the [t] {EDGES) and [u, v] (FACES} associated parameters.
4388:   Requires a `DM` with an EGADS model attached and a previous call to `DMPlexGetGeomModelTUV()`.

4390:   Collective

4392:   Input Parameter:
4393: . dm - The `DM` object representing the mesh with a `PetscContainer` containing an EGADS geometry model

4395:   Level: intermediate

4397:   Note:
4398:   The updated `DM` object inflated to the associated underlying geometry. This updates the [x, y, z] coordinates of `DM` points associated with geometry.

4400: .seealso: `DMPLEX`, `DMCreate()`, `DMPlexCreateGeom()`, `DMPlexCreateGeomFromFile()`, `DMPlexGeomDataAndGrads()`, `DMPlexGetGeomModelTUV()`
4401: @*/
4402: PetscErrorCode DMPlexInflateToGeomModelUseTUV(DM dm) PeNS
4403: {
4404: #if PetscDefined(HAVE_EGADS)
4405:   /* EGADS Variables */
4406:   ego    model, geom, body, face, edge, vertex;
4407:   ego   *bodies;
4408:   int    Nb, oclass, mtype, *senses;
4409:   double result[18], params[2];
4410:   /* PETSc Variables */
4411:   DM             cdm;
4412:   PetscContainer modelObj;
4413:   PetscContainer t_pointObj, u_pointObj, v_pointObj;
4414:   DMLabel        bodyLabel, faceLabel, edgeLabel, vertexLabel;
4415:   Vec            coordinates;
4416:   PetscScalar   *coords;
4417:   PetscScalar   *t_point, *u_point, *v_point;
4418:   PetscInt       bodyID, faceID, edgeID, vertexID;
4419:   PetscInt       cdim, d, vStart, vEnd, v;
4420:   PetscBool      islite = PETSC_FALSE;
4421: #endif

4423:   PetscFunctionBegin;
4424: #if PetscDefined(HAVE_EGADS)
4425:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4426:   if (!modelObj) {
4427:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4428:     islite = PETSC_TRUE;
4429:   }

4431:   PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Edge t Parameter", (PetscObject *)&t_pointObj));
4432:   PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Face u Parameter", (PetscObject *)&u_pointObj));
4433:   PetscCall(PetscObjectQuery((PetscObject)dm, "Point - Face v Parameter", (PetscObject *)&v_pointObj));

4435:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);
4436:   if (!t_pointObj) PetscFunctionReturn(PETSC_SUCCESS);
4437:   if (!u_pointObj) PetscFunctionReturn(PETSC_SUCCESS);
4438:   if (!v_pointObj) PetscFunctionReturn(PETSC_SUCCESS);

4440:   PetscCall(DMGetCoordinateDim(dm, &cdim));
4441:   PetscCall(DMGetCoordinateDM(dm, &cdm));
4442:   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
4443:   PetscCall(DMGetLabel(dm, "EGADS Body ID", &bodyLabel));
4444:   PetscCall(DMGetLabel(dm, "EGADS Face ID", &faceLabel));
4445:   PetscCall(DMGetLabel(dm, "EGADS Edge ID", &edgeLabel));
4446:   PetscCall(DMGetLabel(dm, "EGADS Vertex ID", &vertexLabel));

4448:   PetscCall(PetscContainerGetPointer(t_pointObj, &t_point));
4449:   PetscCall(PetscContainerGetPointer(u_pointObj, &u_point));
4450:   PetscCall(PetscContainerGetPointer(v_pointObj, &v_point));

4452:   PetscCall(PetscContainerGetPointer(modelObj, &model));

4454:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));
4455:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, &Nb, &bodies, &senses));

4457:   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
4458:   PetscCall(VecGetArrayWrite(coordinates, &coords));

4460:   for (v = vStart; v < vEnd; ++v) {
4461:     PetscScalar *vcoords;

4463:     PetscCall(DMLabelGetValue(bodyLabel, v, &bodyID));
4464:     PetscCall(DMLabelGetValue(faceLabel, v, &faceID));
4465:     PetscCall(DMLabelGetValue(edgeLabel, v, &edgeID));
4466:     PetscCall(DMLabelGetValue(vertexLabel, v, &vertexID));

4468:     // TODO Figure out why this is unknown sometimes
4469:     if (bodyID < 0 && Nb == 1) bodyID = 0;
4470:     PetscCheck(bodyID >= 0 && bodyID < Nb, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Body %" PetscInt_FMT " for vertex %" PetscInt_FMT " is not in [0, %d)", bodyID, v, Nb);
4471:     body = bodies[bodyID];

4473:     PetscCall(DMPlexPointLocalRef(cdm, v, coords, (void *)&vcoords));
4474:     if (vertexID > 0) {
4475:       /* Snap to Vertices */
4476:       if (islite) {
4477:         PetscCall(EGlite_objectBodyTopo(body, NODE, vertexID, &vertex));
4478:         PetscCall(EGlite_evaluate(vertex, NULL, result));
4479:       } else {
4480:         PetscCall(EG_objectBodyTopo(body, NODE, vertexID, &vertex));
4481:         PetscCall(EG_evaluate(vertex, NULL, result));
4482:       }
4483:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
4484:     } else if (edgeID > 0) {
4485:       /* Snap to EDGE */
4486:       params[0] = t_point[v - vStart];
4487:       if (islite) {
4488:         PetscCall(EGlite_objectBodyTopo(body, EDGE, edgeID, &edge));
4489:         PetscCall(EGlite_evaluate(edge, params, result));
4490:       } else {
4491:         PetscCall(EG_objectBodyTopo(body, EDGE, edgeID, &edge));
4492:         PetscCall(EG_evaluate(edge, params, result));
4493:       }
4494:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
4495:     } else if (faceID > 0) {
4496:       /* Snap to FACE */
4497:       params[0] = u_point[v - vStart];
4498:       params[1] = v_point[v - vStart];
4499:       if (islite) {
4500:         PetscCall(EGlite_objectBodyTopo(body, FACE, faceID, &face));
4501:         PetscCall(EGlite_evaluate(face, params, result));
4502:       } else {
4503:         PetscCall(EG_objectBodyTopo(body, FACE, faceID, &face));
4504:         PetscCall(EG_evaluate(face, params, result));
4505:       }
4506:       for (d = 0; d < cdim; ++d) vcoords[d] = result[d];
4507:     }
4508:   }
4509:   PetscCall(VecRestoreArrayWrite(coordinates, &coords));
4510:   /* Clear out global coordinates */
4511:   PetscCall(VecDestroy(&dm->coordinates[0].x));
4512: #endif
4513:   PetscFunctionReturn(PETSC_SUCCESS);
4514: }

4516: /*@
4517:   DMPlexInflateToGeomModel - Wrapper function allowing two methods for inflating refined meshes to the underlying geometric domain.

4519:   Collective

4521:   Input Parameters:
4522: + dm     - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4523: - useTUV - whether to inflate the `DMPLEX` to the underlying geometry
4524:            using (t) for nodes on EDGEs and (u, v) for nodes on FACEs or using the nodes (x, y, z) coordinates
4525:            and shortest distance routine.
4526:             If useTUV = PETSC_TRUE, use the (t) or (u, v) parameters to inflate the DMPlex to the CAD geometry.
4527:             If useTUV = PETSC_FALSE, use the nodes (x, y, z) coordinates and the shortest disctance routine.

4529:   Level: intermediate

4531:   Notes:
4532:   `DM` with nodal coordinates modified so that they lie on the EDGEs and FACEs of the underlying geometry.

4534:   (t) and (u, v) parameters for all `DMPLEX` nodes on EDGEs and FACEs are stored in arrays within `PetscContainer`s attached to the `DM`.
4535:   The containers have names "Point - Edge t Parameter", "Point - Face u Parameter", and "Point - Face v Parameter".
4536:   The arrays are organized by Point 0-based ID (i.e. [v-vstart] as defined in the DMPlex.

4538: .seealso: `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4539: @*/
4540: PetscErrorCode DMPlexInflateToGeomModel(DM dm, PetscBool useTUV) PeNS
4541: {
4542:   PetscFunctionBeginHot;
4543:   if (useTUV) {
4544:     PetscCall(DMPlexGetGeomModelTUV(dm));
4545:     PetscCall(DMPlexInflateToGeomModelUseTUV(dm));
4546:   } else {
4547:     PetscCall(DMPlexInflateToGeomModelUseXYZ(dm));
4548:   }
4549:   PetscFunctionReturn(PETSC_SUCCESS);
4550: }

4552: #if PetscDefined(HAVE_EGADS)
4553: /*@
4554:   DMPlexGetGeomModelBodies - Returns an array of `PetscGeom` BODY objects attached to the referenced geometric model entity as well as the number of BODYs.

4556:   Collective

4558:   Input Parameter:
4559: . dm - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object

4561:   Output Parameters:
4562: + bodies    - Array of PetscGeom BODY objects referenced by the geometric model.
4563: - numBodies - Number of BODYs referenced by the geometric model. Also the length of `bodies`.

4565:   Level: intermediate

4567: .seealso: `DMPlexGetGeomModelBodyShells()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4568: @*/
4569: PetscErrorCode DMPlexGetGeomModelBodies(DM dm, PetscGeom *bodies[], PetscInt *numBodies) PeNS
4570: {
4571:   PetscFunctionBeginHot;
4572:   PetscContainer modelObj;
4573:   PetscBool      islite = PETSC_FALSE;
4574:   ego            model, geom;
4575:   int            oclass, mtype;
4576:   int           *senses;

4578:   /* Determine which type of EGADS model is attached to the DM */
4579:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4580:   if (!modelObj) {
4581:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4582:     islite = PETSC_TRUE;
4583:   }

4585:   // Get attached EGADS or EGADSlite model (pointer)
4586:   PetscCall(PetscContainerGetPointer(modelObj, &model));

4588:   if (islite) PetscCall(EGlite_getTopology(model, &geom, &oclass, &mtype, NULL, numBodies, bodies, &senses));
4589:   else PetscCall(EG_getTopology(model, &geom, &oclass, &mtype, NULL, numBodies, bodies, &senses));
4590:   PetscFunctionReturn(PETSC_SUCCESS);
4591: }

4593: /*@
4594:   DMPlexGetGeomModelBodyShells - Returns an array of `PetscGeom` SHELL objects attached to the referenced BODY geometric entity as well as the number of SHELLs.

4596:   Collective

4598:   Input Parameters:
4599: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4600: - body - `PetscGeom` BODY object containing the SHELL objects of interest.

4602:   Output Parameters:
4603: + shells    - Array of `PetscGeom` SHELL objects referenced by the `PetscGeom` BODY object
4604: - numShells - Number of SHELLs referenced by the PetscGeom BODY object. Also the length of `shells`.

4606:   Level: intermediate

4608: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4609: @*/
4610: PetscErrorCode DMPlexGetGeomModelBodyShells(DM dm, PetscGeom body, PetscGeom *shells[], PetscInt *numShells) PeNS
4611: {
4612:   PetscFunctionBeginHot;
4613:   #if PetscDefined(HAVE_EGADS)
4614:   PetscContainer modelObj;
4615:   PetscBool      islite = PETSC_FALSE;

4617:   /* Determine which type of EGADS model is attached to the DM */
4618:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4619:   if (!modelObj) {
4620:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4621:     islite = PETSC_TRUE;
4622:   }

4624:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, SHELL, numShells, shells));
4625:   else PetscCall(EG_getBodyTopos(body, NULL, SHELL, numShells, shells));
4626:   #endif
4627:   PetscFunctionReturn(PETSC_SUCCESS);
4628: }

4630: /*@
4631:   DMPlexGetGeomModelBodyFaces - Returns an array of `PetscGeom` FACE objects attached to the referenced BODY geometric entity as well as the number of FACEs.

4633:   Collective

4635:   Input Parameters:
4636: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4637: - body - `PetscGeom` BODY object containing the FACE objects of interest.

4639:   Output Parameters:
4640: + faces    - Array of `PetscGeom` FACE objects referenced by the `PetscGeom` BODY object
4641: - numFaces - Number of FACEs referenced by the `PetscGeom` BODY object. Also the length of `faces`.

4643:   Level: intermediate

4645: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4646: @*/
4647: PetscErrorCode DMPlexGetGeomModelBodyFaces(DM dm, PetscGeom body, PetscGeom *faces[], PetscInt *numFaces) PeNS
4648: {
4649:   PetscFunctionBeginHot;
4650:   #if PetscDefined(HAVE_EGADS)
4651:   PetscContainer modelObj;
4652:   PetscBool      islite = PETSC_FALSE;

4654:   /* Determine which type of EGADS model is attached to the DM */
4655:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4656:   if (!modelObj) {
4657:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4658:     islite = PETSC_TRUE;
4659:   }

4661:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, FACE, numFaces, faces));
4662:   else PetscCall(EG_getBodyTopos(body, NULL, FACE, numFaces, faces));
4663:   #endif
4664:   PetscFunctionReturn(PETSC_SUCCESS);
4665: }

4667: /*@
4668:   DMPlexGetGeomModelBodyLoops - Returns an array of `PetscGeom` Loop objects attached to the referenced BODY geometric entity as well as the number of LOOPs.

4670:   Collective

4672:   Input Parameters:
4673: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4674: - body - `PetscGeom` BODY object containing the LOOP objects of interest.

4676:   Output Parameters:
4677: + loops    - Array of `PetscGeom` FACE objects referenced by the `PetscGeom` SHELL object
4678: - numLoops - Number of LOOPs referenced by the `PetscGeom` BODY object. Also the length of `loops`.

4680:   Level: intermediate

4682: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4683: @*/
4684: PetscErrorCode DMPlexGetGeomModelBodyLoops(DM dm, PetscGeom body, PetscGeom *loops[], PetscInt *numLoops) PeNS
4685: {
4686:   PetscFunctionBeginHot;
4687:   #if PetscDefined(HAVE_EGADS)
4688:   PetscContainer modelObj;
4689:   PetscBool      islite = PETSC_FALSE;

4691:   /* Determine which type of EGADS model is attached to the DM */
4692:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4693:   if (!modelObj) {
4694:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4695:     islite = PETSC_TRUE;
4696:   }

4698:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, LOOP, numLoops, loops));
4699:   else PetscCall(EG_getBodyTopos(body, NULL, LOOP, numLoops, loops));
4700:   #endif
4701:   PetscFunctionReturn(PETSC_SUCCESS);
4702: }

4704: /*@
4705:   DMPlexGetGeomModelShellFaces - Returns an array of `PetscGeom` FACE objects attached to the referenced SHELL geometric entity as well as the number of FACEs.

4707:   Collective

4709:   Input Parameters:
4710: + dm    - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4711: . body  - `PetscGeom` BODY object containing the FACE objects of interest.
4712: - shell - `PetscGeom` SHELL object with FACEs of interest.

4714:   Output Parameters:
4715: + faces    - Array of `PetscGeom` FACE objects referenced by the `PetscGeom` SHELL object
4716: - numFaces - Number of FACEs referenced by the `PetscGeom` SHELL object. Also the length of `faces`.

4718:   Level: intermediate

4720: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4721: @*/
4722: PetscErrorCode DMPlexGetGeomModelShellFaces(DM dm, PetscGeom body, PetscGeom shell, PetscGeom *faces[], PetscInt *numFaces) PeNS
4723: {
4724:   PetscFunctionBeginHot;
4725:   #if PetscDefined(HAVE_EGADS)
4726:   PetscContainer modelObj;
4727:   PetscBool      islite = PETSC_FALSE;

4729:   /* Determine which type of EGADS model is attached to the DM */
4730:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4731:   if (!modelObj) {
4732:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4733:     islite = PETSC_TRUE;
4734:   }

4736:   if (islite) PetscCall(EGlite_getBodyTopos(body, shell, FACE, numFaces, faces));
4737:   else PetscCall(EG_getBodyTopos(body, shell, FACE, numFaces, faces));
4738:   #endif
4739:   PetscFunctionReturn(PETSC_SUCCESS);
4740: }

4742: /*@
4743:   DMPlexGetGeomModelFaceLoops - Returns an array of `PetscGeom` LOOP objects attached to the referenced FACE geometric entity as well as the number of LOOPs.

4745:   Collective

4747:   Input Parameters:
4748: + dm   - The `DMPLEX` object with an attached PetscContainer storing a CAD Geometry object
4749: . body - `PetscGeom` BODY object containing the LOOP objects of interest.
4750: - face - `PetscGeom` FACE object with LOOPs of interest.

4752:   Output Parameters:
4753: + loops    - Array of `PetscGeom` LOOP objects referenced by the `PetscGeom` FACE object
4754: - numLoops - Number of LOOPs referenced by the `PetscGeom` FACE object. Also the length of `loops`.

4756:   Level: intermediate

4758: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4759: @*/
4760: PetscErrorCode DMPlexGetGeomModelFaceLoops(DM dm, PetscGeom body, PetscGeom face, PetscGeom *loops[], PetscInt *numLoops) PeNS
4761: {
4762:   PetscFunctionBeginHot;
4763:   #if PetscDefined(HAVE_EGADS)
4764:   PetscContainer modelObj;
4765:   PetscBool      islite = PETSC_FALSE;

4767:   /* Determine which type of EGADS model is attached to the DM */
4768:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4769:   if (!modelObj) {
4770:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4771:     islite = PETSC_TRUE;
4772:   }

4774:   if (islite) PetscCall(EGlite_getBodyTopos(body, face, LOOP, numLoops, loops));
4775:   else PetscCall(EG_getBodyTopos(body, face, LOOP, numLoops, loops));
4776:   #endif
4777:   PetscFunctionReturn(PETSC_SUCCESS);
4778: }

4780: /*@
4781:   DMPlexGetGeomModelFaceEdges - Returns an array of `PetscGeom` EDGE objects attached to the referenced FACE geometric entity as well as the number of EDGEs.

4783:   Collective

4785:   Input Parameters:
4786: + dm   - The `DMPLEX` object with an attached PetscContainer storing a CAD Geometry object
4787: . body - `PetscGeom` Body object containing the EDGE objects of interest.
4788: - face - `PetscGeom` FACE object with EDGEs of interest.

4790:   Output Parameters:
4791: + edges    - Array of `PetscGeom` EDGE objects referenced by the `PetscGeom` FACE object
4792: - numEdges - Number of EDGEs referenced by the `PetscGeom` FACE object. Also the length of `edges`.

4794:   Level: intermediate

4796: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4797: @*/
4798: PetscErrorCode DMPlexGetGeomModelFaceEdges(DM dm, PetscGeom body, PetscGeom face, PetscGeom *edges[], PetscInt *numEdges) PeNS
4799: {
4800:   PetscFunctionBeginHot;
4801:   #if PetscDefined(HAVE_EGADS)
4802:   PetscContainer modelObj;
4803:   PetscBool      islite = PETSC_FALSE;

4805:   /* Determine which type of EGADS model is attached to the DM */
4806:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4807:   if (!modelObj) {
4808:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4809:     islite = PETSC_TRUE;
4810:   }

4812:   if (islite) PetscCall(EGlite_getBodyTopos(body, face, EDGE, numEdges, edges));
4813:   else PetscCall(EG_getBodyTopos(body, face, EDGE, numEdges, edges));
4814:   #endif
4815:   PetscFunctionReturn(PETSC_SUCCESS);
4816: }

4818: /*@
4819:   DMPlexGetGeomModelBodyEdges - Returns an array of `PetscGeom` EDGE objects attached to the referenced BODY geometric entity as well as the number of EDGEs.

4821:   Collective

4823:   Input Parameters:
4824: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4825: - body - `PetscGeom` body object of interest.

4827:   Output Parameters:
4828: + edges    - Array of `PetscGeom` EDGE objects referenced by the `PetscGeom` BODY object
4829: - numEdges - Number of EDGEs referenced by the `PetscGeom` BODY object. Also the length of `edges`.

4831:   Level: intermediate

4833: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4834: @*/
4835: PetscErrorCode DMPlexGetGeomModelBodyEdges(DM dm, PetscGeom body, PetscGeom *edges[], PetscInt *numEdges) PeNS
4836: {
4837:   PetscFunctionBeginHot;
4838:   #if PetscDefined(HAVE_EGADS)
4839:   PetscContainer modelObj;
4840:   PetscBool      islite = PETSC_FALSE;

4842:   /* Determine which type of EGADS model is attached to the DM */
4843:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4844:   if (!modelObj) {
4845:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4846:     islite = PETSC_TRUE;
4847:   }

4849:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, EDGE, numEdges, edges));
4850:   else PetscCall(EG_getBodyTopos(body, NULL, EDGE, numEdges, edges));
4851:   #endif
4852:   PetscFunctionReturn(PETSC_SUCCESS);
4853: }

4855: /*@
4856:   DMPlexGetGeomModelBodyNodes - Returns an array of `PetscGeom` NODE objects attached to the referenced BODY geometric entity as well as the number of NODES.

4858:   Collective

4860:   Input Parameters:
4861: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4862: - body - `PetscGeom` body object of interest.

4864:   Output Parameters:
4865: + nodes    - Array of `PetscGeom` NODE objects referenced by the `PetscGeom` BODY object
4866: - numNodes - Number of NODEs referenced by the `PetscGeom` BODY object. Also the length of `nodes`.

4868:   Level: intermediate

4870: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4871: @*/
4872: PetscErrorCode DMPlexGetGeomModelBodyNodes(DM dm, PetscGeom body, PetscGeom *nodes[], PetscInt *numNodes) PeNS
4873: {
4874:   PetscFunctionBeginHot;
4875:   #if PetscDefined(HAVE_EGADS)
4876:   PetscContainer modelObj;
4877:   PetscBool      islite = PETSC_FALSE;

4879:   /* Determine which type of EGADS model is attached to the DM */
4880:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4881:   if (!modelObj) {
4882:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4883:     islite = PETSC_TRUE;
4884:   }

4886:   if (islite) PetscCall(EGlite_getBodyTopos(body, NULL, NODE, numNodes, nodes));
4887:   else PetscCall(EG_getBodyTopos(body, NULL, NODE, numNodes, nodes));
4888:   #endif
4889:   PetscFunctionReturn(PETSC_SUCCESS);
4890: }

4892: /*@
4893:   DMPlexGetGeomModelEdgeNodes - Returns an array of `PetscGeom` NODE objects attached to the referenced EDGE geometric entity as well as the number of NODES.

4895:   Collective

4897:   Input Parameters:
4898: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4899: . body - `PetscGeom` body object containing the EDGE object of interest.
4900: - edge - `PetscGeom` EDGE object with NODEs of interest.

4902:   Output Parameters:
4903: + nodes    - Array of `PetscGeom` NODE objects referenced by the `PetscGeom` EDGE object
4904: - numNodes - Number of Nodes referenced by the `PetscGeom` EDGE object. Also the length of `nodes`

4906:   Level: intermediate

4908: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4909: @*/
4910: PetscErrorCode DMPlexGetGeomModelEdgeNodes(DM dm, PetscGeom body, PetscGeom edge, PetscGeom *nodes[], PetscInt *numNodes) PeNS
4911: {
4912:   PetscFunctionBeginHot;
4913:   #if PetscDefined(HAVE_EGADS)
4914:   PetscContainer modelObj;
4915:   PetscBool      islite = PETSC_FALSE;

4917:   /* Determine which type of EGADS model is attached to the DM */
4918:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4919:   if (!modelObj) {
4920:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4921:     islite = PETSC_TRUE;
4922:   }

4924:   if (islite) PetscCall(EGlite_getBodyTopos(body, edge, NODE, numNodes, nodes));
4925:   else PetscCall(EG_getBodyTopos(body, edge, NODE, numNodes, nodes));
4926:   #endif
4927:   PetscFunctionReturn(PETSC_SUCCESS);
4928: }

4930: /*@
4931:   DMPlexGetGeomID - Returns ID number of the entity in the geometric (CAD) model

4933:   Collective

4935:   Input Parameters:
4936: + dm      - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4937: . body    - `PetscGeom` body object containing the lower level entity the ID number is being requested.
4938: - topoObj - `PetscGeom` SHELL, FACE, LOOP, EDGE, or NODE object for which ID number is being requested.

4940:   Output Parameter:
4941: . id - ID number of the entity

4943:   Level: intermediate

4945: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4946: @*/
4947: PetscErrorCode DMPlexGetGeomID(DM dm, PetscGeom body, PetscGeom topoObj, PetscInt *id) PeNS
4948: {
4949:   PetscFunctionBeginHot;
4950:   #if PetscDefined(HAVE_EGADS)
4951:   PetscContainer modelObj;
4952:   PetscBool      islite = PETSC_FALSE;
4953:   int            topoID;

4955:   /* Determine which type of EGADS model is attached to the DM */
4956:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4957:   if (!modelObj) {
4958:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
4959:     islite = PETSC_TRUE;
4960:   }

4962:   // Get Topology Object's ID
4963:   if (islite) topoID = EGlite_indexBodyTopo(body, topoObj);
4964:   else topoID = EG_indexBodyTopo(body, topoObj);

4966:   *id = topoID;
4967:   #endif
4968:   PetscFunctionReturn(PETSC_SUCCESS);
4969: }

4971: /*@
4972:   DMPlexGetGeomObject - Returns Geometry Object using the objects ID in the geometric (CAD) model

4974:   Collective

4976:   Input Parameters:
4977: + dm       - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
4978: . body     - `PetscGeom` body object containing the lower level entity the referenced by the ID.
4979: . geomType - Keyword SHELL, FACE, LOOP, EDGE, or NODE of the geometry type for which ID number is being requested.
4980: - geomID   - ID number of the geometry entity being requested.

4982:   Output Parameter:
4983: . geomObj - Geometry Object referenced by the ID number requested.

4985:   Level: intermediate

4987: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
4988: @*/
4989: PetscErrorCode DMPlexGetGeomObject(DM dm, PetscGeom body, PetscInt geomType, PetscInt geomID, PetscGeom *geomObj) PeNS
4990: {
4991:   PetscFunctionBeginHot;
4992:   #if PetscDefined(HAVE_EGADS)
4993:   PetscContainer modelObj;
4994:   PetscBool      islite = PETSC_FALSE;

4996:   /* Determine which type of EGADS model is attached to the DM */
4997:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
4998:   if (!modelObj) {
4999:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
5000:     islite = PETSC_TRUE;
5001:   }

5003:   // Get Topology Object's ID
5004:   if (islite) PetscCall(EGlite_objectBodyTopo(body, geomType, geomID, geomObj));
5005:   else PetscCall(EG_objectBodyTopo(body, geomType, geomID, geomObj));
5006:   #endif
5007:   PetscFunctionReturn(PETSC_SUCCESS);
5008: }

5010: /*@
5011:   DMPlexGetGeomFaceNumOfControlPoints - Returns the total number of Control Points (and associated Weights) defining a FACE of a Geometry

5013:   Not collective

5015:   Input Parameters:
5016: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
5017: - face - `PetscGeom` FACE object

5019:   Output Parameter:
5020: . numCntrlPnts - Number of Control Points (and Weights) defining the FACE

5022:   Level: intermediate

5024: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
5025: @*/
5026: PetscErrorCode DMPlexGetGeomFaceNumOfControlPoints(DM dm, PetscGeom face, PetscInt *numCntrlPnts) PeNS
5027: {
5028:   PetscFunctionBeginHot;
5029:   #if PetscDefined(HAVE_EGADS)
5030:   PetscContainer modelObj;
5031:   PetscBool      islite = PETSC_FALSE;
5032:   PetscGeom      geom, gRef;
5033:   PetscGeom     *lobjs;
5034:   int            Nl, oclass, mtype, goclass, gmtype;
5035:   int           *lsenses, *gpinfo;
5036:   double        *gprv;

5038:   /* Determine which type of EGADS model is attached to the DM */
5039:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5040:   if (!modelObj) {
5041:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
5042:     islite = PETSC_TRUE;
5043:   }

5045:   // Get Total Number of Control Points on FACE
5046:   if (islite) {
5047:     PetscCall(EGlite_getTopology(face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses));
5048:     PetscCall(EGlite_getGeometry(geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv));
5049:   } else {
5050:     PetscCall(EG_getTopology(face, &geom, &oclass, &mtype, NULL, &Nl, &lobjs, &lsenses));
5051:     PetscCall(EG_getGeometry(geom, &goclass, &gmtype, &gRef, &gpinfo, &gprv));
5052:   }

5054:   *numCntrlPnts = gpinfo[2] * gpinfo[5];
5055:   #endif
5056:   PetscFunctionReturn(PETSC_SUCCESS);
5057: }

5059: /*@
5060:   DMPlexGetGeomBodyMassProperties - Returns the Volume, Surface Area, Center of Gravity, and Inertia about the Body's Center of Gravity

5062:   Not collective

5064:   Input Parameters:
5065: + dm   - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object
5066: - body - `PetscGeom` BODY object

5068:   Output Parameters:
5069: + volume           - Volume of the CAD Body attached to the `DMPLEX`
5070: . surfArea         - Surface Area of the CAD Body attached to the DM Plex
5071: . centerOfGravity  - Array with the Center of Gravity coordinates of the CAD Body attached to the DM Plex [x, y, z]
5072: . COGsize          - Length of `centerOfGravity`
5073: . inertiaMatrixCOG - Array containing the Inertia about the Body's Center of Gravity [Ixx, Ixy, Ixz, Iyx, Iyy, Iyz, Izx, Izy, Izz]
5074: - IMCOGsize        - Length of `inertiaMatrixCOG` Array

5076:   Level: intermediate

5078: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
5079: @*/
5080: PetscErrorCode DMPlexGetGeomBodyMassProperties(DM dm, PetscGeom body, PetscScalar *volume, PetscScalar *surfArea, PetscScalar *centerOfGravity[], PetscInt *COGsize, PetscScalar *inertiaMatrixCOG[], PetscInt *IMCOGsize) PeNS
5081: {
5082:   PetscFunctionBeginHot;
5083:   #if PetscDefined(HAVE_EGADS)
5084:   PetscContainer modelObj;
5085:   PetscBool      islite = PETSC_FALSE;
5086:   PetscScalar    geomData[14];

5088:   /* Determine which type of EGADS model is attached to the DM */
5089:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5090:   if (!modelObj) {
5091:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
5092:     islite = PETSC_TRUE;
5093:     PetscCheck(modelObj, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot provide geometric mass properties for geometries defined by EGADSlite (.egadslite)! Please use another geometry file format STEP, IGES, EGADS or BRep");
5094:   }

5096:   if (islite) {
5097:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " WARNING!! This functionality is not supported for EGADSlite files. \n"));
5098:     PetscCall(PetscPrintf(PETSC_COMM_SELF, " All returned values are equal to 0 \n"));
5099:   } else PetscCall(EG_getMassProperties(body, geomData));

5101:   PetscCall(PetscMalloc2(3, centerOfGravity, 9, inertiaMatrixCOG));

5103:   if (!islite) {
5104:     *volume   = geomData[0];
5105:     *surfArea = geomData[1];
5106:     for (int ii = 2; ii < 5; ++ii) (*centerOfGravity)[ii - 2] = geomData[ii];
5107:     *COGsize = 3;
5108:     for (int ii = 5; ii < 14; ++ii) (*inertiaMatrixCOG)[ii - 5] = geomData[ii];
5109:     *IMCOGsize = 9;
5110:   } else {
5111:     *volume   = 0.;
5112:     *surfArea = 0.;
5113:     for (int ii = 2; ii < 5; ++ii) (*centerOfGravity)[ii - 2] = 0.;
5114:     *COGsize = 0;
5115:     for (int ii = 5; ii < 14; ++ii) (*inertiaMatrixCOG)[ii - 5] = 0.;
5116:     *IMCOGsize = 0;
5117:   }
5118:   #endif
5119:   PetscFunctionReturn(PETSC_SUCCESS);
5120: }

5122: /*@
5123:   DMPlexRestoreGeomBodyMassProperties - Release the arrays returned by `DMPlexGetGeomBodyMassProperties()`

5125:   Not Collective

5127:   Input Parameters:
5128: + dm               - The `DMPLEX` with an attached CAD geometry
5129: . body             - The `PetscGeom` body previously queried
5130: . volume           - The volume value (unused, retained for API symmetry)
5131: . surfArea         - The surface area value (unused, retained for API symmetry)
5132: . centerOfGravity  - Center-of-gravity array to free
5133: . COGsize          - The length of `centerOfGravity` (unused, retained for API symmetry)
5134: . inertiaMatrixCOG - Inertia-matrix-at-COG array to free
5135: - IMCOGsize        - The length of `inertiaMatrixCOG` (unused, retained for API symmetry)

5137:   Level: intermediate

5139: .seealso: `DMPlexGetGeomBodyMassProperties()`, `DMPlexGetGeomModelBodies()`
5140: @*/
5141: PetscErrorCode DMPlexRestoreGeomBodyMassProperties(DM dm, PetscGeom body, PetscScalar *volume, PetscScalar *surfArea, PetscScalar *centerOfGravity[], PetscInt *COGsize, PetscScalar *inertiaMatrixCOG[], PetscInt *IMCOGsize) PeNS
5142: {
5143:   PetscFunctionBegin;
5144:   PetscCall(PetscFree2(*centerOfGravity, *inertiaMatrixCOG));
5145:   PetscFunctionReturn(PETSC_SUCCESS);
5146: }

5148: /*@
5149:   DMPlexFreeGeomObject - Frees PetscGeom Objects

5151:   Not collective

5153:   Input Parameters:
5154: + dm      - The `DMPLEX` object with an attached PetscContainer storing a CAD Geometry object
5155: - geomObj - `PetscGeom` object

5157:   Level: intermediate

5159: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
5160: @*/
5161: PetscErrorCode DMPlexFreeGeomObject(DM dm, PetscGeom *geomObj) PeNS
5162: {
5163:   PetscFunctionBeginHot;
5164:   #if PetscDefined(HAVE_EGADS)
5165:   PetscContainer modelObj;
5166:   PetscBool      islite = PETSC_FALSE;

5168:   /* Determine which type of EGADS model is attached to the DM */
5169:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5170:   if (!modelObj) {
5171:     PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
5172:     islite = PETSC_TRUE;
5173:   }

5175:   if (islite) EGlite_free(geomObj);
5176:   else EG_free(geomObj);
5177:   #endif
5178:   PetscFunctionReturn(PETSC_SUCCESS);
5179: }

5181: /*@
5182:   DMPlexGetGeomCntrlPntAndWeightData - Gets Control Point and Associated Weight Data for the Geometry attached to the DMPlex

5184:   Not collective

5186:   Input Parameter:
5187: . dm - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object

5189:   Output Parameters:
5190: + cpHashTable       - Hash Table containing the relationship between FACE ID and Control Point IDs.
5191: . cpCoordDataLength - Length of cpCoordData Array.
5192: . cpCoordData       - Array holding the Geometry Control Point Coordinate Data.
5193: . maxNumEquiv       - Maximum Number of Equivalent Control Points (Control Points with the same coordinates but different IDs).
5194: . cpEquiv           - Matrix with a size(Number of Control Points, Number or Control Points) which stores a value of 1.0 in locations where Control Points with different IDS (row or column) have the same coordinates
5195: . wHashTable        - Hash Table containing the relationship between FACE ID and Control Point Weight.
5196: . wDataLength       - Length of wData Array.
5197: - wData             - Array holding the Weight for an associated Geometry Control Point.

5199:   Note:
5200:   Must Call `DMPlexGeomDataAndGrads()` before calling this function.

5202:   Level: intermediate

5204: .seealso: `DMPlexGetGeomModelBodies()`, `DMPlexGetGeomModelTUV()`, `DMPlexInflateToGeomModelUseTUV()`, `DMPlexInflateToGeomModelUseXYZ()`
5205: @*/
5206: PetscErrorCode DMPlexGetGeomCntrlPntAndWeightData(DM dm, PetscHMapI *cpHashTable, PetscInt *cpCoordDataLength, PetscScalar **cpCoordData, PetscInt *maxNumEquiv, Mat *cpEquiv, PetscHMapI *wHashTable, PetscInt *wDataLength, PetscScalar **wData) PeNS
5207: {
5208:   PetscContainer modelObj, cpHashTableObj, wHashTableObj, cpCoordDataLengthObj, wDataLengthObj, maxNumRelateObj;
5209:   Vec            cntrlPtCoordsVec, cntrlPtWeightsVec;
5210:   PetscInt      *cpCoordDataLengthPtr, *wDataLengthPtr, *maxNumEquivPtr;
5211:   PetscHMapI     cpHashTableTemp, wHashTableTemp;

5213:   PetscFunctionBeginHot;
5214:   /* Determine which type of EGADS model is attached to the DM */
5215:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5216:   if (!modelObj) PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));

5218:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);

5220:   // Look to see if DM has Container for Geometry Control Point Data
5221:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Hash Table", (PetscObject *)&cpHashTableObj));
5222:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Coordinates", (PetscObject *)&cntrlPtCoordsVec));
5223:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Coordinate Data Length", (PetscObject *)&cpCoordDataLengthObj));
5224:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weights Hash Table", (PetscObject *)&wHashTableObj));
5225:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data", (PetscObject *)&cntrlPtWeightsVec));
5226:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data Length", (PetscObject *)&wDataLengthObj));
5227:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Equivalency Matrix", (PetscObject *)cpEquiv));
5228:   PetscCall(PetscObjectQuery((PetscObject)dm, "Maximum Number Control Point Equivalency", (PetscObject *)&maxNumRelateObj));

5230:   // Get attached EGADS model Control Point and Weights Hash Tables and Data Arrays (pointer)
5231:   PetscCall(PetscContainerGetPointer(cpHashTableObj, &cpHashTableTemp));
5232:   PetscCall(PetscContainerGetPointer(cpCoordDataLengthObj, &cpCoordDataLengthPtr));
5233:   PetscCall(PetscContainerGetPointer(wHashTableObj, &wHashTableTemp));
5234:   PetscCall(PetscContainerGetPointer(wDataLengthObj, &wDataLengthPtr));
5235:   PetscCall(PetscContainerGetPointer(maxNumRelateObj, &maxNumEquivPtr));

5237:   *cpCoordDataLength = *cpCoordDataLengthPtr;
5238:   *wDataLength       = *wDataLengthPtr;
5239:   *maxNumEquiv       = *maxNumEquivPtr;
5240:   *cpHashTable       = cpHashTableTemp;
5241:   *wHashTable        = wHashTableTemp;
5242:   PetscCall(VecGetArrayWrite(cntrlPtCoordsVec, cpCoordData));
5243:   PetscCall(VecGetArrayWrite(cntrlPtWeightsVec, wData));
5244:   PetscFunctionReturn(PETSC_SUCCESS);
5245: }

5247: /*@
5248:   DMPlexRestoreGeomCntrlPntAndWeightData - Release the arrays returned by `DMPlexGetGeomCntrlPntAndWeightData()`

5250:   Not Collective

5252:   Input Parameters:
5253: + dm                - The `DMPLEX` with an attached CAD geometry
5254: . cpHashTable       - Control-point hash table (unused, retained for API symmetry)
5255: . cpCoordDataLength - Length of `cpCoordData` (unused, retained for API symmetry)
5256: . cpCoordData       - Control-point coordinate array to release
5257: . maxNumEquiv       - Maximum number of equivalent control points (unused, retained for API symmetry)
5258: . cpEquiv           - Control-point equivalency matrix (unused, retained for API symmetry)
5259: . wHashTable        - Weight hash table (unused, retained for API symmetry)
5260: . wDataLength       - Length of `wData` (unused, retained for API symmetry)
5261: - wData             - Weight array to release

5263:   Level: intermediate

5265: .seealso: `DMPlexGetGeomCntrlPntAndWeightData()`, `DMPlexGeomDataAndGrads()`
5266: @*/
5267: PetscErrorCode DMPlexRestoreGeomCntrlPntAndWeightData(DM dm, PetscHMapI *cpHashTable, PetscInt *cpCoordDataLength, PetscScalar **cpCoordData, PetscInt *maxNumEquiv, Mat *cpEquiv, PetscHMapI *wHashTable, PetscInt *wDataLength, PetscScalar **wData)
5268: {
5269:   Vec cntrlPtCoordsVec, cntrlPtWeightsVec;

5271:   PetscFunctionBeginHot;
5272:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Coordinates", (PetscObject *)&cntrlPtCoordsVec));
5273:   PetscCall(VecRestoreArrayWrite(cntrlPtCoordsVec, cpCoordData));
5274:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data", (PetscObject *)&cntrlPtWeightsVec));
5275:   PetscCall(VecRestoreArrayWrite(cntrlPtWeightsVec, wData));
5276:   PetscFunctionReturn(PETSC_SUCCESS);
5277: }

5279: /*@
5280:   DMPlexGetGeomGradData - Gets Point, Surface and Volume Gradients with respect to changes in Control Points and their associated Weights for the Geometry attached to the DMPlex .

5282:   Not collective

5284:   Input Parameter:
5285: . dm - The `DMPLEX` object with an attached PetscContainer storing a CAD Geometry object

5287:   Output Parameters:
5288: + cpSurfGradHashTable - Hash Table Relating the Control Point ID to the the Row in the cpSurfGrad Matrix
5289: . cpSurfGrad          - Matrix containing the Surface Gradient with respect to the Control Point Data. Data is ranged where the Row corresponds to Control Point ID and the Columns are associated with the Geometric FACE.
5290: . cpArraySize         - The length of `gradSACP` and `gradVolCP` and is equal to 3 * total number of Control Points in the Geometry
5291: . gradSACP            - Array containing the Surface Area Gradient with respect to Control Point Data. Data is arranged by Control Point ID * 3 where 3 is for the coordinate dimension.
5292: . gradVolCP           - Array containing the Volume Gradient with respect to Control Point Data. Data is arranged by Control Point ID * 3 where 3 is for the coordinate dimension.
5293: . wArraySize          - The length of `gradSAW` and `gradVolW` and is equal to the total number of Control Points in the Geometry.
5294: . gradSAW             - Array containing the Surface Area Gradient with respect to Control Point Weight. Data is arranged by Control Point ID.
5295: - gradVolW            - Array containing the Volume Gradient with respect to Control Point Weight. Data is arranged by Control Point ID.

5297:   Notes:
5298:   Must Call `DMPlexGeomDataAndGrads()` before calling this function.

5300:   `gradVolCP` and `gradVolW` are only available when `DMPlexGeomDataAndGrads()` is called with `fullGeomGrad` equal to `PETSC_TRUE`.

5302:   Level: intermediate

5304: .seealso: `DMPlexGeomDataAndGrads()`
5305: @*/
5306: PetscErrorCode DMPlexGetGeomGradData(DM dm, PetscHMapI *cpSurfGradHashTable, Mat *cpSurfGrad, PetscInt *cpArraySize, PetscScalar *gradSACP[], PetscScalar *gradVolCP[], PetscInt *wArraySize, PetscScalar *gradSAW[], PetscScalar *gradVolW[])
5307: {
5308:   PetscContainer modelObj, cpSurfGradHashTableObj, cpArraySizeObj, wArraySizeObj;
5309:   Vec            gradSACPVec, gradVolCPVec, gradSAWVec, gradVolWVec;
5310:   PetscInt      *cpArraySizePtr, *wArraySizePtr;
5311:   PetscHMapI     cpSurfGradHashTableTemp;

5313:   PetscFunctionBeginHot;
5314:   /* Determine which type of EGADS model is attached to the DM */
5315:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5316:   if (!modelObj) PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));

5318:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);

5320:   // Look to see if DM has Container for Geometry Control Point Data
5321:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Gradient Hash Table", (PetscObject *)&cpSurfGradHashTableObj));
5322:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Gradient Matrix", (PetscObject *)cpSurfGrad));
5323:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Coordinate Data Length", (PetscObject *)&cpArraySizeObj));
5324:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Area Control Point Gradient", (PetscObject *)&gradSACPVec));
5325:   PetscCall(PetscObjectQuery((PetscObject)dm, "Volume Control Point Gradient", (PetscObject *)&gradVolCPVec));
5326:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data Length", (PetscObject *)&wArraySizeObj));
5327:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Area Weights Gradient", (PetscObject *)&gradSAWVec));
5328:   PetscCall(PetscObjectQuery((PetscObject)dm, "Volume Weights Gradient", (PetscObject *)&gradVolWVec));

5330:   // Get attached EGADS model Control Point and Weights Hash Tables and Data Arrays (pointer)
5331:   if (cpSurfGradHashTableObj) {
5332:     PetscCall(PetscContainerGetPointer(cpSurfGradHashTableObj, &cpSurfGradHashTableTemp));
5333:     *cpSurfGradHashTable = cpSurfGradHashTableTemp;
5334:   }

5336:   if (cpArraySizeObj) {
5337:     PetscCall(PetscContainerGetPointer(cpArraySizeObj, &cpArraySizePtr));
5338:     *cpArraySize = *cpArraySizePtr;
5339:   }

5341:   if (gradSACPVec) PetscCall(VecGetArrayWrite(gradSACPVec, gradSACP));
5342:   if (gradVolCPVec) PetscCall(VecGetArrayWrite(gradVolCPVec, gradVolCP));
5343:   if (gradSAWVec) PetscCall(VecGetArrayWrite(gradSAWVec, gradSAW));
5344:   if (gradVolWVec) PetscCall(VecGetArrayWrite(gradVolWVec, gradVolW));

5346:   if (wArraySizeObj) {
5347:     PetscCall(PetscContainerGetPointer(wArraySizeObj, &wArraySizePtr));
5348:     *wArraySize = *wArraySizePtr;
5349:   }
5350:   PetscFunctionReturn(PETSC_SUCCESS);
5351: }

5353: /*@
5354:   DMPlexRestoreGeomGradData - Release the arrays returned by `DMPlexGetGeomGradData()`

5356:   Not Collective

5358:   Input Parameters:
5359: + dm                  - The `DMPLEX` with an attached CAD geometry
5360: . cpSurfGradHashTable - Surface-gradient hash table (unused, retained for API symmetry)
5361: . cpSurfGrad          - Surface-gradient matrix (unused, retained for API symmetry)
5362: . cpArraySize         - Length of the control-point gradient arrays (unused, retained for API symmetry)
5363: . gradSACP            - Surface-area gradient with respect to control points, to release
5364: . gradVolCP           - Volume gradient with respect to control points, to release
5365: . wArraySize          - Length of the control-point-weight gradient arrays (unused, retained for API symmetry)
5366: . gradSAW             - Surface-area gradient with respect to weights, to release
5367: - gradVolW            - Volume gradient with respect to weights, to release

5369:   Level: intermediate

5371: .seealso: `DMPlexGetGeomGradData()`, `DMPlexGeomDataAndGrads()`
5372: @*/
5373: PetscErrorCode DMPlexRestoreGeomGradData(DM dm, PetscHMapI *cpSurfGradHashTable, Mat *cpSurfGrad, PetscInt *cpArraySize, PetscScalar *gradSACP[], PetscScalar *gradVolCP[], PetscInt *wArraySize, PetscScalar *gradSAW[], PetscScalar *gradVolW[])
5374: {
5375:   Vec gradSACPVec, gradVolCPVec, gradSAWVec, gradVolWVec;

5377:   PetscFunctionBegin;
5378:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Area Control Point Gradient", (PetscObject *)&gradSACPVec));
5379:   PetscCall(PetscObjectQuery((PetscObject)dm, "Volume Control Point Gradient", (PetscObject *)&gradVolCPVec));
5380:   PetscCall(PetscObjectQuery((PetscObject)dm, "Surface Area Weights Gradient", (PetscObject *)&gradSAWVec));
5381:   PetscCall(PetscObjectQuery((PetscObject)dm, "Volume Weights Gradient", (PetscObject *)&gradVolWVec));

5383:   if (gradSACPVec) PetscCall(VecRestoreArrayWrite(gradSACPVec, gradSACP));
5384:   if (gradVolCPVec) PetscCall(VecRestoreArrayWrite(gradVolCPVec, gradVolCP));
5385:   if (gradSAWVec) PetscCall(VecRestoreArrayWrite(gradSAWVec, gradSAW));
5386:   if (gradVolWVec) PetscCall(VecRestoreArrayWrite(gradVolWVec, gradVolW));
5387:   PetscFunctionReturn(PETSC_SUCCESS);
5388: }

5390: /*@
5391:   DMPlexGetGeomCntrlPntMaps - Gets arrays which maps Control Point IDs to their associated Geometry FACE, EDGE, and VERTEX.

5393:   Not collective

5395:   Input Parameter:
5396: . dm - The `DMPLEX` object with an attached `PetscContainer` storing a CAD Geometry object

5398:   Output Parameters:
5399: + numCntrlPnts            - Number of Control Points defining the Geometry attached to the `DMPLEX`
5400: . cntrlPntFaceMap         - Array containing the FACE ID for the Control Point. Array index corresponds to Control Point ID
5401: . cntrlPntWeightFaceMap   - Array containing the FACE ID for the Control Point Weight. Array index corresponds to Control Point ID
5402: . cntrlPntEdgeMap         - Array containing the EDGE ID for the Control Point. Array index corresponds to Control Point ID
5403: . cntrlPntWeightEdgeMap   - Array containing the EDGE ID for the Control Point Weight. Array index corresponds to Control Point ID
5404: . cntrlPntVertexMap       - Array containing the VERTEX ID for the Control Point. Array index corresponds to Control Point ID
5405: - cntrlPntWeightVertexMap - Array containing the VERTEX ID for the Control Point Weight. Array index corresponds to Control Point ID

5407:   Level: intermediate

5409:   Notes:
5410:   If no EGADS model is composed with `dm`, `numCntrlPnts` is set to zero and each of the six arrays is set to `NULL`.

5412:   The same holds for any individual output that has no composed data in the `dm`.

5414:   All the arrays have a length of `numCntrlPnts`.

5416:   Arrays are initialized to -1. Array elements with a -1 value indicates that the Control Point or Control Point Weight not associated with the referenced Geometric entity in the array name.

5418: .seealso: `DMPlexGeomDataAndGrads()`
5419: @*/
5420: PetscErrorCode DMPlexGetGeomCntrlPntMaps(DM dm, PetscInt *numCntrlPnts, PetscInt *cntrlPntFaceMap[], PetscInt *cntrlPntWeightFaceMap[], PetscInt *cntrlPntEdgeMap[], PetscInt *cntrlPntWeightEdgeMap[], PetscInt *cntrlPntVertexMap[], PetscInt *cntrlPntWeightVertexMap[])
5421: {
5422:   PetscFunctionBeginHot;
5423:   #if PetscDefined(HAVE_EGADS)
5424:   PetscContainer modelObj, numCntrlPntsObj, cntrlPntFaceMapObj, cntrlPntWeightFaceMapObj, cntrlPntEdgeMapObj, cntrlPntWeightEdgeMapObj, cntrlPntVertexMapObj, cntrlPntWeightVertexMapObj;
5425:   PetscInt      *numCntrlPntsPtr, *cntrlPntFaceMapPtr, *cntrlPntWeightFaceMapPtr, *cntrlPntEdgeMapPtr, *cntrlPntWeightEdgeMapPtr, *cntrlPntVertexMapPtr, *cntrlPntWeightVertexMapPtr;

5427:   *numCntrlPnts            = 0;
5428:   *cntrlPntFaceMap         = NULL;
5429:   *cntrlPntWeightFaceMap   = NULL;
5430:   *cntrlPntEdgeMap         = NULL;
5431:   *cntrlPntWeightEdgeMap   = NULL;
5432:   *cntrlPntVertexMap       = NULL;
5433:   *cntrlPntWeightVertexMap = NULL;

5435:   /* Determine which type of EGADS model is attached to the DM */
5436:   PetscCall(PetscObjectQuery((PetscObject)dm, "EGADS Model", (PetscObject *)&modelObj));
5437:   if (!modelObj) PetscCall(PetscObjectQuery((PetscObject)dm, "EGADSlite Model", (PetscObject *)&modelObj));
5438:   if (!modelObj) PetscFunctionReturn(PETSC_SUCCESS);

5440:   // Look to see if DM has Container for Geometry Control Point Data
5441:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight Data Length", (PetscObject *)&numCntrlPntsObj));
5442:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Face Map", (PetscObject *)&cntrlPntFaceMapObj));
5443:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Face Map", (PetscObject *)&cntrlPntWeightFaceMapObj));
5444:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Edge Map", (PetscObject *)&cntrlPntEdgeMapObj));
5445:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Edge Map", (PetscObject *)&cntrlPntWeightEdgeMapObj));
5446:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point - Vertex Map", (PetscObject *)&cntrlPntVertexMapObj));
5447:   PetscCall(PetscObjectQuery((PetscObject)dm, "Control Point Weight - Vertex Map", (PetscObject *)&cntrlPntWeightVertexMapObj));

5449:   // Get attached EGADS model Control Point and Weights Hash Tables and Data Arrays (pointer)
5450:   if (numCntrlPntsObj) {
5451:     PetscCall(PetscContainerGetPointer(numCntrlPntsObj, &numCntrlPntsPtr));
5452:     *numCntrlPnts = *numCntrlPntsPtr;
5453:   }

5455:   if (cntrlPntFaceMapObj) {
5456:     PetscCall(PetscContainerGetPointer(cntrlPntFaceMapObj, &cntrlPntFaceMapPtr));
5457:     *cntrlPntFaceMap = cntrlPntFaceMapPtr;
5458:   }

5460:   if (cntrlPntWeightFaceMapObj) {
5461:     PetscCall(PetscContainerGetPointer(cntrlPntWeightFaceMapObj, &cntrlPntWeightFaceMapPtr));
5462:     *cntrlPntWeightFaceMap = cntrlPntWeightFaceMapPtr;
5463:   }

5465:   if (cntrlPntEdgeMapObj) {
5466:     PetscCall(PetscContainerGetPointer(cntrlPntEdgeMapObj, &cntrlPntEdgeMapPtr));
5467:     *cntrlPntEdgeMap = cntrlPntEdgeMapPtr;
5468:   }

5470:   if (cntrlPntWeightEdgeMapObj) {
5471:     PetscCall(PetscContainerGetPointer(cntrlPntWeightEdgeMapObj, &cntrlPntWeightEdgeMapPtr));
5472:     *cntrlPntWeightEdgeMap = cntrlPntWeightEdgeMapPtr;
5473:   }

5475:   if (cntrlPntVertexMapObj) {
5476:     PetscCall(PetscContainerGetPointer(cntrlPntVertexMapObj, &cntrlPntVertexMapPtr));
5477:     *cntrlPntVertexMap = cntrlPntVertexMapPtr;
5478:   }

5480:   if (cntrlPntWeightVertexMapObj) {
5481:     PetscCall(PetscContainerGetPointer(cntrlPntWeightVertexMapObj, &cntrlPntWeightVertexMapPtr));
5482:     *cntrlPntWeightVertexMap = cntrlPntWeightVertexMapPtr;
5483:   }
5484:   #endif
5485:   PetscFunctionReturn(PETSC_SUCCESS);
5486: }
5487: #endif