Actual source code: shell.c


  2: /*
  3:    This provides a simple shell for Fortran (and C programmers) to
  4:   create a very simple matrix class for use with KSP without coding
  5:   much of anything.
  6: */

  8: #include <petsc/private/matimpl.h>
  9: #include <petsc/private/vecimpl.h>

 11: struct _MatShellOps {
 12:   /*  3 */ PetscErrorCode (*mult)(Mat, Vec, Vec);
 13:   /*  5 */ PetscErrorCode (*multtranspose)(Mat, Vec, Vec);
 14:   /* 17 */ PetscErrorCode (*getdiagonal)(Mat, Vec);
 15:   /* 43 */ PetscErrorCode (*copy)(Mat, Mat, MatStructure);
 16:   /* 60 */ PetscErrorCode (*destroy)(Mat);
 17: };

 19: struct _n_MatShellMatFunctionList {
 20:   PetscErrorCode (*symbolic)(Mat, Mat, Mat, void **);
 21:   PetscErrorCode (*numeric)(Mat, Mat, Mat, void *);
 22:   PetscErrorCode (*destroy)(void *);
 23:   MatProductType ptype;
 24:   char          *composedname; /* string to identify routine with double dispatch */
 25:   char          *resultname;   /* result matrix type */

 27:   struct _n_MatShellMatFunctionList *next;
 28: };
 29: typedef struct _n_MatShellMatFunctionList *MatShellMatFunctionList;

 31: typedef struct {
 32:   struct _MatShellOps ops[1];

 34:   /* The user will manage the scaling and shifts for the MATSHELL, not the default */
 35:   PetscBool managescalingshifts;

 37:   /* support for MatScale, MatShift and MatMultAdd */
 38:   PetscScalar vscale, vshift;
 39:   Vec         dshift;
 40:   Vec         left, right;
 41:   Vec         left_work, right_work;
 42:   Vec         left_add_work, right_add_work;

 44:   /* support for MatAXPY */
 45:   Mat              axpy;
 46:   PetscScalar      axpy_vscale;
 47:   Vec              axpy_left, axpy_right;
 48:   PetscObjectState axpy_state;

 50:   /* support for ZeroRows/Columns operations */
 51:   IS         zrows;
 52:   IS         zcols;
 53:   Vec        zvals;
 54:   Vec        zvals_w;
 55:   VecScatter zvals_sct_r;
 56:   VecScatter zvals_sct_c;

 58:   /* MatMat operations */
 59:   MatShellMatFunctionList matmat;

 61:   /* user defined context */
 62:   PetscContainer ctxcontainer;
 63: } Mat_Shell;

 65: /*
 66:      Store and scale values on zeroed rows
 67:      xx = [x_1, 0], 0 on zeroed columns
 68: */
 69: static PetscErrorCode MatShellPreZeroRight(Mat A, Vec x, Vec *xx)
 70: {
 71:   Mat_Shell *shell = (Mat_Shell *)A->data;

 73:   *xx = x;
 74:   if (shell->zrows) {
 75:     VecSet(shell->zvals_w, 0.0);
 76:     VecScatterBegin(shell->zvals_sct_c, x, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
 77:     VecScatterEnd(shell->zvals_sct_c, x, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
 78:     VecPointwiseMult(shell->zvals_w, shell->zvals_w, shell->zvals);
 79:   }
 80:   if (shell->zcols) {
 81:     if (!shell->right_work) MatCreateVecs(A, &shell->right_work, NULL);
 82:     VecCopy(x, shell->right_work);
 83:     VecISSet(shell->right_work, shell->zcols, 0.0);
 84:     *xx = shell->right_work;
 85:   }
 86:   return 0;
 87: }

 89: /* Insert properly diagonally scaled values stored in MatShellPreZeroRight */
 90: static PetscErrorCode MatShellPostZeroLeft(Mat A, Vec x)
 91: {
 92:   Mat_Shell *shell = (Mat_Shell *)A->data;

 94:   if (shell->zrows) {
 95:     VecScatterBegin(shell->zvals_sct_r, shell->zvals_w, x, INSERT_VALUES, SCATTER_REVERSE);
 96:     VecScatterEnd(shell->zvals_sct_r, shell->zvals_w, x, INSERT_VALUES, SCATTER_REVERSE);
 97:   }
 98:   return 0;
 99: }

101: /*
102:      Store and scale values on zeroed rows
103:      xx = [x_1, 0], 0 on zeroed rows
104: */
105: static PetscErrorCode MatShellPreZeroLeft(Mat A, Vec x, Vec *xx)
106: {
107:   Mat_Shell *shell = (Mat_Shell *)A->data;

109:   *xx = NULL;
110:   if (!shell->zrows) {
111:     *xx = x;
112:   } else {
113:     if (!shell->left_work) MatCreateVecs(A, NULL, &shell->left_work);
114:     VecCopy(x, shell->left_work);
115:     VecSet(shell->zvals_w, 0.0);
116:     VecScatterBegin(shell->zvals_sct_r, shell->zvals_w, shell->left_work, INSERT_VALUES, SCATTER_REVERSE);
117:     VecScatterEnd(shell->zvals_sct_r, shell->zvals_w, shell->left_work, INSERT_VALUES, SCATTER_REVERSE);
118:     VecScatterBegin(shell->zvals_sct_r, x, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
119:     VecScatterEnd(shell->zvals_sct_r, x, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
120:     VecPointwiseMult(shell->zvals_w, shell->zvals_w, shell->zvals);
121:     *xx = shell->left_work;
122:   }
123:   return 0;
124: }

126: /* Zero zero-columns contributions, sum contributions from properly scaled values stored in MatShellPreZeroLeft */
127: static PetscErrorCode MatShellPostZeroRight(Mat A, Vec x)
128: {
129:   Mat_Shell *shell = (Mat_Shell *)A->data;

131:   if (shell->zcols) VecISSet(x, shell->zcols, 0.0);
132:   if (shell->zrows) {
133:     VecScatterBegin(shell->zvals_sct_c, shell->zvals_w, x, ADD_VALUES, SCATTER_REVERSE);
134:     VecScatterEnd(shell->zvals_sct_c, shell->zvals_w, x, ADD_VALUES, SCATTER_REVERSE);
135:   }
136:   return 0;
137: }

139: /*
140:       xx = diag(left)*x
141: */
142: static PetscErrorCode MatShellPreScaleLeft(Mat A, Vec x, Vec *xx)
143: {
144:   Mat_Shell *shell = (Mat_Shell *)A->data;

146:   *xx = NULL;
147:   if (!shell->left) {
148:     *xx = x;
149:   } else {
150:     if (!shell->left_work) VecDuplicate(shell->left, &shell->left_work);
151:     VecPointwiseMult(shell->left_work, x, shell->left);
152:     *xx = shell->left_work;
153:   }
154:   return 0;
155: }

157: /*
158:      xx = diag(right)*x
159: */
160: static PetscErrorCode MatShellPreScaleRight(Mat A, Vec x, Vec *xx)
161: {
162:   Mat_Shell *shell = (Mat_Shell *)A->data;

164:   *xx = NULL;
165:   if (!shell->right) {
166:     *xx = x;
167:   } else {
168:     if (!shell->right_work) VecDuplicate(shell->right, &shell->right_work);
169:     VecPointwiseMult(shell->right_work, x, shell->right);
170:     *xx = shell->right_work;
171:   }
172:   return 0;
173: }

175: /*
176:     x = diag(left)*x
177: */
178: static PetscErrorCode MatShellPostScaleLeft(Mat A, Vec x)
179: {
180:   Mat_Shell *shell = (Mat_Shell *)A->data;

182:   if (shell->left) VecPointwiseMult(x, x, shell->left);
183:   return 0;
184: }

186: /*
187:     x = diag(right)*x
188: */
189: static PetscErrorCode MatShellPostScaleRight(Mat A, Vec x)
190: {
191:   Mat_Shell *shell = (Mat_Shell *)A->data;

193:   if (shell->right) VecPointwiseMult(x, x, shell->right);
194:   return 0;
195: }

197: /*
198:          Y = vscale*Y + diag(dshift)*X + vshift*X

200:          On input Y already contains A*x
201: */
202: static PetscErrorCode MatShellShiftAndScale(Mat A, Vec X, Vec Y)
203: {
204:   Mat_Shell *shell = (Mat_Shell *)A->data;

206:   if (shell->dshift) { /* get arrays because there is no VecPointwiseMultAdd() */
207:     PetscInt           i, m;
208:     const PetscScalar *x, *d;
209:     PetscScalar       *y;
210:     VecGetLocalSize(X, &m);
211:     VecGetArrayRead(shell->dshift, &d);
212:     VecGetArrayRead(X, &x);
213:     VecGetArray(Y, &y);
214:     for (i = 0; i < m; i++) y[i] = shell->vscale * y[i] + d[i] * x[i];
215:     VecRestoreArrayRead(shell->dshift, &d);
216:     VecRestoreArrayRead(X, &x);
217:     VecRestoreArray(Y, &y);
218:   } else {
219:     VecScale(Y, shell->vscale);
220:   }
221:   if (shell->vshift != 0.0) VecAXPY(Y, shell->vshift, X); /* if test is for non-square matrices */
222:   return 0;
223: }

225: static PetscErrorCode MatShellGetContext_Shell(Mat mat, void *ctx)
226: {
227:   Mat_Shell *shell = (Mat_Shell *)mat->data;

229:   if (shell->ctxcontainer) PetscContainerGetPointer(shell->ctxcontainer, (void **)ctx);
230:   else *(void **)ctx = NULL;
231:   return 0;
232: }

234: /*@
235:     MatShellGetContext - Returns the user-provided context associated with a `MATSHELL` shell matrix.

237:     Not Collective

239:     Input Parameter:
240: .   mat - the matrix, should have been created with `MatCreateShell()`

242:     Output Parameter:
243: .   ctx - the user provided context

245:     Level: advanced

247:    Fortran Note:
248:     To use this from Fortran you must write a Fortran interface definition for this
249:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

251: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellSetOperation()`, `MatShellSetContext()`
252: @*/
253: PetscErrorCode MatShellGetContext(Mat mat, void *ctx)
254: {
257:   PetscUseMethod(mat, "MatShellGetContext_C", (Mat, void *), (mat, ctx));
258:   return 0;
259: }

261: static PetscErrorCode MatZeroRowsColumns_Local_Shell(Mat mat, PetscInt nr, PetscInt rows[], PetscInt nc, PetscInt cols[], PetscScalar diag, PetscBool rc)
262: {
263:   Mat_Shell      *shell = (Mat_Shell *)mat->data;
264:   Vec             x = NULL, b = NULL;
265:   IS              is1, is2;
266:   const PetscInt *ridxs;
267:   PetscInt       *idxs, *gidxs;
268:   PetscInt        cum, rst, cst, i;

270:   if (!shell->zvals) MatCreateVecs(mat, NULL, &shell->zvals);
271:   if (!shell->zvals_w) VecDuplicate(shell->zvals, &shell->zvals_w);
272:   MatGetOwnershipRange(mat, &rst, NULL);
273:   MatGetOwnershipRangeColumn(mat, &cst, NULL);

275:   /* Expand/create index set of zeroed rows */
276:   PetscMalloc1(nr, &idxs);
277:   for (i = 0; i < nr; i++) idxs[i] = rows[i] + rst;
278:   ISCreateGeneral(PETSC_COMM_SELF, nr, idxs, PETSC_OWN_POINTER, &is1);
279:   ISSort(is1);
280:   VecISSet(shell->zvals, is1, diag);
281:   if (shell->zrows) {
282:     ISSum(shell->zrows, is1, &is2);
283:     ISDestroy(&shell->zrows);
284:     ISDestroy(&is1);
285:     shell->zrows = is2;
286:   } else shell->zrows = is1;

288:   /* Create scatters for diagonal values communications */
289:   VecScatterDestroy(&shell->zvals_sct_c);
290:   VecScatterDestroy(&shell->zvals_sct_r);

292:   /* row scatter: from/to left vector */
293:   MatCreateVecs(mat, &x, &b);
294:   VecScatterCreate(b, shell->zrows, shell->zvals_w, shell->zrows, &shell->zvals_sct_r);

296:   /* col scatter: from right vector to left vector */
297:   ISGetIndices(shell->zrows, &ridxs);
298:   ISGetLocalSize(shell->zrows, &nr);
299:   PetscMalloc1(nr, &gidxs);
300:   for (i = 0, cum = 0; i < nr; i++) {
301:     if (ridxs[i] >= mat->cmap->N) continue;
302:     gidxs[cum] = ridxs[i];
303:     cum++;
304:   }
305:   ISCreateGeneral(PetscObjectComm((PetscObject)mat), cum, gidxs, PETSC_OWN_POINTER, &is1);
306:   VecScatterCreate(x, is1, shell->zvals_w, is1, &shell->zvals_sct_c);
307:   ISDestroy(&is1);
308:   VecDestroy(&x);
309:   VecDestroy(&b);

311:   /* Expand/create index set of zeroed columns */
312:   if (rc) {
313:     PetscMalloc1(nc, &idxs);
314:     for (i = 0; i < nc; i++) idxs[i] = cols[i] + cst;
315:     ISCreateGeneral(PETSC_COMM_SELF, nc, idxs, PETSC_OWN_POINTER, &is1);
316:     ISSort(is1);
317:     if (shell->zcols) {
318:       ISSum(shell->zcols, is1, &is2);
319:       ISDestroy(&shell->zcols);
320:       ISDestroy(&is1);
321:       shell->zcols = is2;
322:     } else shell->zcols = is1;
323:   }
324:   return 0;
325: }

327: static PetscErrorCode MatZeroRows_Shell(Mat mat, PetscInt n, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
328: {
329:   Mat_Shell *shell = (Mat_Shell *)mat->data;
330:   PetscInt   nr, *lrows;

332:   if (x && b) {
333:     Vec          xt;
334:     PetscScalar *vals;
335:     PetscInt    *gcols, i, st, nl, nc;

337:     PetscMalloc1(n, &gcols);
338:     for (i = 0, nc = 0; i < n; i++)
339:       if (rows[i] < mat->cmap->N) gcols[nc++] = rows[i];

341:     MatCreateVecs(mat, &xt, NULL);
342:     VecCopy(x, xt);
343:     PetscCalloc1(nc, &vals);
344:     VecSetValues(xt, nc, gcols, vals, INSERT_VALUES); /* xt = [x1, 0] */
345:     PetscFree(vals);
346:     VecAssemblyBegin(xt);
347:     VecAssemblyEnd(xt);
348:     VecAYPX(xt, -1.0, x); /* xt = [0, x2] */

350:     VecGetOwnershipRange(xt, &st, NULL);
351:     VecGetLocalSize(xt, &nl);
352:     VecGetArray(xt, &vals);
353:     for (i = 0; i < nl; i++) {
354:       PetscInt g = i + st;
355:       if (g > mat->rmap->N) continue;
356:       if (PetscAbsScalar(vals[i]) == 0.0) continue;
357:       VecSetValue(b, g, diag * vals[i], INSERT_VALUES);
358:     }
359:     VecRestoreArray(xt, &vals);
360:     VecAssemblyBegin(b);
361:     VecAssemblyEnd(b); /* b  = [b1, x2 * diag] */
362:     VecDestroy(&xt);
363:     PetscFree(gcols);
364:   }
365:   PetscLayoutMapLocal(mat->rmap, n, rows, &nr, &lrows, NULL);
366:   MatZeroRowsColumns_Local_Shell(mat, nr, lrows, 0, NULL, diag, PETSC_FALSE);
367:   if (shell->axpy) MatZeroRows(shell->axpy, n, rows, 0.0, NULL, NULL);
368:   PetscFree(lrows);
369:   return 0;
370: }

372: static PetscErrorCode MatZeroRowsColumns_Shell(Mat mat, PetscInt n, const PetscInt rowscols[], PetscScalar diag, Vec x, Vec b)
373: {
374:   Mat_Shell *shell = (Mat_Shell *)mat->data;
375:   PetscInt  *lrows, *lcols;
376:   PetscInt   nr, nc;
377:   PetscBool  congruent;

379:   if (x && b) {
380:     Vec          xt, bt;
381:     PetscScalar *vals;
382:     PetscInt    *grows, *gcols, i, st, nl;

384:     PetscMalloc2(n, &grows, n, &gcols);
385:     for (i = 0, nr = 0; i < n; i++)
386:       if (rowscols[i] < mat->rmap->N) grows[nr++] = rowscols[i];
387:     for (i = 0, nc = 0; i < n; i++)
388:       if (rowscols[i] < mat->cmap->N) gcols[nc++] = rowscols[i];
389:     PetscCalloc1(n, &vals);

391:     MatCreateVecs(mat, &xt, &bt);
392:     VecCopy(x, xt);
393:     VecSetValues(xt, nc, gcols, vals, INSERT_VALUES); /* xt = [x1, 0] */
394:     VecAssemblyBegin(xt);
395:     VecAssemblyEnd(xt);
396:     VecAXPY(xt, -1.0, x);                             /* xt = [0, -x2] */
397:     MatMult(mat, xt, bt);                             /* bt = [-A12*x2,-A22*x2] */
398:     VecSetValues(bt, nr, grows, vals, INSERT_VALUES); /* bt = [-A12*x2,0] */
399:     VecAssemblyBegin(bt);
400:     VecAssemblyEnd(bt);
401:     VecAXPY(b, 1.0, bt);                              /* b  = [b1 - A12*x2, b2] */
402:     VecSetValues(bt, nr, grows, vals, INSERT_VALUES); /* b  = [b1 - A12*x2, 0] */
403:     VecAssemblyBegin(bt);
404:     VecAssemblyEnd(bt);
405:     PetscFree(vals);

407:     VecGetOwnershipRange(xt, &st, NULL);
408:     VecGetLocalSize(xt, &nl);
409:     VecGetArray(xt, &vals);
410:     for (i = 0; i < nl; i++) {
411:       PetscInt g = i + st;
412:       if (g > mat->rmap->N) continue;
413:       if (PetscAbsScalar(vals[i]) == 0.0) continue;
414:       VecSetValue(b, g, -diag * vals[i], INSERT_VALUES);
415:     }
416:     VecRestoreArray(xt, &vals);
417:     VecAssemblyBegin(b);
418:     VecAssemblyEnd(b); /* b  = [b1 - A12*x2, x2 * diag] */
419:     VecDestroy(&xt);
420:     VecDestroy(&bt);
421:     PetscFree2(grows, gcols);
422:   }
423:   PetscLayoutMapLocal(mat->rmap, n, rowscols, &nr, &lrows, NULL);
424:   MatHasCongruentLayouts(mat, &congruent);
425:   if (congruent) {
426:     nc    = nr;
427:     lcols = lrows;
428:   } else { /* MatZeroRowsColumns implicitly assumes the rowscols indices are for a square matrix, here we handle a more general case */
429:     PetscInt i, nt, *t;

431:     PetscMalloc1(n, &t);
432:     for (i = 0, nt = 0; i < n; i++)
433:       if (rowscols[i] < mat->cmap->N) t[nt++] = rowscols[i];
434:     PetscLayoutMapLocal(mat->cmap, nt, t, &nc, &lcols, NULL);
435:     PetscFree(t);
436:   }
437:   MatZeroRowsColumns_Local_Shell(mat, nr, lrows, nc, lcols, diag, PETSC_TRUE);
438:   if (!congruent) PetscFree(lcols);
439:   PetscFree(lrows);
440:   if (shell->axpy) MatZeroRowsColumns(shell->axpy, n, rowscols, 0.0, NULL, NULL);
441:   return 0;
442: }

444: static PetscErrorCode MatDestroy_Shell(Mat mat)
445: {
446:   Mat_Shell              *shell = (Mat_Shell *)mat->data;
447:   MatShellMatFunctionList matmat;

449:   if (shell->ops->destroy) (*shell->ops->destroy)(mat);
450:   PetscMemzero(shell->ops, sizeof(struct _MatShellOps));
451:   VecDestroy(&shell->left);
452:   VecDestroy(&shell->right);
453:   VecDestroy(&shell->dshift);
454:   VecDestroy(&shell->left_work);
455:   VecDestroy(&shell->right_work);
456:   VecDestroy(&shell->left_add_work);
457:   VecDestroy(&shell->right_add_work);
458:   VecDestroy(&shell->axpy_left);
459:   VecDestroy(&shell->axpy_right);
460:   MatDestroy(&shell->axpy);
461:   VecDestroy(&shell->zvals_w);
462:   VecDestroy(&shell->zvals);
463:   VecScatterDestroy(&shell->zvals_sct_c);
464:   VecScatterDestroy(&shell->zvals_sct_r);
465:   ISDestroy(&shell->zrows);
466:   ISDestroy(&shell->zcols);

468:   matmat = shell->matmat;
469:   while (matmat) {
470:     MatShellMatFunctionList next = matmat->next;

472:     PetscObjectComposeFunction((PetscObject)mat, matmat->composedname, NULL);
473:     PetscFree(matmat->composedname);
474:     PetscFree(matmat->resultname);
475:     PetscFree(matmat);
476:     matmat = next;
477:   }
478:   MatShellSetContext(mat, NULL);
479:   PetscObjectComposeFunction((PetscObject)mat, "MatShellGetContext_C", NULL);
480:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetContext_C", NULL);
481:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetContextDestroy_C", NULL);
482:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetVecType_C", NULL);
483:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetManageScalingShifts_C", NULL);
484:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetOperation_C", NULL);
485:   PetscObjectComposeFunction((PetscObject)mat, "MatShellGetOperation_C", NULL);
486:   PetscObjectComposeFunction((PetscObject)mat, "MatShellSetMatProductOperation_C", NULL);
487:   PetscFree(mat->data);
488:   return 0;
489: }

491: typedef struct {
492:   PetscErrorCode (*numeric)(Mat, Mat, Mat, void *);
493:   PetscErrorCode (*destroy)(void *);
494:   void *userdata;
495:   Mat   B;
496:   Mat   Bt;
497:   Mat   axpy;
498: } MatMatDataShell;

500: static PetscErrorCode DestroyMatMatDataShell(void *data)
501: {
502:   MatMatDataShell *mmdata = (MatMatDataShell *)data;

504:   if (mmdata->destroy) (*mmdata->destroy)(mmdata->userdata);
505:   MatDestroy(&mmdata->B);
506:   MatDestroy(&mmdata->Bt);
507:   MatDestroy(&mmdata->axpy);
508:   PetscFree(mmdata);
509:   return 0;
510: }

512: static PetscErrorCode MatProductNumeric_Shell_X(Mat D)
513: {
514:   Mat_Product     *product;
515:   Mat              A, B;
516:   MatMatDataShell *mdata;
517:   PetscScalar      zero = 0.0;

519:   MatCheckProduct(D, 1);
520:   product = D->product;
522:   A     = product->A;
523:   B     = product->B;
524:   mdata = (MatMatDataShell *)product->data;
525:   if (mdata->numeric) {
526:     Mat_Shell *shell                = (Mat_Shell *)A->data;
527:     PetscErrorCode (*stashsym)(Mat) = D->ops->productsymbolic;
528:     PetscErrorCode (*stashnum)(Mat) = D->ops->productnumeric;
529:     PetscBool useBmdata = PETSC_FALSE, newB = PETSC_TRUE;

531:     if (shell->managescalingshifts) {
533:       if (shell->right || shell->left) {
534:         useBmdata = PETSC_TRUE;
535:         if (!mdata->B) {
536:           MatDuplicate(B, MAT_SHARE_NONZERO_PATTERN, &mdata->B);
537:         } else {
538:           newB = PETSC_FALSE;
539:         }
540:         MatCopy(B, mdata->B, SAME_NONZERO_PATTERN);
541:       }
542:       switch (product->type) {
543:       case MATPRODUCT_AB: /* s L A R B + v L R B + L D R B */
544:         if (shell->right) MatDiagonalScale(mdata->B, shell->right, NULL);
545:         break;
546:       case MATPRODUCT_AtB: /* s R A^t L B + v R L B + R D L B */
547:         if (shell->left) MatDiagonalScale(mdata->B, shell->left, NULL);
548:         break;
549:       case MATPRODUCT_ABt: /* s L A R B^t + v L R B^t + L D R B^t */
550:         if (shell->right) MatDiagonalScale(mdata->B, NULL, shell->right);
551:         break;
552:       case MATPRODUCT_RARt: /* s B L A R B^t + v B L R B^t + B L D R B^t */
553:         if (shell->right && shell->left) {
554:           PetscBool flg;

556:           VecEqual(shell->right, shell->left, &flg);
558:                      ((PetscObject)B)->type_name);
559:         }
560:         if (shell->right) MatDiagonalScale(mdata->B, NULL, shell->right);
561:         break;
562:       case MATPRODUCT_PtAP: /* s B^t L A R B + v B^t L R B + B^t L D R B */
563:         if (shell->right && shell->left) {
564:           PetscBool flg;

566:           VecEqual(shell->right, shell->left, &flg);
568:                      ((PetscObject)B)->type_name);
569:         }
570:         if (shell->right) MatDiagonalScale(mdata->B, shell->right, NULL);
571:         break;
572:       default:
573:         SETERRQ(PetscObjectComm((PetscObject)D), PETSC_ERR_SUP, "MatProductSymbolic type %s not supported for %s and %s matrices", MatProductTypes[product->type], ((PetscObject)A)->type_name, ((PetscObject)B)->type_name);
574:       }
575:     }
576:     /* allow the user to call MatMat operations on D */
577:     D->product              = NULL;
578:     D->ops->productsymbolic = NULL;
579:     D->ops->productnumeric  = NULL;

581:     (*mdata->numeric)(A, useBmdata ? mdata->B : B, D, mdata->userdata);

583:     /* clear any leftover user data and restore D pointers */
584:     MatProductClear(D);
585:     D->ops->productsymbolic = stashsym;
586:     D->ops->productnumeric  = stashnum;
587:     D->product              = product;

589:     if (shell->managescalingshifts) {
590:       MatScale(D, shell->vscale);
591:       switch (product->type) {
592:       case MATPRODUCT_AB:  /* s L A R B + v L R B + L D R B */
593:       case MATPRODUCT_ABt: /* s L A R B^t + v L R B^t + L D R B^t */
594:         if (shell->left) {
595:           MatDiagonalScale(D, shell->left, NULL);
596:           if (shell->dshift || shell->vshift != zero) {
597:             if (!shell->left_work) MatCreateVecs(A, NULL, &shell->left_work);
598:             if (shell->dshift) {
599:               VecCopy(shell->dshift, shell->left_work);
600:               VecShift(shell->left_work, shell->vshift);
601:               VecPointwiseMult(shell->left_work, shell->left_work, shell->left);
602:             } else {
603:               VecSet(shell->left_work, shell->vshift);
604:             }
605:             if (product->type == MATPRODUCT_ABt) {
606:               MatReuse     reuse = mdata->Bt ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX;
607:               MatStructure str   = mdata->Bt ? SUBSET_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN;

609:               MatTranspose(mdata->B, reuse, &mdata->Bt);
610:               MatDiagonalScale(mdata->Bt, shell->left_work, NULL);
611:               MatAXPY(D, 1.0, mdata->Bt, str);
612:             } else {
613:               MatStructure str = newB ? DIFFERENT_NONZERO_PATTERN : SUBSET_NONZERO_PATTERN;

615:               MatDiagonalScale(mdata->B, shell->left_work, NULL);
616:               MatAXPY(D, 1.0, mdata->B, str);
617:             }
618:           }
619:         }
620:         break;
621:       case MATPRODUCT_AtB: /* s R A^t L B + v R L B + R D L B */
622:         if (shell->right) {
623:           MatDiagonalScale(D, shell->right, NULL);
624:           if (shell->dshift || shell->vshift != zero) {
625:             MatStructure str = newB ? DIFFERENT_NONZERO_PATTERN : SUBSET_NONZERO_PATTERN;

627:             if (!shell->right_work) MatCreateVecs(A, &shell->right_work, NULL);
628:             if (shell->dshift) {
629:               VecCopy(shell->dshift, shell->right_work);
630:               VecShift(shell->right_work, shell->vshift);
631:               VecPointwiseMult(shell->right_work, shell->right_work, shell->right);
632:             } else {
633:               VecSet(shell->right_work, shell->vshift);
634:             }
635:             MatDiagonalScale(mdata->B, shell->right_work, NULL);
636:             MatAXPY(D, 1.0, mdata->B, str);
637:           }
638:         }
639:         break;
640:       case MATPRODUCT_PtAP: /* s B^t L A R B + v B^t L R B + B^t L D R B */
641:       case MATPRODUCT_RARt: /* s B L A R B^t + v B L R B^t + B L D R B^t */
643:                    ((PetscObject)B)->type_name);
644:         break;
645:       default:
646:         SETERRQ(PetscObjectComm((PetscObject)D), PETSC_ERR_SUP, "MatProductSymbolic type %s not supported for %s and %s matrices", MatProductTypes[product->type], ((PetscObject)A)->type_name, ((PetscObject)B)->type_name);
647:       }
648:       if (shell->axpy && shell->axpy_vscale != zero) {
649:         Mat              X;
650:         PetscObjectState axpy_state;
651:         MatStructure     str = DIFFERENT_NONZERO_PATTERN; /* not sure it is safe to ever use SUBSET_NONZERO_PATTERN */

653:         MatShellGetContext(shell->axpy, &X);
654:         PetscObjectStateGet((PetscObject)X, &axpy_state);
656:         if (!mdata->axpy) {
657:           str = DIFFERENT_NONZERO_PATTERN;
658:           MatProductCreate(shell->axpy, B, NULL, &mdata->axpy);
659:           MatProductSetType(mdata->axpy, product->type);
660:           MatProductSetFromOptions(mdata->axpy);
661:           MatProductSymbolic(mdata->axpy);
662:         } else { /* May be that shell->axpy has changed */
663:           PetscBool flg;

665:           MatProductReplaceMats(shell->axpy, B, NULL, mdata->axpy);
666:           MatHasOperation(mdata->axpy, MATOP_PRODUCTSYMBOLIC, &flg);
667:           if (!flg) {
668:             str = DIFFERENT_NONZERO_PATTERN;
669:             MatProductSetFromOptions(mdata->axpy);
670:             MatProductSymbolic(mdata->axpy);
671:           }
672:         }
673:         MatProductNumeric(mdata->axpy);
674:         MatAXPY(D, shell->axpy_vscale, mdata->axpy, str);
675:       }
676:     }
677:   } else SETERRQ(PetscObjectComm((PetscObject)D), PETSC_ERR_PLIB, "Missing numeric operation");
678:   return 0;
679: }

681: static PetscErrorCode MatProductSymbolic_Shell_X(Mat D)
682: {
683:   Mat_Product            *product;
684:   Mat                     A, B;
685:   MatShellMatFunctionList matmat;
686:   Mat_Shell              *shell;
687:   PetscBool               flg;
688:   char                    composedname[256];
689:   MatMatDataShell        *mdata;

691:   MatCheckProduct(D, 1);
692:   product = D->product;
694:   A      = product->A;
695:   B      = product->B;
696:   shell  = (Mat_Shell *)A->data;
697:   matmat = shell->matmat;
698:   PetscSNPrintf(composedname, sizeof(composedname), "MatProductSetFromOptions_%s_%s_C", ((PetscObject)A)->type_name, ((PetscObject)B)->type_name);
699:   while (matmat) {
700:     PetscStrcmp(composedname, matmat->composedname, &flg);
701:     flg = (PetscBool)(flg && (matmat->ptype == product->type));
702:     if (flg) break;
703:     matmat = matmat->next;
704:   }
706:   switch (product->type) {
707:   case MATPRODUCT_AB:
708:     MatSetSizes(D, A->rmap->n, B->cmap->n, A->rmap->N, B->cmap->N);
709:     break;
710:   case MATPRODUCT_AtB:
711:     MatSetSizes(D, A->cmap->n, B->cmap->n, A->cmap->N, B->cmap->N);
712:     break;
713:   case MATPRODUCT_ABt:
714:     MatSetSizes(D, A->rmap->n, B->rmap->n, A->rmap->N, B->rmap->N);
715:     break;
716:   case MATPRODUCT_RARt:
717:     MatSetSizes(D, B->rmap->n, B->rmap->n, B->rmap->N, B->rmap->N);
718:     break;
719:   case MATPRODUCT_PtAP:
720:     MatSetSizes(D, B->cmap->n, B->cmap->n, B->cmap->N, B->cmap->N);
721:     break;
722:   default:
723:     SETERRQ(PetscObjectComm((PetscObject)D), PETSC_ERR_SUP, "MatProductSymbolic type %s not supported for %s and %s matrices", MatProductTypes[product->type], ((PetscObject)A)->type_name, ((PetscObject)B)->type_name);
724:   }
725:   /* respect users who passed in a matrix for which resultname is the base type */
726:   if (matmat->resultname) {
727:     PetscObjectBaseTypeCompare((PetscObject)D, matmat->resultname, &flg);
728:     if (!flg) MatSetType(D, matmat->resultname);
729:   }
730:   /* If matrix type was not set or different, we need to reset this pointers */
731:   D->ops->productsymbolic = MatProductSymbolic_Shell_X;
732:   D->ops->productnumeric  = MatProductNumeric_Shell_X;
733:   /* attach product data */
734:   PetscNew(&mdata);
735:   mdata->numeric = matmat->numeric;
736:   mdata->destroy = matmat->destroy;
737:   if (matmat->symbolic) {
738:     (*matmat->symbolic)(A, B, D, &mdata->userdata);
739:   } else { /* call general setup if symbolic operation not provided */
740:     MatSetUp(D);
741:   }
744:   D->product->data    = mdata;
745:   D->product->destroy = DestroyMatMatDataShell;
746:   /* Be sure to reset these pointers if the user did something unexpected */
747:   D->ops->productsymbolic = MatProductSymbolic_Shell_X;
748:   D->ops->productnumeric  = MatProductNumeric_Shell_X;
749:   return 0;
750: }

752: static PetscErrorCode MatProductSetFromOptions_Shell_X(Mat D)
753: {
754:   Mat_Product            *product;
755:   Mat                     A, B;
756:   MatShellMatFunctionList matmat;
757:   Mat_Shell              *shell;
758:   PetscBool               flg;
759:   char                    composedname[256];

761:   MatCheckProduct(D, 1);
762:   product = D->product;
763:   A       = product->A;
764:   B       = product->B;
765:   MatIsShell(A, &flg);
766:   if (!flg) return 0;
767:   shell  = (Mat_Shell *)A->data;
768:   matmat = shell->matmat;
769:   PetscSNPrintf(composedname, sizeof(composedname), "MatProductSetFromOptions_%s_%s_C", ((PetscObject)A)->type_name, ((PetscObject)B)->type_name);
770:   while (matmat) {
771:     PetscStrcmp(composedname, matmat->composedname, &flg);
772:     flg = (PetscBool)(flg && (matmat->ptype == product->type));
773:     if (flg) break;
774:     matmat = matmat->next;
775:   }
776:   if (flg) {
777:     D->ops->productsymbolic = MatProductSymbolic_Shell_X;
778:   } else PetscInfo(D, "  symbolic product %s not registered for product type %s\n", composedname, MatProductTypes[product->type]);
779:   return 0;
780: }

782: static PetscErrorCode MatShellSetMatProductOperation_Private(Mat A, MatProductType ptype, PetscErrorCode (*symbolic)(Mat, Mat, Mat, void **), PetscErrorCode (*numeric)(Mat, Mat, Mat, void *), PetscErrorCode (*destroy)(void *), char *composedname, const char *resultname)
783: {
784:   PetscBool               flg;
785:   Mat_Shell              *shell;
786:   MatShellMatFunctionList matmat;


791:   /* add product callback */
792:   shell  = (Mat_Shell *)A->data;
793:   matmat = shell->matmat;
794:   if (!matmat) {
795:     PetscNew(&shell->matmat);
796:     matmat = shell->matmat;
797:   } else {
798:     MatShellMatFunctionList entry = matmat;
799:     while (entry) {
800:       PetscStrcmp(composedname, entry->composedname, &flg);
801:       flg    = (PetscBool)(flg && (entry->ptype == ptype));
802:       matmat = entry;
803:       if (flg) goto set;
804:       entry = entry->next;
805:     }
806:     PetscNew(&matmat->next);
807:     matmat = matmat->next;
808:   }

810: set:
811:   matmat->symbolic = symbolic;
812:   matmat->numeric  = numeric;
813:   matmat->destroy  = destroy;
814:   matmat->ptype    = ptype;
815:   PetscFree(matmat->composedname);
816:   PetscFree(matmat->resultname);
817:   PetscStrallocpy(composedname, &matmat->composedname);
818:   PetscStrallocpy(resultname, &matmat->resultname);
819:   PetscInfo(A, "Composing %s for product type %s with result %s\n", matmat->composedname, MatProductTypes[matmat->ptype], matmat->resultname ? matmat->resultname : "not specified");
820:   PetscObjectComposeFunction((PetscObject)A, matmat->composedname, MatProductSetFromOptions_Shell_X);
821:   return 0;
822: }

824: /*@C
825:     MatShellSetMatProductOperation - Allows user to set a matrix matrix operation for a `MATSHELL` shell matrix.

827:    Logically Collective on A; No Fortran Support

829:     Input Parameters:
830: +   A - the `MATSHELL` shell matrix
831: .   ptype - the product type
832: .   symbolic - the function for the symbolic phase (can be NULL)
833: .   numeric - the function for the numerical phase
834: .   destroy - the function for the destruction of the needed data generated during the symbolic phase (can be NULL)
835: .   Btype - the matrix type for the matrix to be multiplied against
836: -   Ctype - the matrix type for the result (can be NULL)

838:    Level: advanced

840:     Usage:
841: .vb
842:       extern PetscErrorCode usersymbolic(Mat,Mat,Mat,void**);
843:       extern PetscErrorCode usernumeric(Mat,Mat,Mat,void*);
844:       extern PetscErrorCode userdestroy(void*);
845:       MatCreateShell(comm,m,n,M,N,ctx,&A);
846:       MatShellSetMatProductOperation(A,MATPRODUCT_AB,usersymbolic,usernumeric,userdestroy,MATSEQAIJ,MATDENSE);
847:       [ create B of type SEQAIJ etc..]
848:       MatProductCreate(A,B,NULL,&C);
849:       MatProductSetType(C,MATPRODUCT_AB);
850:       MatProductSetFromOptions(C);
851:       MatProductSymbolic(C); -> actually runs the user defined symbolic operation
852:       MatProductNumeric(C); -> actually runs the user defined numeric operation
853:       [ use C = A*B ]
854: .ve

856:     Notes:
857:     `MATPRODUCT_ABC` is not supported yet.

859:     If the symbolic phase is not specified, `MatSetUp()` is called on the result matrix that must have its type set if Ctype is NULL.

861:     Any additional data needed by the matrix product needs to be returned during the symbolic phase and destroyed with the destroy callback.
862:     PETSc will take care of calling the user-defined callbacks.
863:     It is allowed to specify the same callbacks for different Btype matrix types.
864:     The couple (Btype,ptype) uniquely identifies the operation: the last specified callbacks takes precedence.

866: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellSetContext()`, `MatSetOperation()`, `MatProductType`, `MatType`, `MatSetUp()`
867: @*/
868: PetscErrorCode MatShellSetMatProductOperation(Mat A, MatProductType ptype, PetscErrorCode (*symbolic)(Mat, Mat, Mat, void **), PetscErrorCode (*numeric)(Mat, Mat, Mat, void *), PetscErrorCode (*destroy)(void *), MatType Btype, MatType Ctype)
869: {
876:   PetscTryMethod(A, "MatShellSetMatProductOperation_C", (Mat, MatProductType, PetscErrorCode(*)(Mat, Mat, Mat, void **), PetscErrorCode(*)(Mat, Mat, Mat, void *), PetscErrorCode(*)(void *), MatType, MatType), (A, ptype, symbolic, numeric, destroy, Btype, Ctype));
877:   return 0;
878: }

880: static PetscErrorCode MatShellSetMatProductOperation_Shell(Mat A, MatProductType ptype, PetscErrorCode (*symbolic)(Mat, Mat, Mat, void **), PetscErrorCode (*numeric)(Mat, Mat, Mat, void *), PetscErrorCode (*destroy)(void *), MatType Btype, MatType Ctype)
881: {
882:   PetscBool   flg;
883:   char        composedname[256];
884:   MatRootName Bnames = MatRootNameList, Cnames = MatRootNameList;
885:   PetscMPIInt size;

888:   while (Bnames) { /* user passed in the root name */
889:     PetscStrcmp(Btype, Bnames->rname, &flg);
890:     if (flg) break;
891:     Bnames = Bnames->next;
892:   }
893:   while (Cnames) { /* user passed in the root name */
894:     PetscStrcmp(Ctype, Cnames->rname, &flg);
895:     if (flg) break;
896:     Cnames = Cnames->next;
897:   }
898:   MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
899:   Btype = Bnames ? (size > 1 ? Bnames->mname : Bnames->sname) : Btype;
900:   Ctype = Cnames ? (size > 1 ? Cnames->mname : Cnames->sname) : Ctype;
901:   PetscSNPrintf(composedname, sizeof(composedname), "MatProductSetFromOptions_%s_%s_C", ((PetscObject)A)->type_name, Btype);
902:   MatShellSetMatProductOperation_Private(A, ptype, symbolic, numeric, destroy, composedname, Ctype);
903:   return 0;
904: }

906: static PetscErrorCode MatCopy_Shell(Mat A, Mat B, MatStructure str)
907: {
908:   Mat_Shell              *shellA = (Mat_Shell *)A->data, *shellB = (Mat_Shell *)B->data;
909:   PetscBool               matflg;
910:   MatShellMatFunctionList matmatA;

912:   MatIsShell(B, &matflg);

915:   PetscMemcpy(B->ops, A->ops, sizeof(struct _MatOps));
916:   PetscMemcpy(shellB->ops, shellA->ops, sizeof(struct _MatShellOps));

918:   if (shellA->ops->copy) (*shellA->ops->copy)(A, B, str);
919:   shellB->vscale = shellA->vscale;
920:   shellB->vshift = shellA->vshift;
921:   if (shellA->dshift) {
922:     if (!shellB->dshift) VecDuplicate(shellA->dshift, &shellB->dshift);
923:     VecCopy(shellA->dshift, shellB->dshift);
924:   } else {
925:     VecDestroy(&shellB->dshift);
926:   }
927:   if (shellA->left) {
928:     if (!shellB->left) VecDuplicate(shellA->left, &shellB->left);
929:     VecCopy(shellA->left, shellB->left);
930:   } else {
931:     VecDestroy(&shellB->left);
932:   }
933:   if (shellA->right) {
934:     if (!shellB->right) VecDuplicate(shellA->right, &shellB->right);
935:     VecCopy(shellA->right, shellB->right);
936:   } else {
937:     VecDestroy(&shellB->right);
938:   }
939:   MatDestroy(&shellB->axpy);
940:   shellB->axpy_vscale = 0.0;
941:   shellB->axpy_state  = 0;
942:   if (shellA->axpy) {
943:     PetscObjectReference((PetscObject)shellA->axpy);
944:     shellB->axpy        = shellA->axpy;
945:     shellB->axpy_vscale = shellA->axpy_vscale;
946:     shellB->axpy_state  = shellA->axpy_state;
947:   }
948:   if (shellA->zrows) {
949:     ISDuplicate(shellA->zrows, &shellB->zrows);
950:     if (shellA->zcols) ISDuplicate(shellA->zcols, &shellB->zcols);
951:     VecDuplicate(shellA->zvals, &shellB->zvals);
952:     VecCopy(shellA->zvals, shellB->zvals);
953:     VecDuplicate(shellA->zvals_w, &shellB->zvals_w);
954:     PetscObjectReference((PetscObject)shellA->zvals_sct_r);
955:     PetscObjectReference((PetscObject)shellA->zvals_sct_c);
956:     shellB->zvals_sct_r = shellA->zvals_sct_r;
957:     shellB->zvals_sct_c = shellA->zvals_sct_c;
958:   }

960:   matmatA = shellA->matmat;
961:   if (matmatA) {
962:     while (matmatA->next) {
963:       MatShellSetMatProductOperation_Private(B, matmatA->ptype, matmatA->symbolic, matmatA->numeric, matmatA->destroy, matmatA->composedname, matmatA->resultname);
964:       matmatA = matmatA->next;
965:     }
966:   }
967:   return 0;
968: }

970: static PetscErrorCode MatDuplicate_Shell(Mat mat, MatDuplicateOption op, Mat *M)
971: {
972:   MatCreateShell(PetscObjectComm((PetscObject)mat), mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N, NULL, M);
973:   ((Mat_Shell *)(*M)->data)->ctxcontainer = ((Mat_Shell *)mat->data)->ctxcontainer;
974:   PetscObjectCompose((PetscObject)(*M), "MatShell ctx", (PetscObject)((Mat_Shell *)(*M)->data)->ctxcontainer);
975:   PetscObjectChangeTypeName((PetscObject)(*M), ((PetscObject)mat)->type_name);
976:   if (op != MAT_DO_NOT_COPY_VALUES) MatCopy(mat, *M, SAME_NONZERO_PATTERN);
977:   return 0;
978: }

980: PetscErrorCode MatMult_Shell(Mat A, Vec x, Vec y)
981: {
982:   Mat_Shell       *shell = (Mat_Shell *)A->data;
983:   Vec              xx;
984:   PetscObjectState instate, outstate;

986:   MatShellPreZeroRight(A, x, &xx);
987:   MatShellPreScaleRight(A, xx, &xx);
988:   PetscObjectStateGet((PetscObject)y, &instate);
989:   (*shell->ops->mult)(A, xx, y);
990:   PetscObjectStateGet((PetscObject)y, &outstate);
991:   if (instate == outstate) {
992:     /* increase the state of the output vector since the user did not update its state themself as should have been done */
993:     PetscObjectStateIncrease((PetscObject)y);
994:   }
995:   MatShellShiftAndScale(A, xx, y);
996:   MatShellPostScaleLeft(A, y);
997:   MatShellPostZeroLeft(A, y);

999:   if (shell->axpy) {
1000:     Mat              X;
1001:     PetscObjectState axpy_state;

1003:     MatShellGetContext(shell->axpy, &X);
1004:     PetscObjectStateGet((PetscObject)X, &axpy_state);

1007:     MatCreateVecs(shell->axpy, shell->axpy_right ? NULL : &shell->axpy_right, shell->axpy_left ? NULL : &shell->axpy_left);
1008:     VecCopy(x, shell->axpy_right);
1009:     MatMult(shell->axpy, shell->axpy_right, shell->axpy_left);
1010:     VecAXPY(y, shell->axpy_vscale, shell->axpy_left);
1011:   }
1012:   return 0;
1013: }

1015: static PetscErrorCode MatMultAdd_Shell(Mat A, Vec x, Vec y, Vec z)
1016: {
1017:   Mat_Shell *shell = (Mat_Shell *)A->data;

1019:   if (y == z) {
1020:     if (!shell->right_add_work) VecDuplicate(z, &shell->right_add_work);
1021:     MatMult(A, x, shell->right_add_work);
1022:     VecAXPY(z, 1.0, shell->right_add_work);
1023:   } else {
1024:     MatMult(A, x, z);
1025:     VecAXPY(z, 1.0, y);
1026:   }
1027:   return 0;
1028: }

1030: static PetscErrorCode MatMultTranspose_Shell(Mat A, Vec x, Vec y)
1031: {
1032:   Mat_Shell       *shell = (Mat_Shell *)A->data;
1033:   Vec              xx;
1034:   PetscObjectState instate, outstate;

1036:   MatShellPreZeroLeft(A, x, &xx);
1037:   MatShellPreScaleLeft(A, xx, &xx);
1038:   PetscObjectStateGet((PetscObject)y, &instate);
1039:   (*shell->ops->multtranspose)(A, xx, y);
1040:   PetscObjectStateGet((PetscObject)y, &outstate);
1041:   if (instate == outstate) {
1042:     /* increase the state of the output vector since the user did not update its state themself as should have been done */
1043:     PetscObjectStateIncrease((PetscObject)y);
1044:   }
1045:   MatShellShiftAndScale(A, xx, y);
1046:   MatShellPostScaleRight(A, y);
1047:   MatShellPostZeroRight(A, y);

1049:   if (shell->axpy) {
1050:     Mat              X;
1051:     PetscObjectState axpy_state;

1053:     MatShellGetContext(shell->axpy, &X);
1054:     PetscObjectStateGet((PetscObject)X, &axpy_state);
1056:     MatCreateVecs(shell->axpy, shell->axpy_right ? NULL : &shell->axpy_right, shell->axpy_left ? NULL : &shell->axpy_left);
1057:     VecCopy(x, shell->axpy_left);
1058:     MatMultTranspose(shell->axpy, shell->axpy_left, shell->axpy_right);
1059:     VecAXPY(y, shell->axpy_vscale, shell->axpy_right);
1060:   }
1061:   return 0;
1062: }

1064: static PetscErrorCode MatMultTransposeAdd_Shell(Mat A, Vec x, Vec y, Vec z)
1065: {
1066:   Mat_Shell *shell = (Mat_Shell *)A->data;

1068:   if (y == z) {
1069:     if (!shell->left_add_work) VecDuplicate(z, &shell->left_add_work);
1070:     MatMultTranspose(A, x, shell->left_add_work);
1071:     VecAXPY(z, 1.0, shell->left_add_work);
1072:   } else {
1073:     MatMultTranspose(A, x, z);
1074:     VecAXPY(z, 1.0, y);
1075:   }
1076:   return 0;
1077: }

1079: /*
1080:           diag(left)(vscale*A + diag(dshift) + vshift I)diag(right)
1081: */
1082: static PetscErrorCode MatGetDiagonal_Shell(Mat A, Vec v)
1083: {
1084:   Mat_Shell *shell = (Mat_Shell *)A->data;

1086:   if (shell->ops->getdiagonal) {
1087:     (*shell->ops->getdiagonal)(A, v);
1088:   } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Must provide shell matrix with routine to return diagonal using\nMatShellSetOperation(S,MATOP_GET_DIAGONAL,...)");
1089:   VecScale(v, shell->vscale);
1090:   if (shell->dshift) VecAXPY(v, 1.0, shell->dshift);
1091:   VecShift(v, shell->vshift);
1092:   if (shell->left) VecPointwiseMult(v, v, shell->left);
1093:   if (shell->right) VecPointwiseMult(v, v, shell->right);
1094:   if (shell->zrows) {
1095:     VecScatterBegin(shell->zvals_sct_r, shell->zvals, v, INSERT_VALUES, SCATTER_REVERSE);
1096:     VecScatterEnd(shell->zvals_sct_r, shell->zvals, v, INSERT_VALUES, SCATTER_REVERSE);
1097:   }
1098:   if (shell->axpy) {
1099:     Mat              X;
1100:     PetscObjectState axpy_state;

1102:     MatShellGetContext(shell->axpy, &X);
1103:     PetscObjectStateGet((PetscObject)X, &axpy_state);
1105:     MatCreateVecs(shell->axpy, NULL, shell->axpy_left ? NULL : &shell->axpy_left);
1106:     MatGetDiagonal(shell->axpy, shell->axpy_left);
1107:     VecAXPY(v, shell->axpy_vscale, shell->axpy_left);
1108:   }
1109:   return 0;
1110: }

1112: static PetscErrorCode MatShift_Shell(Mat Y, PetscScalar a)
1113: {
1114:   Mat_Shell *shell = (Mat_Shell *)Y->data;
1115:   PetscBool  flg;

1117:   MatHasCongruentLayouts(Y, &flg);
1119:   if (shell->left || shell->right) {
1120:     if (!shell->dshift) {
1121:       VecDuplicate(shell->left ? shell->left : shell->right, &shell->dshift);
1122:       VecSet(shell->dshift, a);
1123:     } else {
1124:       if (shell->left) VecPointwiseMult(shell->dshift, shell->dshift, shell->left);
1125:       if (shell->right) VecPointwiseMult(shell->dshift, shell->dshift, shell->right);
1126:       VecShift(shell->dshift, a);
1127:     }
1128:     if (shell->left) VecPointwiseDivide(shell->dshift, shell->dshift, shell->left);
1129:     if (shell->right) VecPointwiseDivide(shell->dshift, shell->dshift, shell->right);
1130:   } else shell->vshift += a;
1131:   if (shell->zrows) VecShift(shell->zvals, a);
1132:   return 0;
1133: }

1135: static PetscErrorCode MatDiagonalSet_Shell_Private(Mat A, Vec D, PetscScalar s)
1136: {
1137:   Mat_Shell *shell = (Mat_Shell *)A->data;

1139:   if (!shell->dshift) VecDuplicate(D, &shell->dshift);
1140:   if (shell->left || shell->right) {
1141:     if (!shell->right_work) VecDuplicate(shell->left ? shell->left : shell->right, &shell->right_work);
1142:     if (shell->left && shell->right) {
1143:       VecPointwiseDivide(shell->right_work, D, shell->left);
1144:       VecPointwiseDivide(shell->right_work, shell->right_work, shell->right);
1145:     } else if (shell->left) {
1146:       VecPointwiseDivide(shell->right_work, D, shell->left);
1147:     } else {
1148:       VecPointwiseDivide(shell->right_work, D, shell->right);
1149:     }
1150:     VecAXPY(shell->dshift, s, shell->right_work);
1151:   } else {
1152:     VecAXPY(shell->dshift, s, D);
1153:   }
1154:   return 0;
1155: }

1157: PetscErrorCode MatDiagonalSet_Shell(Mat A, Vec D, InsertMode ins)
1158: {
1159:   Mat_Shell *shell = (Mat_Shell *)A->data;
1160:   Vec        d;
1161:   PetscBool  flg;

1163:   MatHasCongruentLayouts(A, &flg);
1165:   if (ins == INSERT_VALUES) {
1166:     VecDuplicate(D, &d);
1167:     MatGetDiagonal(A, d);
1168:     MatDiagonalSet_Shell_Private(A, d, -1.);
1169:     MatDiagonalSet_Shell_Private(A, D, 1.);
1170:     VecDestroy(&d);
1171:     if (shell->zrows) VecCopy(D, shell->zvals);
1172:   } else {
1173:     MatDiagonalSet_Shell_Private(A, D, 1.);
1174:     if (shell->zrows) VecAXPY(shell->zvals, 1.0, D);
1175:   }
1176:   return 0;
1177: }

1179: static PetscErrorCode MatScale_Shell(Mat Y, PetscScalar a)
1180: {
1181:   Mat_Shell *shell = (Mat_Shell *)Y->data;

1183:   shell->vscale *= a;
1184:   shell->vshift *= a;
1185:   if (shell->dshift) VecScale(shell->dshift, a);
1186:   shell->axpy_vscale *= a;
1187:   if (shell->zrows) VecScale(shell->zvals, a);
1188:   return 0;
1189: }

1191: static PetscErrorCode MatDiagonalScale_Shell(Mat Y, Vec left, Vec right)
1192: {
1193:   Mat_Shell *shell = (Mat_Shell *)Y->data;

1195:   if (left) {
1196:     if (!shell->left) {
1197:       VecDuplicate(left, &shell->left);
1198:       VecCopy(left, shell->left);
1199:     } else {
1200:       VecPointwiseMult(shell->left, shell->left, left);
1201:     }
1202:     if (shell->zrows) VecPointwiseMult(shell->zvals, shell->zvals, left);
1203:   }
1204:   if (right) {
1205:     if (!shell->right) {
1206:       VecDuplicate(right, &shell->right);
1207:       VecCopy(right, shell->right);
1208:     } else {
1209:       VecPointwiseMult(shell->right, shell->right, right);
1210:     }
1211:     if (shell->zrows) {
1212:       if (!shell->left_work) MatCreateVecs(Y, NULL, &shell->left_work);
1213:       VecSet(shell->zvals_w, 1.0);
1214:       VecScatterBegin(shell->zvals_sct_c, right, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
1215:       VecScatterEnd(shell->zvals_sct_c, right, shell->zvals_w, INSERT_VALUES, SCATTER_FORWARD);
1216:       VecPointwiseMult(shell->zvals, shell->zvals, shell->zvals_w);
1217:     }
1218:   }
1219:   if (shell->axpy) MatDiagonalScale(shell->axpy, left, right);
1220:   return 0;
1221: }

1223: PetscErrorCode MatAssemblyEnd_Shell(Mat Y, MatAssemblyType t)
1224: {
1225:   Mat_Shell *shell = (Mat_Shell *)Y->data;

1227:   if (t == MAT_FINAL_ASSEMBLY) {
1228:     shell->vshift      = 0.0;
1229:     shell->vscale      = 1.0;
1230:     shell->axpy_vscale = 0.0;
1231:     shell->axpy_state  = 0;
1232:     VecDestroy(&shell->dshift);
1233:     VecDestroy(&shell->left);
1234:     VecDestroy(&shell->right);
1235:     MatDestroy(&shell->axpy);
1236:     VecDestroy(&shell->axpy_left);
1237:     VecDestroy(&shell->axpy_right);
1238:     VecScatterDestroy(&shell->zvals_sct_c);
1239:     VecScatterDestroy(&shell->zvals_sct_r);
1240:     ISDestroy(&shell->zrows);
1241:     ISDestroy(&shell->zcols);
1242:   }
1243:   return 0;
1244: }

1246: static PetscErrorCode MatMissingDiagonal_Shell(Mat A, PetscBool *missing, PetscInt *d)
1247: {
1248:   *missing = PETSC_FALSE;
1249:   return 0;
1250: }

1252: PetscErrorCode MatAXPY_Shell(Mat Y, PetscScalar a, Mat X, MatStructure str)
1253: {
1254:   Mat_Shell *shell = (Mat_Shell *)Y->data;

1256:   if (X == Y) {
1257:     MatScale(Y, 1.0 + a);
1258:     return 0;
1259:   }
1260:   if (!shell->axpy) {
1261:     MatConvertFrom_Shell(X, MATSHELL, MAT_INITIAL_MATRIX, &shell->axpy);
1262:     shell->axpy_vscale = a;
1263:     PetscObjectStateGet((PetscObject)X, &shell->axpy_state);
1264:   } else {
1265:     MatAXPY(shell->axpy, a / shell->axpy_vscale, X, str);
1266:   }
1267:   return 0;
1268: }

1270: static struct _MatOps MatOps_Values = {NULL,
1271:                                        NULL,
1272:                                        NULL,
1273:                                        NULL,
1274:                                        /* 4*/ MatMultAdd_Shell,
1275:                                        NULL,
1276:                                        MatMultTransposeAdd_Shell,
1277:                                        NULL,
1278:                                        NULL,
1279:                                        NULL,
1280:                                        /*10*/ NULL,
1281:                                        NULL,
1282:                                        NULL,
1283:                                        NULL,
1284:                                        NULL,
1285:                                        /*15*/ NULL,
1286:                                        NULL,
1287:                                        NULL,
1288:                                        MatDiagonalScale_Shell,
1289:                                        NULL,
1290:                                        /*20*/ NULL,
1291:                                        MatAssemblyEnd_Shell,
1292:                                        NULL,
1293:                                        NULL,
1294:                                        /*24*/ MatZeroRows_Shell,
1295:                                        NULL,
1296:                                        NULL,
1297:                                        NULL,
1298:                                        NULL,
1299:                                        /*29*/ NULL,
1300:                                        NULL,
1301:                                        NULL,
1302:                                        NULL,
1303:                                        NULL,
1304:                                        /*34*/ MatDuplicate_Shell,
1305:                                        NULL,
1306:                                        NULL,
1307:                                        NULL,
1308:                                        NULL,
1309:                                        /*39*/ MatAXPY_Shell,
1310:                                        NULL,
1311:                                        NULL,
1312:                                        NULL,
1313:                                        MatCopy_Shell,
1314:                                        /*44*/ NULL,
1315:                                        MatScale_Shell,
1316:                                        MatShift_Shell,
1317:                                        MatDiagonalSet_Shell,
1318:                                        MatZeroRowsColumns_Shell,
1319:                                        /*49*/ NULL,
1320:                                        NULL,
1321:                                        NULL,
1322:                                        NULL,
1323:                                        NULL,
1324:                                        /*54*/ NULL,
1325:                                        NULL,
1326:                                        NULL,
1327:                                        NULL,
1328:                                        NULL,
1329:                                        /*59*/ NULL,
1330:                                        MatDestroy_Shell,
1331:                                        NULL,
1332:                                        MatConvertFrom_Shell,
1333:                                        NULL,
1334:                                        /*64*/ NULL,
1335:                                        NULL,
1336:                                        NULL,
1337:                                        NULL,
1338:                                        NULL,
1339:                                        /*69*/ NULL,
1340:                                        NULL,
1341:                                        MatConvert_Shell,
1342:                                        NULL,
1343:                                        NULL,
1344:                                        /*74*/ NULL,
1345:                                        NULL,
1346:                                        NULL,
1347:                                        NULL,
1348:                                        NULL,
1349:                                        /*79*/ NULL,
1350:                                        NULL,
1351:                                        NULL,
1352:                                        NULL,
1353:                                        NULL,
1354:                                        /*84*/ NULL,
1355:                                        NULL,
1356:                                        NULL,
1357:                                        NULL,
1358:                                        NULL,
1359:                                        /*89*/ NULL,
1360:                                        NULL,
1361:                                        NULL,
1362:                                        NULL,
1363:                                        NULL,
1364:                                        /*94*/ NULL,
1365:                                        NULL,
1366:                                        NULL,
1367:                                        NULL,
1368:                                        NULL,
1369:                                        /*99*/ NULL,
1370:                                        NULL,
1371:                                        NULL,
1372:                                        NULL,
1373:                                        NULL,
1374:                                        /*104*/ NULL,
1375:                                        NULL,
1376:                                        NULL,
1377:                                        NULL,
1378:                                        NULL,
1379:                                        /*109*/ NULL,
1380:                                        NULL,
1381:                                        NULL,
1382:                                        NULL,
1383:                                        MatMissingDiagonal_Shell,
1384:                                        /*114*/ NULL,
1385:                                        NULL,
1386:                                        NULL,
1387:                                        NULL,
1388:                                        NULL,
1389:                                        /*119*/ NULL,
1390:                                        NULL,
1391:                                        NULL,
1392:                                        NULL,
1393:                                        NULL,
1394:                                        /*124*/ NULL,
1395:                                        NULL,
1396:                                        NULL,
1397:                                        NULL,
1398:                                        NULL,
1399:                                        /*129*/ NULL,
1400:                                        NULL,
1401:                                        NULL,
1402:                                        NULL,
1403:                                        NULL,
1404:                                        /*134*/ NULL,
1405:                                        NULL,
1406:                                        NULL,
1407:                                        NULL,
1408:                                        NULL,
1409:                                        /*139*/ NULL,
1410:                                        NULL,
1411:                                        NULL,
1412:                                        NULL,
1413:                                        NULL,
1414:                                        /*144*/ NULL,
1415:                                        NULL,
1416:                                        NULL,
1417:                                        NULL,
1418:                                        NULL,
1419:                                        NULL,
1420:                                        /*150*/ NULL};

1422: static PetscErrorCode MatShellSetContext_Shell(Mat mat, void *ctx)
1423: {
1424:   Mat_Shell *shell = (Mat_Shell *)mat->data;

1426:   if (ctx) {
1427:     PetscContainer ctxcontainer;
1428:     PetscContainerCreate(PetscObjectComm((PetscObject)mat), &ctxcontainer);
1429:     PetscContainerSetPointer(ctxcontainer, ctx);
1430:     PetscObjectCompose((PetscObject)mat, "MatShell ctx", (PetscObject)ctxcontainer);
1431:     shell->ctxcontainer = ctxcontainer;
1432:     PetscContainerDestroy(&ctxcontainer);
1433:   } else {
1434:     PetscObjectCompose((PetscObject)mat, "MatShell ctx", NULL);
1435:     shell->ctxcontainer = NULL;
1436:   }

1438:   return 0;
1439: }

1441: PetscErrorCode MatShellSetContextDestroy_Shell(Mat mat, PetscErrorCode (*f)(void *))
1442: {
1443:   Mat_Shell *shell = (Mat_Shell *)mat->data;

1445:   if (shell->ctxcontainer) PetscContainerSetUserDestroy(shell->ctxcontainer, f);
1446:   return 0;
1447: }

1449: static PetscErrorCode MatShellSetVecType_Shell(Mat mat, VecType vtype)
1450: {
1451:   PetscFree(mat->defaultvectype);
1452:   PetscStrallocpy(vtype, (char **)&mat->defaultvectype);
1453:   return 0;
1454: }

1456: PetscErrorCode MatShellSetManageScalingShifts_Shell(Mat A)
1457: {
1458:   Mat_Shell *shell = (Mat_Shell *)A->data;

1460:   shell->managescalingshifts = PETSC_FALSE;
1461:   A->ops->diagonalset        = NULL;
1462:   A->ops->diagonalscale      = NULL;
1463:   A->ops->scale              = NULL;
1464:   A->ops->shift              = NULL;
1465:   A->ops->axpy               = NULL;
1466:   return 0;
1467: }

1469: static PetscErrorCode MatShellSetOperation_Shell(Mat mat, MatOperation op, void (*f)(void))
1470: {
1471:   Mat_Shell *shell = (Mat_Shell *)mat->data;

1473:   switch (op) {
1474:   case MATOP_DESTROY:
1475:     shell->ops->destroy = (PetscErrorCode(*)(Mat))f;
1476:     break;
1477:   case MATOP_VIEW:
1478:     if (!mat->ops->viewnative) mat->ops->viewnative = mat->ops->view;
1479:     mat->ops->view = (PetscErrorCode(*)(Mat, PetscViewer))f;
1480:     break;
1481:   case MATOP_COPY:
1482:     shell->ops->copy = (PetscErrorCode(*)(Mat, Mat, MatStructure))f;
1483:     break;
1484:   case MATOP_DIAGONAL_SET:
1485:   case MATOP_DIAGONAL_SCALE:
1486:   case MATOP_SHIFT:
1487:   case MATOP_SCALE:
1488:   case MATOP_AXPY:
1489:   case MATOP_ZERO_ROWS:
1490:   case MATOP_ZERO_ROWS_COLUMNS:
1492:     (((void (**)(void))mat->ops)[op]) = f;
1493:     break;
1494:   case MATOP_GET_DIAGONAL:
1495:     if (shell->managescalingshifts) {
1496:       shell->ops->getdiagonal = (PetscErrorCode(*)(Mat, Vec))f;
1497:       mat->ops->getdiagonal   = MatGetDiagonal_Shell;
1498:     } else {
1499:       shell->ops->getdiagonal = NULL;
1500:       mat->ops->getdiagonal   = (PetscErrorCode(*)(Mat, Vec))f;
1501:     }
1502:     break;
1503:   case MATOP_MULT:
1504:     if (shell->managescalingshifts) {
1505:       shell->ops->mult = (PetscErrorCode(*)(Mat, Vec, Vec))f;
1506:       mat->ops->mult   = MatMult_Shell;
1507:     } else {
1508:       shell->ops->mult = NULL;
1509:       mat->ops->mult   = (PetscErrorCode(*)(Mat, Vec, Vec))f;
1510:     }
1511:     break;
1512:   case MATOP_MULT_TRANSPOSE:
1513:     if (shell->managescalingshifts) {
1514:       shell->ops->multtranspose = (PetscErrorCode(*)(Mat, Vec, Vec))f;
1515:       mat->ops->multtranspose   = MatMultTranspose_Shell;
1516:     } else {
1517:       shell->ops->multtranspose = NULL;
1518:       mat->ops->multtranspose   = (PetscErrorCode(*)(Mat, Vec, Vec))f;
1519:     }
1520:     break;
1521:   default:
1522:     (((void (**)(void))mat->ops)[op]) = f;
1523:     break;
1524:   }
1525:   return 0;
1526: }

1528: static PetscErrorCode MatShellGetOperation_Shell(Mat mat, MatOperation op, void (**f)(void))
1529: {
1530:   Mat_Shell *shell = (Mat_Shell *)mat->data;

1532:   switch (op) {
1533:   case MATOP_DESTROY:
1534:     *f = (void (*)(void))shell->ops->destroy;
1535:     break;
1536:   case MATOP_VIEW:
1537:     *f = (void (*)(void))mat->ops->view;
1538:     break;
1539:   case MATOP_COPY:
1540:     *f = (void (*)(void))shell->ops->copy;
1541:     break;
1542:   case MATOP_DIAGONAL_SET:
1543:   case MATOP_DIAGONAL_SCALE:
1544:   case MATOP_SHIFT:
1545:   case MATOP_SCALE:
1546:   case MATOP_AXPY:
1547:   case MATOP_ZERO_ROWS:
1548:   case MATOP_ZERO_ROWS_COLUMNS:
1549:     *f = (((void (**)(void))mat->ops)[op]);
1550:     break;
1551:   case MATOP_GET_DIAGONAL:
1552:     if (shell->ops->getdiagonal) *f = (void (*)(void))shell->ops->getdiagonal;
1553:     else *f = (((void (**)(void))mat->ops)[op]);
1554:     break;
1555:   case MATOP_MULT:
1556:     if (shell->ops->mult) *f = (void (*)(void))shell->ops->mult;
1557:     else *f = (((void (**)(void))mat->ops)[op]);
1558:     break;
1559:   case MATOP_MULT_TRANSPOSE:
1560:     if (shell->ops->multtranspose) *f = (void (*)(void))shell->ops->multtranspose;
1561:     else *f = (((void (**)(void))mat->ops)[op]);
1562:     break;
1563:   default:
1564:     *f = (((void (**)(void))mat->ops)[op]);
1565:   }
1566:   return 0;
1567: }

1569: /*MC
1570:    MATSHELL - MATSHELL = "shell" - A matrix type to be used to define your own matrix type -- perhaps matrix free.

1572:   Level: advanced

1574: .seealso: `Mat`, `MatCreateShell()`
1575: M*/

1577: PETSC_EXTERN PetscErrorCode MatCreate_Shell(Mat A)
1578: {
1579:   Mat_Shell *b;

1581:   PetscMemcpy(A->ops, &MatOps_Values, sizeof(struct _MatOps));

1583:   PetscNew(&b);
1584:   A->data = (void *)b;

1586:   b->ctxcontainer        = NULL;
1587:   b->vshift              = 0.0;
1588:   b->vscale              = 1.0;
1589:   b->managescalingshifts = PETSC_TRUE;
1590:   A->assembled           = PETSC_TRUE;
1591:   A->preallocated        = PETSC_FALSE;

1593:   PetscObjectComposeFunction((PetscObject)A, "MatShellGetContext_C", MatShellGetContext_Shell);
1594:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetContext_C", MatShellSetContext_Shell);
1595:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetContextDestroy_C", MatShellSetContextDestroy_Shell);
1596:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetVecType_C", MatShellSetVecType_Shell);
1597:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetManageScalingShifts_C", MatShellSetManageScalingShifts_Shell);
1598:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetOperation_C", MatShellSetOperation_Shell);
1599:   PetscObjectComposeFunction((PetscObject)A, "MatShellGetOperation_C", MatShellGetOperation_Shell);
1600:   PetscObjectComposeFunction((PetscObject)A, "MatShellSetMatProductOperation_C", MatShellSetMatProductOperation_Shell);
1601:   PetscObjectChangeTypeName((PetscObject)A, MATSHELL);
1602:   return 0;
1603: }

1605: /*@C
1606:    MatCreateShell - Creates a new matrix of `MatType` `MATSHELL` for use with a user-defined
1607:    private data storage format.

1609:   Collective

1611:    Input Parameters:
1612: +  comm - MPI communicator
1613: .  m - number of local rows (must be given)
1614: .  n - number of local columns (must be given)
1615: .  M - number of global rows (may be PETSC_DETERMINE)
1616: .  N - number of global columns (may be PETSC_DETERMINE)
1617: -  ctx - pointer to data needed by the shell matrix routines

1619:    Output Parameter:
1620: .  A - the matrix

1622:    Level: advanced

1624:   Usage:
1625: $    extern PetscErrorCode mult(Mat,Vec,Vec);
1626: $    MatCreateShell(comm,m,n,M,N,ctx,&mat);
1627: $    MatShellSetOperation(mat,MATOP_MULT,(void(*)(void))mult);
1628: $    [ Use matrix for operations that have been set ]
1629: $    MatDestroy(mat);

1631:    Notes:
1632:    The shell matrix type is intended to provide a simple class to use
1633:    with `KSP` (such as, for use with matrix-free methods). You should not
1634:    use the shell type if you plan to define a complete matrix class.

1636:    PETSc requires that matrices and vectors being used for certain
1637:    operations are partitioned accordingly.  For example, when
1638:    creating a shell matrix, A, that supports parallel matrix-vector
1639:    products using `MatMult`(A,x,y) the user should set the number
1640:    of local matrix rows to be the number of local elements of the
1641:    corresponding result vector, y. Note that this is information is
1642:    required for use of the matrix interface routines, even though
1643:    the shell matrix may not actually be physically partitioned.
1644:    For example,

1646: $
1647: $     Vec x, y
1648: $     extern PetscErrorCode mult(Mat,Vec,Vec);
1649: $     Mat A
1650: $
1651: $     VecCreateMPI(comm,PETSC_DECIDE,M,&y);
1652: $     VecCreateMPI(comm,PETSC_DECIDE,N,&x);
1653: $     VecGetLocalSize(y,&m);
1654: $     VecGetLocalSize(x,&n);
1655: $     MatCreateShell(comm,m,n,M,N,ctx,&A);
1656: $     MatShellSetOperation(mat,MATOP_MULT,(void(*)(void))mult);
1657: $     MatMult(A,x,y);
1658: $     MatDestroy(&A);
1659: $     VecDestroy(&y);
1660: $     VecDestroy(&x);
1661: $

1663:    `MATSHELL` handles `MatShift()`, `MatDiagonalSet()`, `MatDiagonalScale()`, `MatAXPY()`, `MatScale()`, `MatZeroRows()` and `MatZeroRowsColumns()` internally, so these
1664:    operations cannot be overwritten unless `MatShellSetManageScalingShifts()` is called.

1666:     For rectangular matrices do all the scalings and shifts make sense?

1668:     Developers Notes:
1669:     Regarding shifting and scaling. The general form is

1671:           diag(left)(vscale*A + diag(dshift) + vshift I)diag(right)

1673:       The order you apply the operations is important. For example if you have a dshift then
1674:       apply a MatScale(s) you get s*vscale*A + s*diag(shift). But if you first scale and then shift
1675:       you get s*vscale*A + diag(shift)

1677:           A is the user provided function.

1679:    `KSP`/`PC` uses changes in the `Mat`'s "state" to decide if preconditioners need to be rebuilt: `PCSetUp()` only calls the setup() for
1680:    for the `PC` implementation if the `Mat` state has increased from the previous call. Thus to get changes in a `MATSHELL` to trigger
1681:    an update in the preconditioner you must call `MatAssemblyBegin()` and `MatAssemblyEnd()` or `PetscObjectStateIncrease`((`PetscObject`)mat);
1682:    each time the `MATSHELL` matrix has changed.

1684:    Matrix product operations (i.e. `MatMat()`, `MatTransposeMat()` etc) can be specified using `MatShellSetMatProductOperation()`

1686:    Calling `MatAssemblyBegin()`/`MatAssemblyEnd()` on a `MATSHELL` removes any previously supplied shift and scales that were provided
1687:    with `MatDiagonalSet()`, `MatShift()`, `MatScale()`, or `MatDiagonalScale()`.

1689:    Fortran Note:
1690:     To use this from Fortran with a ctx you must write an interface definition for this
1691:     function and for `MatShellGetContext()` that tells Fortran the Fortran derived data type you are passing
1692:     in as the ctx argument.

1694: .seealso: `MATSHELL`, `MatShellSetOperation()`, `MatHasOperation()`, `MatShellGetContext()`, `MatShellSetContext()`, `MATSHELL`, `MatShellSetManageScalingShifts()`, `MatShellSetMatProductOperation()`
1695: @*/
1696: PetscErrorCode MatCreateShell(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, void *ctx, Mat *A)
1697: {
1698:   MatCreate(comm, A);
1699:   MatSetSizes(*A, m, n, M, N);
1700:   MatSetType(*A, MATSHELL);
1701:   MatShellSetContext(*A, ctx);
1702:   MatSetUp(*A);
1703:   return 0;
1704: }

1706: /*@
1707:     MatShellSetContext - sets the context for a `MATSHELL` shell matrix

1709:    Logically Collective

1711:     Input Parameters:
1712: +   mat - the `MATSHELL` shell matrix
1713: -   ctx - the context

1715:    Level: advanced

1717:    Fortran Note:
1718:     To use this from Fortran you must write a Fortran interface definition for this
1719:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

1721: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
1722: @*/
1723: PetscErrorCode MatShellSetContext(Mat mat, void *ctx)
1724: {
1726:   PetscTryMethod(mat, "MatShellSetContext_C", (Mat, void *), (mat, ctx));
1727:   return 0;
1728: }

1730: /*@
1731:     MatShellSetContextDestroy - sets the destroy function for a `MATSHELL` shell matrix context

1733:    Logically Collective

1735:     Input Parameters:
1736: +   mat - the shell matrix
1737: -   f - the context destroy function

1739:     Note:
1740:     If the `MatShell` is never duplicated, the behavior of this function is equivalent
1741:     to `MatShellSetOperation`(`Mat`,`MATOP_DESTROY`,f). However, `MatShellSetContextDestroy()`
1742:     ensures proper reference counting for the user provided context data in the case that
1743:     the `MATSHELL` is duplicated.

1745:    Level: advanced

1747: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellSetContext()`
1748: @*/
1749: PetscErrorCode MatShellSetContextDestroy(Mat mat, PetscErrorCode (*f)(void *))
1750: {
1752:   PetscTryMethod(mat, "MatShellSetContextDestroy_C", (Mat, PetscErrorCode(*)(void *)), (mat, f));
1753:   return 0;
1754: }

1756: /*@C
1757:  MatShellSetVecType - Sets the type of `Vec` returned by `MatCreateVecs()`

1759:  Logically collective

1761:     Input Parameters:
1762: +   mat   - the `MATSHELL` shell matrix
1763: -   vtype - type to use for creating vectors

1765:  Level: advanced

1767: .seealso: `MATSHELL`, `MatCreateVecs()`
1768: @*/
1769: PetscErrorCode MatShellSetVecType(Mat mat, VecType vtype)
1770: {
1771:   PetscTryMethod(mat, "MatShellSetVecType_C", (Mat, VecType), (mat, vtype));
1772:   return 0;
1773: }

1775: /*@
1776:     MatShellSetManageScalingShifts - Allows the user to control the scaling and shift operations of the `MATSHELL`. Must be called immediately
1777:           after `MatCreateShell()`

1779:    Logically Collective on A

1781:     Input Parameter:
1782: .   mat - the `MATSHELL` shell matrix

1784:   Level: advanced

1786: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellSetContext()`, `MatShellSetOperation()`
1787: @*/
1788: PetscErrorCode MatShellSetManageScalingShifts(Mat A)
1789: {
1791:   PetscTryMethod(A, "MatShellSetManageScalingShifts_C", (Mat), (A));
1792:   return 0;
1793: }

1795: /*@C
1796:     MatShellTestMult - Compares the multiply routine provided to the `MATSHELL` with differencing on a given function.

1798:    Logically Collective; No Fortran Support

1800:     Input Parameters:
1801: +   mat - the `MATSHELL` shell matrix
1802: .   f - the function
1803: .   base - differences are computed around this vector, see `MatMFFDSetBase()`, for Jacobians this is the point at which the Jacobian is being evaluated
1804: -   ctx - an optional context for the function

1806:    Output Parameter:
1807: .   flg - `PETSC_TRUE` if the multiply is likely correct

1809:    Options Database Key:
1810: .   -mat_shell_test_mult_view - print if any differences are detected between the products and print the difference

1812:    Level: advanced

1814: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`
1815: @*/
1816: PetscErrorCode MatShellTestMult(Mat mat, PetscErrorCode (*f)(void *, Vec, Vec), Vec base, void *ctx, PetscBool *flg)
1817: {
1818:   PetscInt  m, n;
1819:   Mat       mf, Dmf, Dmat, Ddiff;
1820:   PetscReal Diffnorm, Dmfnorm;
1821:   PetscBool v = PETSC_FALSE, flag = PETSC_TRUE;

1824:   PetscOptionsHasName(NULL, ((PetscObject)mat)->prefix, "-mat_shell_test_mult_view", &v);
1825:   MatGetLocalSize(mat, &m, &n);
1826:   MatCreateMFFD(PetscObjectComm((PetscObject)mat), m, n, PETSC_DECIDE, PETSC_DECIDE, &mf);
1827:   MatMFFDSetFunction(mf, f, ctx);
1828:   MatMFFDSetBase(mf, base, NULL);

1830:   MatComputeOperator(mf, MATAIJ, &Dmf);
1831:   MatComputeOperator(mat, MATAIJ, &Dmat);

1833:   MatDuplicate(Dmat, MAT_COPY_VALUES, &Ddiff);
1834:   MatAXPY(Ddiff, -1.0, Dmf, DIFFERENT_NONZERO_PATTERN);
1835:   MatNorm(Ddiff, NORM_FROBENIUS, &Diffnorm);
1836:   MatNorm(Dmf, NORM_FROBENIUS, &Dmfnorm);
1837:   if (Diffnorm / Dmfnorm > 10 * PETSC_SQRT_MACHINE_EPSILON) {
1838:     flag = PETSC_FALSE;
1839:     if (v) {
1840:       PetscPrintf(PetscObjectComm((PetscObject)mat), "MATSHELL and matrix free multiple appear to produce different results.\n Norm Ratio %g Difference results followed by finite difference one\n", (double)(Diffnorm / Dmfnorm));
1841:       MatViewFromOptions(Ddiff, (PetscObject)mat, "-mat_shell_test_mult_view");
1842:       MatViewFromOptions(Dmf, (PetscObject)mat, "-mat_shell_test_mult_view");
1843:       MatViewFromOptions(Dmat, (PetscObject)mat, "-mat_shell_test_mult_view");
1844:     }
1845:   } else if (v) {
1846:     PetscPrintf(PetscObjectComm((PetscObject)mat), "MATSHELL and matrix free multiple appear to produce the same results\n");
1847:   }
1848:   if (flg) *flg = flag;
1849:   MatDestroy(&Ddiff);
1850:   MatDestroy(&mf);
1851:   MatDestroy(&Dmf);
1852:   MatDestroy(&Dmat);
1853:   return 0;
1854: }

1856: /*@C
1857:     MatShellTestMultTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on a given function.

1859:    Logically Collective; No Fortran Support

1861:     Input Parameters:
1862: +   mat - the `MATSHELL` shell matrix
1863: .   f - the function
1864: .   base - differences are computed around this vector, see `MatMFFDSetBase()`, for Jacobians this is the point at which the Jacobian is being evaluated
1865: -   ctx - an optional context for the function

1867:    Output Parameter:
1868: .   flg - `PETSC_TRUE` if the multiply is likely correct

1870:    Options Database Key:
1871: .   -mat_shell_test_mult_view - print if any differences are detected between the products and print the difference

1873:    Level: advanced

1875: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMult()`
1876: @*/
1877: PetscErrorCode MatShellTestMultTranspose(Mat mat, PetscErrorCode (*f)(void *, Vec, Vec), Vec base, void *ctx, PetscBool *flg)
1878: {
1879:   Vec       x, y, z;
1880:   PetscInt  m, n, M, N;
1881:   Mat       mf, Dmf, Dmat, Ddiff;
1882:   PetscReal Diffnorm, Dmfnorm;
1883:   PetscBool v = PETSC_FALSE, flag = PETSC_TRUE;

1886:   PetscOptionsHasName(NULL, ((PetscObject)mat)->prefix, "-mat_shell_test_mult_transpose_view", &v);
1887:   MatCreateVecs(mat, &x, &y);
1888:   VecDuplicate(y, &z);
1889:   MatGetLocalSize(mat, &m, &n);
1890:   MatGetSize(mat, &M, &N);
1891:   MatCreateMFFD(PetscObjectComm((PetscObject)mat), m, n, M, N, &mf);
1892:   MatMFFDSetFunction(mf, f, ctx);
1893:   MatMFFDSetBase(mf, base, NULL);
1894:   MatComputeOperator(mf, MATAIJ, &Dmf);
1895:   MatTranspose(Dmf, MAT_INPLACE_MATRIX, &Dmf);
1896:   MatComputeOperatorTranspose(mat, MATAIJ, &Dmat);

1898:   MatDuplicate(Dmat, MAT_COPY_VALUES, &Ddiff);
1899:   MatAXPY(Ddiff, -1.0, Dmf, DIFFERENT_NONZERO_PATTERN);
1900:   MatNorm(Ddiff, NORM_FROBENIUS, &Diffnorm);
1901:   MatNorm(Dmf, NORM_FROBENIUS, &Dmfnorm);
1902:   if (Diffnorm / Dmfnorm > 10 * PETSC_SQRT_MACHINE_EPSILON) {
1903:     flag = PETSC_FALSE;
1904:     if (v) {
1905:       PetscPrintf(PetscObjectComm((PetscObject)mat), "MATSHELL and matrix free multiple appear to produce different results.\n Norm Ratio %g Difference results followed by finite difference one\n", (double)(Diffnorm / Dmfnorm));
1906:       MatViewFromOptions(Ddiff, (PetscObject)mat, "-mat_shell_test_mult_transpose_view");
1907:       MatViewFromOptions(Dmf, (PetscObject)mat, "-mat_shell_test_mult_transpose_view");
1908:       MatViewFromOptions(Dmat, (PetscObject)mat, "-mat_shell_test_mult_transpose_view");
1909:     }
1910:   } else if (v) {
1911:     PetscPrintf(PetscObjectComm((PetscObject)mat), "MATSHELL transpose and matrix free multiple appear to produce the same results\n");
1912:   }
1913:   if (flg) *flg = flag;
1914:   MatDestroy(&mf);
1915:   MatDestroy(&Dmat);
1916:   MatDestroy(&Ddiff);
1917:   MatDestroy(&Dmf);
1918:   VecDestroy(&x);
1919:   VecDestroy(&y);
1920:   VecDestroy(&z);
1921:   return 0;
1922: }

1924: /*@C
1925:     MatShellSetOperation - Allows user to set a matrix operation for a `MATSHELL` shell matrix.

1927:    Logically Collective

1929:     Input Parameters:
1930: +   mat - the `MATSHELL` shell matrix
1931: .   op - the name of the operation
1932: -   g - the function that provides the operation.

1934:    Level: advanced

1936:     Usage:
1937: .vb
1938:       extern PetscErrorCode usermult(Mat,Vec,Vec);
1939:       MatCreateShell(comm,m,n,M,N,ctx,&A);
1940:       MatShellSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
1941: .ve

1943:     Notes:
1944:     See the file include/petscmat.h for a complete list of matrix
1945:     operations, which all have the form MATOP_<OPERATION>, where
1946:     <OPERATION> is the name (in all capital letters) of the
1947:     user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

1949:     All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
1950:     sequence as the usual matrix interface routines, since they
1951:     are intended to be accessed via the usual matrix interface
1952:     routines, e.g.,
1953: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

1955:     In particular each function MUST return an error code of 0 on success and
1956:     nonzero on failure.

1958:     Within each user-defined routine, the user should call
1959:     `MatShellGetContext()` to obtain the user-defined context that was
1960:     set by `MatCreateShell()`.

1962:     Use `MatSetOperation()` to set an operation for any matrix type. For matrix product operations (i.e. `MatMatXXX()`, `MatTransposeMatXXX()` etc) use `MatShellSetMatProductOperation()`

1964:     Fortran Note:
1965:     For `MatCreateVecs()` the user code should check if the input left or right matrix is -1 and in that case not
1966:        generate a matrix. See src/mat/tests/ex120f.F

1968: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellSetContext()`, `MatSetOperation()`, `MatShellSetManageScalingShifts()`, `MatShellSetMatProductOperation()`
1969: @*/
1970: PetscErrorCode MatShellSetOperation(Mat mat, MatOperation op, void (*g)(void))
1971: {
1973:   PetscTryMethod(mat, "MatShellSetOperation_C", (Mat, MatOperation, void (*)(void)), (mat, op, g));
1974:   return 0;
1975: }

1977: /*@C
1978:     MatShellGetOperation - Gets a matrix function for a `MATSHELL` shell matrix.

1980:     Not Collective

1982:     Input Parameters:
1983: +   mat - the `MATSHELL` shell matrix
1984: -   op - the name of the operation

1986:     Output Parameter:
1987: .   g - the function that provides the operation.

1989:     Level: advanced

1991:     Note:
1992:     See the file include/petscmat.h for a complete list of matrix
1993:     operations, which all have the form MATOP_<OPERATION>, where
1994:     <OPERATION> is the name (in all capital letters) of the
1995:     user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

1997:     All user-provided functions have the same calling
1998:     sequence as the usual matrix interface routines, since they
1999:     are intended to be accessed via the usual matrix interface
2000:     routines, e.g.,
2001: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

2003:     Within each user-defined routine, the user should call
2004:     `MatShellGetContext()` to obtain the user-defined context that was
2005:     set by `MatCreateShell()`.

2007: .seealso: `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellSetOperation()`, `MatShellSetContext()`
2008: @*/
2009: PetscErrorCode MatShellGetOperation(Mat mat, MatOperation op, void (**g)(void))
2010: {
2012:   PetscUseMethod(mat, "MatShellGetOperation_C", (Mat, MatOperation, void (**)(void)), (mat, op, g));
2013:   return 0;
2014: }

2016: /*@
2017:     MatIsShell - Inquires if a matrix is derived from `MATSHELL`

2019:     Input Parameter:
2020: .   mat - the matrix

2022:     Output Parameter:
2023: .   flg - the boolean value

2025:     Level: developer

2027:     Developer Note:
2028:     In the future, we should allow the object type name to be changed still using the `MATSHELL` data structure for other matrices (i.e. `MATTRANSPOSEVIRTUAL`, `MATSCHURCOMPLEMENT` etc)

2030: .seealso: `MATSHELL`, `MATMFFD`, `MatCreateShell()`, `MATTRANSPOSEVIRTUAL`, `MATSCHURCOMPLEMENT`
2031: @*/
2032: PetscErrorCode MatIsShell(Mat mat, PetscBool *flg)
2033: {
2036:   *flg = (PetscBool)(mat->ops->destroy == MatDestroy_Shell);
2037:   return 0;
2038: }