Actual source code: shell.c

petsc-master 2019-07-20
Report Typos and Errors

  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: typedef struct {
 20:   struct _MatShellOps ops[1];

 22:   PetscScalar vscale,vshift;
 23:   Vec         dshift;
 24:   Vec         left,right;
 25:   Vec         left_work,right_work;
 26:   Vec         left_add_work,right_add_work;
 27:   Mat         axpy;
 28:   PetscScalar axpy_vscale;
 29:   PetscBool   managescalingshifts;                   /* The user will manage the scaling and shifts for the MATSHELL, not the default */
 30:   /* support for ZeroRows/Columns operations */
 31:   IS          zrows;
 32:   IS          zcols;
 33:   Vec         zvals;
 34:   Vec         zvals_w;
 35:   VecScatter  zvals_sct_r;
 36:   VecScatter  zvals_sct_c;
 37:   void        *ctx;
 38: } Mat_Shell;


 41: /*
 42:      Store and scale values on zeroed rows
 43:      xx = [x_1, 0], 0 on zeroed columns
 44: */
 45: static PetscErrorCode MatShellPreZeroRight(Mat A,Vec x,Vec *xx)
 46: {
 47:   Mat_Shell      *shell = (Mat_Shell*)A->data;

 51:   *xx = x;
 52:   if (shell->zrows) {
 53:     VecSet(shell->zvals_w,0.0);
 54:     VecScatterBegin(shell->zvals_sct_c,x,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
 55:     VecScatterEnd(shell->zvals_sct_c,x,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
 56:     VecPointwiseMult(shell->zvals_w,shell->zvals_w,shell->zvals);
 57:   }
 58:   if (shell->zcols) {
 59:     if (!shell->right_work) {
 60:       MatCreateVecs(A,&shell->right_work,NULL);
 61:     }
 62:     VecCopy(x,shell->right_work);
 63:     VecISSet(shell->right_work,shell->zcols,0.0);
 64:     *xx  = shell->right_work;
 65:   }
 66:   return(0);
 67: }

 69: /* Insert properly diagonally scaled values stored in MatShellPreZeroRight */
 70: static PetscErrorCode MatShellPostZeroLeft(Mat A,Vec x)
 71: {
 72:   Mat_Shell      *shell = (Mat_Shell*)A->data;

 76:   if (shell->zrows) {
 77:     VecScatterBegin(shell->zvals_sct_r,shell->zvals_w,x,INSERT_VALUES,SCATTER_REVERSE);
 78:     VecScatterEnd(shell->zvals_sct_r,shell->zvals_w,x,INSERT_VALUES,SCATTER_REVERSE);
 79:   }
 80:   return(0);
 81: }

 83: /*
 84:      Store and scale values on zeroed rows
 85:      xx = [x_1, 0], 0 on zeroed rows
 86: */
 87: static PetscErrorCode MatShellPreZeroLeft(Mat A,Vec x,Vec *xx)
 88: {
 89:   Mat_Shell      *shell = (Mat_Shell*)A->data;

 93:   *xx = NULL;
 94:   if (!shell->zrows) {
 95:     *xx = x;
 96:   } else {
 97:     if (!shell->left_work) {
 98:       MatCreateVecs(A,NULL,&shell->left_work);
 99:     }
100:     VecCopy(x,shell->left_work);
101:     VecSet(shell->zvals_w,0.0);
102:     VecScatterBegin(shell->zvals_sct_r,shell->zvals_w,shell->left_work,INSERT_VALUES,SCATTER_REVERSE);
103:     VecScatterEnd(shell->zvals_sct_r,shell->zvals_w,shell->left_work,INSERT_VALUES,SCATTER_REVERSE);
104:     VecScatterBegin(shell->zvals_sct_r,x,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
105:     VecScatterEnd(shell->zvals_sct_r,x,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
106:     VecPointwiseMult(shell->zvals_w,shell->zvals_w,shell->zvals);
107:     *xx  = shell->left_work;
108:   }
109:   return(0);
110: }

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

119:   if (shell->zcols) {
120:     VecISSet(x,shell->zcols,0.0);
121:   }
122:   if (shell->zrows) {
123:     VecScatterBegin(shell->zvals_sct_c,shell->zvals_w,x,ADD_VALUES,SCATTER_REVERSE);
124:     VecScatterEnd(shell->zvals_sct_c,shell->zvals_w,x,ADD_VALUES,SCATTER_REVERSE);
125:   }
126:   return(0);
127: }

129: /*
130:       xx = diag(left)*x
131: */
132: static PetscErrorCode MatShellPreScaleLeft(Mat A,Vec x,Vec *xx)
133: {
134:   Mat_Shell      *shell = (Mat_Shell*)A->data;

138:   *xx = NULL;
139:   if (!shell->left) {
140:     *xx = x;
141:   } else {
142:     if (!shell->left_work) {VecDuplicate(shell->left,&shell->left_work);}
143:     VecPointwiseMult(shell->left_work,x,shell->left);
144:     *xx  = shell->left_work;
145:   }
146:   return(0);
147: }

149: /*
150:      xx = diag(right)*x
151: */
152: static PetscErrorCode MatShellPreScaleRight(Mat A,Vec x,Vec *xx)
153: {
154:   Mat_Shell      *shell = (Mat_Shell*)A->data;

158:   *xx = NULL;
159:   if (!shell->right) {
160:     *xx = x;
161:   } else {
162:     if (!shell->right_work) {VecDuplicate(shell->right,&shell->right_work);}
163:     VecPointwiseMult(shell->right_work,x,shell->right);
164:     *xx  = shell->right_work;
165:   }
166:   return(0);
167: }

169: /*
170:     x = diag(left)*x
171: */
172: static PetscErrorCode MatShellPostScaleLeft(Mat A,Vec x)
173: {
174:   Mat_Shell      *shell = (Mat_Shell*)A->data;

178:   if (shell->left) {VecPointwiseMult(x,x,shell->left);}
179:   return(0);
180: }

182: /*
183:     x = diag(right)*x
184: */
185: static PetscErrorCode MatShellPostScaleRight(Mat A,Vec x)
186: {
187:   Mat_Shell      *shell = (Mat_Shell*)A->data;

191:   if (shell->right) {VecPointwiseMult(x,x,shell->right);}
192:   return(0);
193: }

195: /*
196:          Y = vscale*Y + diag(dshift)*X + vshift*X

198:          On input Y already contains A*x
199: */
200: static PetscErrorCode MatShellShiftAndScale(Mat A,Vec X,Vec Y)
201: {
202:   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: /*@
226:     MatShellGetContext - Returns the user-provided context associated with a shell matrix.

228:     Not Collective

230:     Input Parameter:
231: .   mat - the matrix, should have been created with MatCreateShell()

233:     Output Parameter:
234: .   ctx - the user provided context

236:     Level: advanced

238:    Fortran Notes:
239:     To use this from Fortran you must write a Fortran interface definition for this
240:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

242: .seealso: MatCreateShell(), MatShellSetOperation(), MatShellSetContext()
243: @*/
244: PetscErrorCode  MatShellGetContext(Mat mat,void *ctx)
245: {
247:   PetscBool      flg;

252:   PetscObjectTypeCompare((PetscObject)mat,MATSHELL,&flg);
253:   if (flg) *(void**)ctx = ((Mat_Shell*)(mat->data))->ctx;
254:   else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot get context from non-shell matrix");
255:   return(0);
256: }

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

269:   if (shell->axpy) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot diagonal scale MATSHELL after MatAXPY operation");
270:   if (!shell->zvals) {
271:     MatCreateVecs(mat,NULL,&shell->zvals);
272:   }
273:   if (!shell->zvals_w) {
274:     VecDuplicate(shell->zvals,&shell->zvals_w);
275:   }
276:   MatGetOwnershipRange(mat,&rst,NULL);
277:   MatGetOwnershipRangeColumn(mat,&cst,NULL);

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

292:   /* Create scatters for diagonal values communications */
293:   VecScatterDestroy(&shell->zvals_sct_c);
294:   VecScatterDestroy(&shell->zvals_sct_r);

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

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

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

331: static PetscErrorCode MatZeroRows_Shell(Mat mat,PetscInt n,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
332: {
333:   PetscInt       nr, *lrows;

337:   if (x && b) {
338:     Vec          xt;
339:     PetscScalar *vals;
340:     PetscInt    *gcols,i,st,nl,nc;

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

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

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

375: static PetscErrorCode MatZeroRowsColumns_Shell(Mat mat,PetscInt n,const PetscInt rowscols[],PetscScalar diag,Vec x,Vec b)
376: {
377:   PetscInt       *lrows, *lcols;
378:   PetscInt       nr, nc;
379:   PetscBool      congruent;

383:   if (x && b) {
384:     Vec          xt, bt;
385:     PetscScalar *vals;
386:     PetscInt    *grows,*gcols,i,st,nl;

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

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

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

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

446: PetscErrorCode MatDestroy_Shell(Mat mat)
447: {
449:   Mat_Shell      *shell = (Mat_Shell*)mat->data;

452:   if (shell->ops->destroy) {
453:     (*shell->ops->destroy)(mat);
454:   }
455:   VecDestroy(&shell->left);
456:   VecDestroy(&shell->right);
457:   VecDestroy(&shell->dshift);
458:   VecDestroy(&shell->left_work);
459:   VecDestroy(&shell->right_work);
460:   VecDestroy(&shell->left_add_work);
461:   VecDestroy(&shell->right_add_work);
462:   MatDestroy(&shell->axpy);
463:   VecDestroy(&shell->zvals_w);
464:   VecDestroy(&shell->zvals);
465:   VecScatterDestroy(&shell->zvals_sct_c);
466:   VecScatterDestroy(&shell->zvals_sct_r);
467:   ISDestroy(&shell->zrows);
468:   ISDestroy(&shell->zcols);
469:   PetscFree(mat->data);
470:   return(0);
471: }

473: PetscErrorCode MatCopy_Shell(Mat A,Mat B,MatStructure str)
474: {
475:   Mat_Shell       *shellA = (Mat_Shell*)A->data,*shellB = (Mat_Shell*)B->data;
476:   PetscErrorCode  ierr;
477:   PetscBool       matflg;

480:   PetscObjectTypeCompare((PetscObject)B,MATSHELL,&matflg);
481:   if (!matflg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Output matrix must be a MATSHELL");

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

486:   if (shellA->ops->copy) {
487:     (*shellA->ops->copy)(A,B,str);
488:   }
489:   shellB->vscale = shellA->vscale;
490:   shellB->vshift = shellA->vshift;
491:   if (shellA->dshift) {
492:     if (!shellB->dshift) {
493:       VecDuplicate(shellA->dshift,&shellB->dshift);
494:     }
495:     VecCopy(shellA->dshift,shellB->dshift);
496:   } else {
497:     VecDestroy(&shellB->dshift);
498:   }
499:   if (shellA->left) {
500:     if (!shellB->left) {
501:       VecDuplicate(shellA->left,&shellB->left);
502:     }
503:     VecCopy(shellA->left,shellB->left);
504:   } else {
505:     VecDestroy(&shellB->left);
506:   }
507:   if (shellA->right) {
508:     if (!shellB->right) {
509:       VecDuplicate(shellA->right,&shellB->right);
510:     }
511:     VecCopy(shellA->right,shellB->right);
512:   } else {
513:     VecDestroy(&shellB->right);
514:   }
515:   MatDestroy(&shellB->axpy);
516:   if (shellA->axpy) {
517:     PetscObjectReference((PetscObject)shellA->axpy);
518:     shellB->axpy        = shellA->axpy;
519:     shellB->axpy_vscale = shellA->axpy_vscale;
520:   }
521:   if (shellA->zrows) {
522:     ISDuplicate(shellA->zrows,&shellB->zrows);
523:     if (shellA->zcols) {
524:       ISDuplicate(shellA->zcols,&shellB->zcols);
525:     }
526:     VecDuplicate(shellA->zvals,&shellB->zvals);
527:     VecCopy(shellA->zvals,shellB->zvals);
528:     VecDuplicate(shellA->zvals_w,&shellB->zvals_w);
529:     PetscObjectReference((PetscObject)shellA->zvals_sct_r);
530:     PetscObjectReference((PetscObject)shellA->zvals_sct_c);
531:     shellB->zvals_sct_r = shellA->zvals_sct_r;
532:     shellB->zvals_sct_c = shellA->zvals_sct_c;
533:   }
534:   return(0);
535: }

537: PetscErrorCode MatDuplicate_Shell(Mat mat,MatDuplicateOption op,Mat *M)
538: {
540:   void           *ctx;

543:   MatShellGetContext(mat,&ctx);
544:   MatCreateShell(PetscObjectComm((PetscObject)mat),mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N,ctx,M);
545:   if (op != MAT_DO_NOT_COPY_VALUES) {
546:     MatCopy(mat,*M,SAME_NONZERO_PATTERN);
547:   }
548:   return(0);
549: }

551: PetscErrorCode MatMult_Shell(Mat A,Vec x,Vec y)
552: {
553:   Mat_Shell        *shell = (Mat_Shell*)A->data;
554:   PetscErrorCode   ierr;
555:   Vec              xx;
556:   PetscObjectState instate,outstate;

559:   if (!shell->ops->mult) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Have not provided a MatMult() for this MATSHELL");
560:   MatShellPreZeroRight(A,x,&xx);
561:   MatShellPreScaleRight(A,xx,&xx);
562:   PetscObjectStateGet((PetscObject)y, &instate);
563:   (*shell->ops->mult)(A,xx,y);
564:   PetscObjectStateGet((PetscObject)y, &outstate);
565:   if (instate == outstate) {
566:     /* increase the state of the output vector since the user did not update its state themself as should have been done */
567:     PetscObjectStateIncrease((PetscObject)y);
568:   }
569:   MatShellShiftAndScale(A,xx,y);
570:   MatShellPostScaleLeft(A,y);
571:   MatShellPostZeroLeft(A,y);

573:   if (shell->axpy) {
574:     if (!shell->left_work) {MatCreateVecs(A,&shell->left_work,NULL);}
575:     MatMult(shell->axpy,x,shell->left_work);
576:     VecAXPY(y,shell->axpy_vscale,shell->left_work);
577:   }
578:   return(0);
579: }

581: PetscErrorCode MatMultAdd_Shell(Mat A,Vec x,Vec y,Vec z)
582: {
583:   Mat_Shell      *shell = (Mat_Shell*)A->data;

587:   if (y == z) {
588:     if (!shell->right_add_work) {VecDuplicate(z,&shell->right_add_work);}
589:     MatMult(A,x,shell->right_add_work);
590:     VecAXPY(z,1.0,shell->right_add_work);
591:   } else {
592:     MatMult(A,x,z);
593:     VecAXPY(z,1.0,y);
594:   }
595:   return(0);
596: }

598: PetscErrorCode MatMultTranspose_Shell(Mat A,Vec x,Vec y)
599: {
600:   Mat_Shell        *shell = (Mat_Shell*)A->data;
601:   PetscErrorCode   ierr;
602:   Vec              xx;
603:   PetscObjectState instate,outstate;

606:   MatShellPreZeroLeft(A,x,&xx);
607:   MatShellPreScaleLeft(A,xx,&xx);
608:   PetscObjectStateGet((PetscObject)y, &instate);
609:   if (!shell->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Have not provided a MatMultTranspose() for this MATSHELL");
610:   (*shell->ops->multtranspose)(A,xx,y);
611:   PetscObjectStateGet((PetscObject)y, &outstate);
612:   if (instate == outstate) {
613:     /* increase the state of the output vector since the user did not update its state themself as should have been done */
614:     PetscObjectStateIncrease((PetscObject)y);
615:   }
616:   MatShellShiftAndScale(A,xx,y);
617:   MatShellPostScaleRight(A,y);
618:   MatShellPostZeroRight(A,y);

620:   if (shell->axpy) {
621:     if (!shell->right_work) {MatCreateVecs(A,NULL,&shell->right_work);}
622:     MatMultTranspose(shell->axpy,x,shell->right_work);
623:     VecAXPY(y,shell->axpy_vscale,shell->right_work);
624:   }
625:   return(0);
626: }

628: PetscErrorCode MatMultTransposeAdd_Shell(Mat A,Vec x,Vec y,Vec z)
629: {
630:   Mat_Shell      *shell = (Mat_Shell*)A->data;

634:   if (y == z) {
635:     if (!shell->left_add_work) {VecDuplicate(z,&shell->left_add_work);}
636:     MatMultTranspose(A,x,shell->left_add_work);
637:     VecAXPY(z,1.0,shell->left_add_work);
638:   } else {
639:     MatMultTranspose(A,x,z);
640:     VecAXPY(z,1.0,y);
641:   }
642:   return(0);
643: }

645: /*
646:           diag(left)(vscale*A + diag(dshift) + vshift I)diag(right)
647: */
648: PetscErrorCode MatGetDiagonal_Shell(Mat A,Vec v)
649: {
650:   Mat_Shell      *shell = (Mat_Shell*)A->data;

654:   if (shell->ops->getdiagonal) {
655:     (*shell->ops->getdiagonal)(A,v);
656:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Must provide shell matrix with routine to return diagonal using\nMatShellSetOperation(S,MATOP_GET_DIAGONAL,...)");
657:   VecScale(v,shell->vscale);
658:   if (shell->dshift) {
659:     VecAXPY(v,1.0,shell->dshift);
660:   }
661:   VecShift(v,shell->vshift);
662:   if (shell->left)  {VecPointwiseMult(v,v,shell->left);}
663:   if (shell->right) {VecPointwiseMult(v,v,shell->right);}
664:   if (shell->zrows) {
665:     VecScatterBegin(shell->zvals_sct_r,shell->zvals,v,INSERT_VALUES,SCATTER_REVERSE);
666:     VecScatterEnd(shell->zvals_sct_r,shell->zvals,v,INSERT_VALUES,SCATTER_REVERSE);
667:   }
668:   if (shell->axpy) {
669:     if (!shell->left_work) {VecDuplicate(v,&shell->left_work);}
670:     MatGetDiagonal(shell->axpy,shell->left_work);
671:     VecAXPY(v,shell->axpy_vscale,shell->left_work);
672:   }
673:   return(0);
674: }

676: PetscErrorCode MatShift_Shell(Mat Y,PetscScalar a)
677: {
678:   Mat_Shell      *shell = (Mat_Shell*)Y->data;

682:   if (shell->left || shell->right) {
683:     if (!shell->dshift) {
684:       VecDuplicate(shell->left ? shell->left : shell->right, &shell->dshift);
685:       VecSet(shell->dshift,a);
686:     } else {
687:       if (shell->left)  {VecPointwiseMult(shell->dshift,shell->dshift,shell->left);}
688:       if (shell->right) {VecPointwiseMult(shell->dshift,shell->dshift,shell->right);}
689:       VecShift(shell->dshift,a);
690:     }
691:     if (shell->left)  {VecPointwiseDivide(shell->dshift,shell->dshift,shell->left);}
692:     if (shell->right) {VecPointwiseDivide(shell->dshift,shell->dshift,shell->right);}
693:   } else shell->vshift += a;
694:   if (shell->zrows) {
695:     VecShift(shell->zvals,a);
696:   }
697:   return(0);
698: }

700: PetscErrorCode MatDiagonalSet_Shell_Private(Mat A,Vec D,PetscScalar s)
701: {
702:   Mat_Shell      *shell = (Mat_Shell*)A->data;

706:   if (!shell->dshift) {VecDuplicate(D,&shell->dshift);}
707:   if (shell->left || shell->right) {
708:     if (!shell->right_work) {VecDuplicate(shell->left ? shell->left : shell->right, &shell->right_work);}
709:     if (shell->left && shell->right)  {
710:       VecPointwiseDivide(shell->right_work,D,shell->left);
711:       VecPointwiseDivide(shell->right_work,shell->right_work,shell->right);
712:     } else if (shell->left) {
713:       VecPointwiseDivide(shell->right_work,D,shell->left);
714:     } else {
715:       VecPointwiseDivide(shell->right_work,D,shell->right);
716:     }
717:     VecAXPY(shell->dshift,s,shell->right_work);
718:   } else {
719:     VecAXPY(shell->dshift,s,D);
720:   }
721:   return(0);
722: }

724: PetscErrorCode MatDiagonalSet_Shell(Mat A,Vec D,InsertMode ins)
725: {
726:   Mat_Shell      *shell = (Mat_Shell*)A->data;
727:   Vec            d;

731:   if (ins == INSERT_VALUES) {
732:     if (!A->ops->getdiagonal) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Operation MATOP_GETDIAGONAL must be set first");
733:     VecDuplicate(D,&d);
734:     MatGetDiagonal(A,d);
735:     MatDiagonalSet_Shell_Private(A,d,-1.);
736:     MatDiagonalSet_Shell_Private(A,D,1.);
737:     VecDestroy(&d);
738:     if (shell->zrows) {
739:       VecCopy(D,shell->zvals);
740:     }
741:   } else {
742:     MatDiagonalSet_Shell_Private(A,D,1.);
743:     if (shell->zrows) {
744:       VecAXPY(shell->zvals,1.0,D);
745:     }
746:   }
747:   return(0);
748: }

750: PetscErrorCode MatScale_Shell(Mat Y,PetscScalar a)
751: {
752:   Mat_Shell      *shell = (Mat_Shell*)Y->data;

756:   shell->vscale *= a;
757:   shell->vshift *= a;
758:   if (shell->dshift) {
759:     VecScale(shell->dshift,a);
760:   }
761:   shell->axpy_vscale *= a;
762:   if (shell->zrows) {
763:     VecScale(shell->zvals,a);
764:   }
765:   return(0);
766: }

768: static PetscErrorCode MatDiagonalScale_Shell(Mat Y,Vec left,Vec right)
769: {
770:   Mat_Shell      *shell = (Mat_Shell*)Y->data;

774:   if (shell->axpy) SETERRQ(PetscObjectComm((PetscObject)Y),PETSC_ERR_SUP,"Cannot diagonal scale MATSHELL after MatAXPY operation");
775:   if (left) {
776:     if (!shell->left) {
777:       VecDuplicate(left,&shell->left);
778:       VecCopy(left,shell->left);
779:     } else {
780:       VecPointwiseMult(shell->left,shell->left,left);
781:     }
782:     if (shell->zrows) {
783:       VecPointwiseMult(shell->zvals,shell->zvals,left);
784:     }
785:   }
786:   if (right) {
787:     if (!shell->right) {
788:       VecDuplicate(right,&shell->right);
789:       VecCopy(right,shell->right);
790:     } else {
791:       VecPointwiseMult(shell->right,shell->right,right);
792:     }
793:     if (shell->zrows) {
794:       if (!shell->left_work) {
795:         MatCreateVecs(Y,NULL,&shell->left_work);
796:       }
797:       VecSet(shell->zvals_w,1.0);
798:       VecScatterBegin(shell->zvals_sct_c,right,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
799:       VecScatterEnd(shell->zvals_sct_c,right,shell->zvals_w,INSERT_VALUES,SCATTER_FORWARD);
800:       VecPointwiseMult(shell->zvals,shell->zvals,shell->zvals_w);
801:     }
802:   }
803:   return(0);
804: }

806: PetscErrorCode MatAssemblyEnd_Shell(Mat Y,MatAssemblyType t)
807: {
808:   Mat_Shell      *shell = (Mat_Shell*)Y->data;

812:   if (t == MAT_FINAL_ASSEMBLY) {
813:     shell->vshift = 0.0;
814:     shell->vscale = 1.0;
815:     VecDestroy(&shell->dshift);
816:     VecDestroy(&shell->left);
817:     VecDestroy(&shell->right);
818:     MatDestroy(&shell->axpy);
819:     VecScatterDestroy(&shell->zvals_sct_c);
820:     VecScatterDestroy(&shell->zvals_sct_r);
821:     ISDestroy(&shell->zrows);
822:     ISDestroy(&shell->zcols);
823:   }
824:   return(0);
825: }

827: static PetscErrorCode MatMissingDiagonal_Shell(Mat A,PetscBool  *missing,PetscInt *d)
828: {
830:   *missing = PETSC_FALSE;
831:   return(0);
832: }

834: PetscErrorCode MatAXPY_Shell(Mat Y,PetscScalar a,Mat X,MatStructure str)
835: {
836:   Mat_Shell      *shell = (Mat_Shell*)Y->data;

840:   PetscObjectReference((PetscObject)X);
841:   MatDestroy(&shell->axpy);
842:   shell->axpy        = X;
843:   shell->axpy_vscale = a;
844:   return(0);
845: }

847: static struct _MatOps MatOps_Values = {0,
848:                                        0,
849:                                        0,
850:                                        0,
851:                                 /* 4*/ MatMultAdd_Shell,
852:                                        0,
853:                                        MatMultTransposeAdd_Shell,
854:                                        0,
855:                                        0,
856:                                        0,
857:                                 /*10*/ 0,
858:                                        0,
859:                                        0,
860:                                        0,
861:                                        0,
862:                                 /*15*/ 0,
863:                                        0,
864:                                        0,
865:                                        MatDiagonalScale_Shell,
866:                                        0,
867:                                 /*20*/ 0,
868:                                        MatAssemblyEnd_Shell,
869:                                        0,
870:                                        0,
871:                                 /*24*/ MatZeroRows_Shell,
872:                                        0,
873:                                        0,
874:                                        0,
875:                                        0,
876:                                 /*29*/ 0,
877:                                        0,
878:                                        0,
879:                                        0,
880:                                        0,
881:                                 /*34*/ MatDuplicate_Shell,
882:                                        0,
883:                                        0,
884:                                        0,
885:                                        0,
886:                                 /*39*/ MatAXPY_Shell,
887:                                        0,
888:                                        0,
889:                                        0,
890:                                        MatCopy_Shell,
891:                                 /*44*/ 0,
892:                                        MatScale_Shell,
893:                                        MatShift_Shell,
894:                                        MatDiagonalSet_Shell,
895:                                        MatZeroRowsColumns_Shell,
896:                                 /*49*/ 0,
897:                                        0,
898:                                        0,
899:                                        0,
900:                                        0,
901:                                 /*54*/ 0,
902:                                        0,
903:                                        0,
904:                                        0,
905:                                        0,
906:                                 /*59*/ 0,
907:                                        MatDestroy_Shell,
908:                                        0,
909:                                        MatConvertFrom_Shell,
910:                                        0,
911:                                 /*64*/ 0,
912:                                        0,
913:                                        0,
914:                                        0,
915:                                        0,
916:                                 /*69*/ 0,
917:                                        0,
918:                                        MatConvert_Shell,
919:                                        0,
920:                                        0,
921:                                 /*74*/ 0,
922:                                        0,
923:                                        0,
924:                                        0,
925:                                        0,
926:                                 /*79*/ 0,
927:                                        0,
928:                                        0,
929:                                        0,
930:                                        0,
931:                                 /*84*/ 0,
932:                                        0,
933:                                        0,
934:                                        0,
935:                                        0,
936:                                 /*89*/ 0,
937:                                        0,
938:                                        0,
939:                                        0,
940:                                        0,
941:                                 /*94*/ 0,
942:                                        0,
943:                                        0,
944:                                        0,
945:                                        0,
946:                                 /*99*/ 0,
947:                                        0,
948:                                        0,
949:                                        0,
950:                                        0,
951:                                /*104*/ 0,
952:                                        0,
953:                                        0,
954:                                        0,
955:                                        0,
956:                                /*109*/ 0,
957:                                        0,
958:                                        0,
959:                                        0,
960:                                        MatMissingDiagonal_Shell,
961:                                /*114*/ 0,
962:                                        0,
963:                                        0,
964:                                        0,
965:                                        0,
966:                                /*119*/ 0,
967:                                        0,
968:                                        0,
969:                                        0,
970:                                        0,
971:                                /*124*/ 0,
972:                                        0,
973:                                        0,
974:                                        0,
975:                                        0,
976:                                /*129*/ 0,
977:                                        0,
978:                                        0,
979:                                        0,
980:                                        0,
981:                                /*134*/ 0,
982:                                        0,
983:                                        0,
984:                                        0,
985:                                        0,
986:                                /*139*/ 0,
987:                                        0,
988:                                        0
989: };

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

994:   Level: advanced

996: .seealso: MatCreateShell()
997: M*/

999: PETSC_EXTERN PetscErrorCode MatCreate_Shell(Mat A)
1000: {
1001:   Mat_Shell      *b;

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

1007:   PetscNewLog(A,&b);
1008:   A->data = (void*)b;

1010:   PetscLayoutSetUp(A->rmap);
1011:   PetscLayoutSetUp(A->cmap);

1013:   b->ctx                 = 0;
1014:   b->vshift              = 0.0;
1015:   b->vscale              = 1.0;
1016:   b->managescalingshifts = PETSC_TRUE;
1017:   A->assembled           = PETSC_TRUE;
1018:   A->preallocated        = PETSC_FALSE;

1020:   PetscObjectChangeTypeName((PetscObject)A,MATSHELL);
1021:   return(0);
1022: }

1024: /*@C
1025:    MatCreateShell - Creates a new matrix class for use with a user-defined
1026:    private data storage format.

1028:   Collective

1030:    Input Parameters:
1031: +  comm - MPI communicator
1032: .  m - number of local rows (must be given)
1033: .  n - number of local columns (must be given)
1034: .  M - number of global rows (may be PETSC_DETERMINE)
1035: .  N - number of global columns (may be PETSC_DETERMINE)
1036: -  ctx - pointer to data needed by the shell matrix routines

1038:    Output Parameter:
1039: .  A - the matrix

1041:    Level: advanced

1043:   Usage:
1044: $    extern int mult(Mat,Vec,Vec);
1045: $    MatCreateShell(comm,m,n,M,N,ctx,&mat);
1046: $    MatShellSetOperation(mat,MATOP_MULT,(void(*)(void))mult);
1047: $    [ Use matrix for operations that have been set ]
1048: $    MatDestroy(mat);

1050:    Notes:
1051:    The shell matrix type is intended to provide a simple class to use
1052:    with KSP (such as, for use with matrix-free methods). You should not
1053:    use the shell type if you plan to define a complete matrix class.

1055:    Fortran Notes:
1056:     To use this from Fortran with a ctx you must write an interface definition for this
1057:     function and for MatShellGetContext() that tells Fortran the Fortran derived data type you are passing
1058:     in as the ctx argument.

1060:    PETSc requires that matrices and vectors being used for certain
1061:    operations are partitioned accordingly.  For example, when
1062:    creating a shell matrix, A, that supports parallel matrix-vector
1063:    products using MatMult(A,x,y) the user should set the number
1064:    of local matrix rows to be the number of local elements of the
1065:    corresponding result vector, y. Note that this is information is
1066:    required for use of the matrix interface routines, even though
1067:    the shell matrix may not actually be physically partitioned.
1068:    For example,

1070: $
1071: $     Vec x, y
1072: $     extern int mult(Mat,Vec,Vec);
1073: $     Mat A
1074: $
1075: $     VecCreateMPI(comm,PETSC_DECIDE,M,&y);
1076: $     VecCreateMPI(comm,PETSC_DECIDE,N,&x);
1077: $     VecGetLocalSize(y,&m);
1078: $     VecGetLocalSize(x,&n);
1079: $     MatCreateShell(comm,m,n,M,N,ctx,&A);
1080: $     MatShellSetOperation(mat,MATOP_MULT,(void(*)(void))mult);
1081: $     MatMult(A,x,y);
1082: $     MatDestroy(&A);
1083: $     VecDestroy(&y);
1084: $     VecDestroy(&x);
1085: $


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


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

1094:     Developers Notes:
1095:     Regarding shifting and scaling. The general form is

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

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

1103:           A is the user provided function.

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

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

1113: .seealso: MatShellSetOperation(), MatHasOperation(), MatShellGetContext(), MatShellSetContext(), MATSHELL, MatShellSetManageScalingShifts()
1114: @*/
1115: PetscErrorCode  MatCreateShell(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,void *ctx,Mat *A)
1116: {

1120:   MatCreate(comm,A);
1121:   MatSetSizes(*A,m,n,M,N);
1122:   MatSetType(*A,MATSHELL);
1123:   MatShellSetContext(*A,ctx);
1124:   MatSetUp(*A);
1125:   return(0);
1126: }

1128: /*@
1129:     MatShellSetContext - sets the context for a shell matrix

1131:    Logically Collective on Mat

1133:     Input Parameters:
1134: +   mat - the shell matrix
1135: -   ctx - the context

1137:    Level: advanced

1139:    Fortran Notes:
1140:     To use this from Fortran you must write a Fortran interface definition for this
1141:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

1143: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
1144: @*/
1145: PetscErrorCode  MatShellSetContext(Mat mat,void *ctx)
1146: {
1147:   Mat_Shell      *shell = (Mat_Shell*)mat->data;
1149:   PetscBool      flg;

1153:   PetscObjectTypeCompare((PetscObject)mat,MATSHELL,&flg);
1154:   if (flg) {
1155:     shell->ctx = ctx;
1156:   } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot attach context to non-shell matrix");
1157:   return(0);
1158: }

1160: /*@
1161:     MatShellSetManageScalingShifts - Allows the user to control the scaling and shift operations of the MATSHELL. Must be called immediately
1162:           after MatCreateShell()

1164:    Logically Collective on Mat

1166:     Input Parameter:
1167: .   mat - the shell matrix

1169:   Level: advanced

1171: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellSetContext(), MatShellSetOperation()
1172: @*/
1173: PetscErrorCode MatShellSetManageScalingShifts(Mat A)
1174: {
1176:   Mat_Shell      *shell;
1177:   PetscBool      flg;

1181:   PetscObjectTypeCompare((PetscObject)A,MATSHELL,&flg);
1182:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Can only use with MATSHELL matrices");
1183:   shell = (Mat_Shell*)A->data;
1184:   shell->managescalingshifts = PETSC_FALSE;
1185:   A->ops->diagonalset   = NULL;
1186:   A->ops->diagonalscale = NULL;
1187:   A->ops->scale         = NULL;
1188:   A->ops->shift         = NULL;
1189:   A->ops->axpy          = NULL;
1190:   return(0);
1191: }

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

1196:    Logically Collective on Mat

1198:     Input Parameters:
1199: +   mat - the shell matrix
1200: .   f - the function
1201: .   base - differences are computed around this vector, see MatMFFDSetBase(), for Jacobians this is the point at which the Jacobian is being evaluated
1202: -   ctx - an optional context for the function

1204:    Output Parameter:
1205: .   flg - PETSC_TRUE if the multiply is likely correct

1207:    Options Database:
1208: .   -mat_shell_test_mult_view - print if any differences are detected between the products and print the difference

1210:    Level: advanced

1212:    Fortran Notes:
1213:     Not supported from Fortran

1215: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose()
1216: @*/
1217: PetscErrorCode  MatShellTestMult(Mat mat,PetscErrorCode (*f)(void*,Vec,Vec),Vec base,void *ctx,PetscBool *flg)
1218: {
1220:   PetscInt       m,n;
1221:   Mat            mf,Dmf,Dmat,Ddiff;
1222:   PetscReal      Diffnorm,Dmfnorm;
1223:   PetscBool      v = PETSC_FALSE, flag = PETSC_TRUE;

1227:   PetscOptionsHasName(NULL,((PetscObject)mat)->prefix,"-mat_shell_test_mult_view",&v);
1228:   MatGetLocalSize(mat,&m,&n);
1229:   MatCreateMFFD(PetscObjectComm((PetscObject)mat),m,n,PETSC_DECIDE,PETSC_DECIDE,&mf);
1230:   MatMFFDSetFunction(mf,f,ctx);
1231:   MatMFFDSetBase(mf,base,NULL);

1233:   MatComputeOperator(mf,MATAIJ,&Dmf);
1234:   MatComputeOperator(mat,MATAIJ,&Dmat);

1236:   MatDuplicate(Dmat,MAT_COPY_VALUES,&Ddiff);
1237:   MatAXPY(Ddiff,-1.0,Dmf,DIFFERENT_NONZERO_PATTERN);
1238:   MatNorm(Ddiff,NORM_FROBENIUS,&Diffnorm);
1239:   MatNorm(Dmf,NORM_FROBENIUS,&Dmfnorm);
1240:   if (Diffnorm/Dmfnorm > 10*PETSC_SQRT_MACHINE_EPSILON) {
1241:     flag = PETSC_FALSE;
1242:     if (v) {
1243:       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));
1244:       MatViewFromOptions(Ddiff,(PetscObject)mat,"-mat_shell_test_mult_view");
1245:       MatViewFromOptions(Dmf,(PetscObject)mat,"-mat_shell_test_mult_view");
1246:       MatViewFromOptions(Dmat,(PetscObject)mat,"-mat_shell_test_mult_view");
1247:     }
1248:   } else if (v) {
1249:     PetscPrintf(PetscObjectComm((PetscObject)mat),"MATSHELL and matrix free multiple appear to produce the same results\n");
1250:   }
1251:   if (flg) *flg = flag;
1252:   MatDestroy(&Ddiff);
1253:   MatDestroy(&mf);
1254:   MatDestroy(&Dmf);
1255:   MatDestroy(&Dmat);
1256:   return(0);
1257: }

1259: /*@C
1260:     MatShellTestMultTranpose - Compares the multiply transpose routine provided to the MATSHELL with differencing on a given function.

1262:    Logically Collective on Mat

1264:     Input Parameters:
1265: +   mat - the shell matrix
1266: .   f - the function
1267: .   base - differences are computed around this vector, see MatMFFDSetBase(), for Jacobians this is the point at which the Jacobian is being evaluated
1268: -   ctx - an optional context for the function

1270:    Output Parameter:
1271: .   flg - PETSC_TRUE if the multiply is likely correct

1273:    Options Database:
1274: .   -mat_shell_test_mult_view - print if any differences are detected between the products and print the difference

1276:    Level: advanced

1278:    Fortran Notes:
1279:     Not supported from Fortran

1281: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMult()
1282: @*/
1283: PetscErrorCode  MatShellTestMultTranspose(Mat mat,PetscErrorCode (*f)(void*,Vec,Vec),Vec base,void *ctx,PetscBool *flg)
1284: {
1286:   Vec            x,y,z;
1287:   PetscInt       m,n,M,N;
1288:   Mat            mf,Dmf,Dmat,Ddiff;
1289:   PetscReal      Diffnorm,Dmfnorm;
1290:   PetscBool      v = PETSC_FALSE, flag = PETSC_TRUE;

1294:   PetscOptionsHasName(NULL,((PetscObject)mat)->prefix,"-mat_shell_test_mult_transpose_view",&v);
1295:   MatCreateVecs(mat,&x,&y);
1296:   VecDuplicate(y,&z);
1297:   MatGetLocalSize(mat,&m,&n);
1298:   MatGetSize(mat,&M,&N);
1299:   MatCreateMFFD(PetscObjectComm((PetscObject)mat),m,n,M,N,&mf);
1300:   MatMFFDSetFunction(mf,f,ctx);
1301:   MatMFFDSetBase(mf,base,NULL);
1302:   MatComputeOperator(mf,MATAIJ,&Dmf);
1303:   MatTranspose(Dmf,MAT_INPLACE_MATRIX,&Dmf);
1304:   MatComputeOperatorTranspose(mat,MATAIJ,&Dmat);

1306:   MatDuplicate(Dmat,MAT_COPY_VALUES,&Ddiff);
1307:   MatAXPY(Ddiff,-1.0,Dmf,DIFFERENT_NONZERO_PATTERN);
1308:   MatNorm(Ddiff,NORM_FROBENIUS,&Diffnorm);
1309:   MatNorm(Dmf,NORM_FROBENIUS,&Dmfnorm);
1310:   if (Diffnorm/Dmfnorm > 10*PETSC_SQRT_MACHINE_EPSILON) {
1311:     flag = PETSC_FALSE;
1312:     if (v) {
1313:       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));
1314:       MatViewFromOptions(Ddiff,(PetscObject)mat,"-mat_shell_test_mult_transpose_view");
1315:       MatViewFromOptions(Dmf,(PetscObject)mat,"-mat_shell_test_mult_transpose_view");
1316:       MatViewFromOptions(Dmat,(PetscObject)mat,"-mat_shell_test_mult_transpose_view");
1317:     }
1318:   } else if (v) {
1319:     PetscPrintf(PetscObjectComm((PetscObject)mat),"MATSHELL transpose and matrix free multiple appear to produce the same results\n");
1320:   }
1321:   if (flg) *flg = flag;
1322:   MatDestroy(&mf);
1323:   MatDestroy(&Dmat);
1324:   MatDestroy(&Ddiff);
1325:   MatDestroy(&Dmf);
1326:   VecDestroy(&x);
1327:   VecDestroy(&y);
1328:   VecDestroy(&z);
1329:   return(0);
1330: }

1332: /*@C
1333:     MatShellSetOperation - Allows user to set a matrix operation for a shell matrix.

1335:    Logically Collective on Mat

1337:     Input Parameters:
1338: +   mat - the shell matrix
1339: .   op - the name of the operation
1340: -   f - the function that provides the operation.

1342:    Level: advanced

1344:     Usage:
1345: $      extern PetscErrorCode usermult(Mat,Vec,Vec);
1346: $      MatCreateShell(comm,m,n,M,N,ctx,&A);
1347: $      MatShellSetOperation(A,MATOP_MULT,(void(*)(void))usermult);

1349:     Notes:
1350:     See the file include/petscmat.h for a complete list of matrix
1351:     operations, which all have the form MATOP_<OPERATION>, where
1352:     <OPERATION> is the name (in all capital letters) of the
1353:     user interface routine (e.g., MatMult() -> MATOP_MULT).

1355:     All user-provided functions (except for MATOP_DESTROY) should have the same calling
1356:     sequence as the usual matrix interface routines, since they
1357:     are intended to be accessed via the usual matrix interface
1358:     routines, e.g.,
1359: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

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

1364:     Within each user-defined routine, the user should call
1365:     MatShellGetContext() to obtain the user-defined context that was
1366:     set by MatCreateShell().

1368:     Fortran Notes:
1369:     For MatCreateVecs() the user code should check if the input left or right matrix is -1 and in that case not
1370:        generate a matrix. See src/mat/examples/tests/ex120f.F

1372:     Use MatSetOperation() to set an operation for any matrix type

1374: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellSetContext(), MatSetOperation(), MatShellSetManageScalingShifts()
1375: @*/
1376: PetscErrorCode MatShellSetOperation(Mat mat,MatOperation op,void (*f)(void))
1377: {
1378:   PetscBool      flg;
1379:   Mat_Shell      *shell;

1384:   PetscObjectTypeCompare((PetscObject)mat,MATSHELL,&flg);
1385:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Can only use with MATSHELL matrices");
1386:   shell = (Mat_Shell*)mat->data;

1388:   switch (op) {
1389:   case MATOP_DESTROY:
1390:     shell->ops->destroy = (PetscErrorCode (*)(Mat))f;
1391:     break;
1392:   case MATOP_VIEW:
1393:     if (!mat->ops->viewnative) {
1394:       mat->ops->viewnative = mat->ops->view;
1395:     }
1396:     mat->ops->view = (PetscErrorCode (*)(Mat,PetscViewer))f;
1397:     break;
1398:   case MATOP_COPY:
1399:     shell->ops->copy = (PetscErrorCode (*)(Mat,Mat,MatStructure))f;
1400:     break;
1401:   case MATOP_DIAGONAL_SET:
1402:   case MATOP_DIAGONAL_SCALE:
1403:   case MATOP_SHIFT:
1404:   case MATOP_SCALE:
1405:   case MATOP_AXPY:
1406:   case MATOP_ZERO_ROWS:
1407:   case MATOP_ZERO_ROWS_COLUMNS:
1408:     if (shell->managescalingshifts) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MATSHELL is managing scalings and shifts, see MatShellSetManageScalingShifts()");
1409:     (((void(**)(void))mat->ops)[op]) = f;
1410:     break;
1411:   case MATOP_GET_DIAGONAL:
1412:     if (shell->managescalingshifts) {
1413:       shell->ops->getdiagonal = (PetscErrorCode (*)(Mat,Vec))f;
1414:       mat->ops->getdiagonal   = MatGetDiagonal_Shell;
1415:     } else {
1416:       shell->ops->getdiagonal = NULL;
1417:       mat->ops->getdiagonal   = (PetscErrorCode (*)(Mat,Vec))f;
1418:     }
1419:     break;
1420:   case MATOP_MULT:
1421:     if (shell->managescalingshifts) {
1422:       shell->ops->mult = (PetscErrorCode (*)(Mat,Vec,Vec))f;
1423:       mat->ops->mult   = MatMult_Shell;
1424:     } else {
1425:       shell->ops->mult = NULL;
1426:       mat->ops->mult   = (PetscErrorCode (*)(Mat,Vec,Vec))f;
1427:     }
1428:     break;
1429:   case MATOP_MULT_TRANSPOSE:
1430:     if (shell->managescalingshifts) {
1431:       shell->ops->multtranspose = (PetscErrorCode (*)(Mat,Vec,Vec))f;
1432:       mat->ops->multtranspose   = MatMultTranspose_Shell;
1433:     } else {
1434:       shell->ops->multtranspose = NULL;
1435:       mat->ops->multtranspose   = (PetscErrorCode (*)(Mat,Vec,Vec))f;
1436:     }
1437:     break;
1438:   default:
1439:     (((void(**)(void))mat->ops)[op]) = f;
1440:     break;
1441:   }
1442:   return(0);
1443: }

1445: /*@C
1446:     MatShellGetOperation - Gets a matrix function for a shell matrix.

1448:     Not Collective

1450:     Input Parameters:
1451: +   mat - the shell matrix
1452: -   op - the name of the operation

1454:     Output Parameter:
1455: .   f - the function that provides the operation.

1457:     Level: advanced

1459:     Notes:
1460:     See the file include/petscmat.h for a complete list of matrix
1461:     operations, which all have the form MATOP_<OPERATION>, where
1462:     <OPERATION> is the name (in all capital letters) of the
1463:     user interface routine (e.g., MatMult() -> MATOP_MULT).

1465:     All user-provided functions have the same calling
1466:     sequence as the usual matrix interface routines, since they
1467:     are intended to be accessed via the usual matrix interface
1468:     routines, e.g.,
1469: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

1471:     Within each user-defined routine, the user should call
1472:     MatShellGetContext() to obtain the user-defined context that was
1473:     set by MatCreateShell().

1475: .seealso: MatCreateShell(), MatShellGetContext(), MatShellSetOperation(), MatShellSetContext()
1476: @*/
1477: PetscErrorCode MatShellGetOperation(Mat mat,MatOperation op,void(**f)(void))
1478: {
1479:   PetscBool      flg;
1480:   Mat_Shell      *shell;

1485:   PetscObjectTypeCompare((PetscObject)mat,MATSHELL,&flg);
1486:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Can only use with MATSHELL matrices");
1487:   shell = (Mat_Shell*)mat->data;

1489:   switch (op) {
1490:   case MATOP_DESTROY:
1491:     *f = (void (*)(void))shell->ops->destroy;
1492:     break;
1493:   case MATOP_VIEW:
1494:     *f = (void (*)(void))mat->ops->view;
1495:     break;
1496:   case MATOP_COPY:
1497:     *f = (void (*)(void))shell->ops->copy;
1498:     break;
1499:   case MATOP_DIAGONAL_SET:
1500:   case MATOP_DIAGONAL_SCALE:
1501:   case MATOP_SHIFT:
1502:   case MATOP_SCALE:
1503:   case MATOP_AXPY:
1504:   case MATOP_ZERO_ROWS:
1505:   case MATOP_ZERO_ROWS_COLUMNS:
1506:     *f = (((void (**)(void))mat->ops)[op]);
1507:     break;
1508:   case MATOP_GET_DIAGONAL:
1509:     if (shell->ops->getdiagonal)
1510:       *f = (void (*)(void))shell->ops->getdiagonal;
1511:     else
1512:       *f = (((void (**)(void))mat->ops)[op]);
1513:     break;
1514:   case MATOP_MULT:
1515:     if (shell->ops->mult)
1516:       *f = (void (*)(void))shell->ops->mult;
1517:     else
1518:       *f = (((void (**)(void))mat->ops)[op]);
1519:     break;
1520:   case MATOP_MULT_TRANSPOSE:
1521:     if (shell->ops->multtranspose)
1522:       *f = (void (*)(void))shell->ops->multtranspose;
1523:     else
1524:       *f = (((void (**)(void))mat->ops)[op]);
1525:     break;
1526:   default:
1527:     *f = (((void (**)(void))mat->ops)[op]);
1528:   }
1529:   return(0);
1530: }