Actual source code: fdmatrix.c

  1: /*$Id: fdmatrix.c,v 1.92 2001/08/21 21:03:06 bsmith Exp $*/

  3: /*
  4:    This is where the abstract matrix operations are defined that are
  5:   used for finite difference computations of Jacobians using coloring.
  6: */

 8:  #include src/mat/matimpl.h

 10: /* Logging support */
 11: int MAT_FDCOLORING_COOKIE = 0;

 15: int MatFDColoringSetF(MatFDColoring fd,Vec F)
 16: {
 18:   fd->F = F;
 19:   return(0);
 20: }

 24: static int MatFDColoringView_Draw_Zoom(PetscDraw draw,void *Aa)
 25: {
 26:   MatFDColoring fd = (MatFDColoring)Aa;
 27:   int           ierr,i,j;
 28:   PetscReal     x,y;


 32:   /* loop over colors  */
 33:   for (i=0; i<fd->ncolors; i++) {
 34:     for (j=0; j<fd->nrows[i]; j++) {
 35:       y = fd->M - fd->rows[i][j] - fd->rstart;
 36:       x = fd->columnsforrow[i][j];
 37:       PetscDrawRectangle(draw,x,y,x+1,y+1,i+1,i+1,i+1,i+1);
 38:     }
 39:   }
 40:   return(0);
 41: }

 45: static int MatFDColoringView_Draw(MatFDColoring fd,PetscViewer viewer)
 46: {
 47:   int         ierr;
 48:   PetscTruth  isnull;
 49:   PetscDraw   draw;
 50:   PetscReal   xr,yr,xl,yl,h,w;

 53:   PetscViewerDrawGetDraw(viewer,0,&draw);
 54:   PetscDrawIsNull(draw,&isnull); if (isnull) return(0);

 56:   PetscObjectCompose((PetscObject)fd,"Zoomviewer",(PetscObject)viewer);

 58:   xr  = fd->N; yr = fd->M; h = yr/10.0; w = xr/10.0;
 59:   xr += w;     yr += h;    xl = -w;     yl = -h;
 60:   PetscDrawSetCoordinates(draw,xl,yl,xr,yr);
 61:   PetscDrawZoom(draw,MatFDColoringView_Draw_Zoom,fd);
 62:   PetscObjectCompose((PetscObject)fd,"Zoomviewer",PETSC_NULL);
 63:   return(0);
 64: }

 68: /*@C
 69:    MatFDColoringView - Views a finite difference coloring context.

 71:    Collective on MatFDColoring

 73:    Input  Parameters:
 74: +  c - the coloring context
 75: -  viewer - visualization context

 77:    Level: intermediate

 79:    Notes:
 80:    The available visualization contexts include
 81: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
 82: .     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
 83:         output where only the first processor opens
 84:         the file.  All other processors send their 
 85:         data to the first processor to print. 
 86: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

 88:    Notes:
 89:      Since PETSc uses only a small number of basic colors (currently 33), if the coloring
 90:    involves more than 33 then some seemingly identical colors are displayed making it look
 91:    like an illegal coloring. This is just a graphical artifact.

 93: .seealso: MatFDColoringCreate()

 95: .keywords: Mat, finite differences, coloring, view
 96: @*/
 97: int MatFDColoringView(MatFDColoring c,PetscViewer viewer)
 98: {
 99:   int               i,j,ierr;
100:   PetscTruth        isdraw,isascii;
101:   PetscViewerFormat format;

105:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(c->comm);

109:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
110:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);
111:   if (isdraw) {
112:     MatFDColoringView_Draw(c,viewer);
113:   } else if (isascii) {
114:     PetscViewerASCIIPrintf(viewer,"MatFDColoring Object:\n");
115:     PetscViewerASCIIPrintf(viewer,"  Error tolerance=%g\n",c->error_rel);
116:     PetscViewerASCIIPrintf(viewer,"  Umin=%g\n",c->umin);
117:     PetscViewerASCIIPrintf(viewer,"  Number of colors=%d\n",c->ncolors);

119:     PetscViewerGetFormat(viewer,&format);
120:     if (format != PETSC_VIEWER_ASCII_INFO) {
121:       for (i=0; i<c->ncolors; i++) {
122:         PetscViewerASCIIPrintf(viewer,"  Information for color %d\n",i);
123:         PetscViewerASCIIPrintf(viewer,"    Number of columns %d\n",c->ncolumns[i]);
124:         for (j=0; j<c->ncolumns[i]; j++) {
125:           PetscViewerASCIIPrintf(viewer,"      %d\n",c->columns[i][j]);
126:         }
127:         PetscViewerASCIIPrintf(viewer,"    Number of rows %d\n",c->nrows[i]);
128:         for (j=0; j<c->nrows[i]; j++) {
129:           PetscViewerASCIIPrintf(viewer,"      %d %d \n",c->rows[i][j],c->columnsforrow[i][j]);
130:         }
131:       }
132:     }
133:     PetscViewerFlush(viewer);
134:   } else {
135:     SETERRQ1(1,"Viewer type %s not supported for MatFDColoring",((PetscObject)viewer)->type_name);
136:   }
137:   return(0);
138: }

142: /*@
143:    MatFDColoringSetParameters - Sets the parameters for the sparse approximation of
144:    a Jacobian matrix using finite differences.

146:    Collective on MatFDColoring

148:    The Jacobian is estimated with the differencing approximation
149: .vb
150:        F'(u)_{:,i} = [F(u+h*dx_{i}) - F(u)]/h where
151:        h = error_rel*u[i]                 if  abs(u[i]) > umin
152:          = +/- error_rel*umin             otherwise, with +/- determined by the sign of u[i]
153:        dx_{i} = (0, ... 1, .... 0)
154: .ve

156:    Input Parameters:
157: +  coloring - the coloring context
158: .  error_rel - relative error
159: -  umin - minimum allowable u-value magnitude

161:    Level: advanced

163: .keywords: Mat, finite differences, coloring, set, parameters

165: .seealso: MatFDColoringCreate()
166: @*/
167: int MatFDColoringSetParameters(MatFDColoring matfd,PetscReal error,PetscReal umin)
168: {

172:   if (error != PETSC_DEFAULT) matfd->error_rel = error;
173:   if (umin != PETSC_DEFAULT)  matfd->umin      = umin;
174:   return(0);
175: }

179: /*@
180:    MatFDColoringSetFrequency - Sets the frequency for computing new Jacobian
181:    matrices. 

183:    Collective on MatFDColoring

185:    Input Parameters:
186: +  coloring - the coloring context
187: -  freq - frequency (default is 1)

189:    Options Database Keys:
190: .  -mat_fd_coloring_freq <freq>  - Sets coloring frequency

192:    Level: advanced

194:    Notes:
195:    Using a modified Newton strategy, where the Jacobian remains fixed for several
196:    iterations, can be cost effective in terms of overall nonlinear solution 
197:    efficiency.  This parameter indicates that a new Jacobian will be computed every
198:    <freq> nonlinear iterations.  

200: .keywords: Mat, finite differences, coloring, set, frequency

202: .seealso: MatFDColoringCreate(), MatFDColoringGetFrequency(), MatFDColoringSetRecompute()
203: @*/
204: int MatFDColoringSetFrequency(MatFDColoring matfd,int freq)
205: {

209:   matfd->freq = freq;
210:   return(0);
211: }

215: /*@
216:    MatFDColoringGetFrequency - Gets the frequency for computing new Jacobian
217:    matrices. 

219:    Not Collective

221:    Input Parameters:
222: .  coloring - the coloring context

224:    Output Parameters:
225: .  freq - frequency (default is 1)

227:    Options Database Keys:
228: .  -mat_fd_coloring_freq <freq> - Sets coloring frequency

230:    Level: advanced

232:    Notes:
233:    Using a modified Newton strategy, where the Jacobian remains fixed for several
234:    iterations, can be cost effective in terms of overall nonlinear solution 
235:    efficiency.  This parameter indicates that a new Jacobian will be computed every
236:    <freq> nonlinear iterations.  

238: .keywords: Mat, finite differences, coloring, get, frequency

240: .seealso: MatFDColoringSetFrequency()
241: @*/
242: int MatFDColoringGetFrequency(MatFDColoring matfd,int *freq)
243: {
246:   *freq = matfd->freq;
247:   return(0);
248: }

252: /*@C
253:    MatFDColoringSetFunction - Sets the function to use for computing the Jacobian.

255:    Collective on MatFDColoring

257:    Input Parameters:
258: +  coloring - the coloring context
259: .  f - the function
260: -  fctx - the optional user-defined function context

262:    Level: intermediate

264:    Notes:
265:     In Fortran you must call MatFDColoringSetFunctionSNES() for a coloring object to 
266:   be used with the SNES solvers and MatFDColoringSetFunctionTS() if it is to be used
267:   with the TS solvers.

269: .keywords: Mat, Jacobian, finite differences, set, function
270: @*/
271: int MatFDColoringSetFunction(MatFDColoring matfd,int (*f)(void),void *fctx)
272: {
275:   matfd->f    = f;
276:   matfd->fctx = fctx;
277:   return(0);
278: }

282: /*@
283:    MatFDColoringSetFromOptions - Sets coloring finite difference parameters from 
284:    the options database.

286:    Collective on MatFDColoring

288:    The Jacobian, F'(u), is estimated with the differencing approximation
289: .vb
290:        F'(u)_{:,i} = [F(u+h*dx_{i}) - F(u)]/h where
291:        h = error_rel*u[i]                 if  abs(u[i]) > umin
292:          = +/- error_rel*umin             otherwise, with +/- determined by the sign of u[i]
293:        dx_{i} = (0, ... 1, .... 0)
294: .ve

296:    Input Parameter:
297: .  coloring - the coloring context

299:    Options Database Keys:
300: +  -mat_fd_coloring_err <err> - Sets <err> (square root
301:            of relative error in the function)
302: .  -mat_fd_coloring_umin <umin> - Sets umin, the minimum allowable u-value magnitude
303: .  -mat_fd_coloring_freq <freq> - Sets frequency of computing a new Jacobian
304: .  -mat_fd_coloring_view - Activates basic viewing
305: .  -mat_fd_coloring_view_info - Activates viewing info
306: -  -mat_fd_coloring_view_draw - Activates drawing

308:     Level: intermediate

310: .keywords: Mat, finite differences, parameters

312: .seealso: MatFDColoringCreate(), MatFDColoringView(), MatFDColoringSetParameters()

314: @*/
315: int MatFDColoringSetFromOptions(MatFDColoring matfd)
316: {
317:   int        ierr;


322:   PetscOptionsBegin(matfd->comm,matfd->prefix,"Jacobian computation via finite differences option","MatFD");
323:     PetscOptionsReal("-mat_fd_coloring_err","Square root of relative error in function","MatFDColoringSetParameters",matfd->error_rel,&matfd->error_rel,0);
324:     PetscOptionsReal("-mat_fd_coloring_umin","Minimum allowable u magnitude","MatFDColoringSetParameters",matfd->umin,&matfd->umin,0);
325:     PetscOptionsInt("-mat_fd_coloring_freq","How often Jacobian is recomputed","MatFDColoringSetFrequency",matfd->freq,&matfd->freq,0);
326:     /* not used here; but so they are presented in the GUI */
327:     PetscOptionsName("-mat_fd_coloring_view","Print entire datastructure used for Jacobian","None",0);
328:     PetscOptionsName("-mat_fd_coloring_view_info","Print number of colors etc for Jacobian","None",0);
329:     PetscOptionsName("-mat_fd_coloring_view_draw","Plot nonzero structure ofJacobian","None",0);
330:   PetscOptionsEnd();
331:   return(0);
332: }

336: int MatFDColoringView_Private(MatFDColoring fd)
337: {
338:   int        ierr;
339:   PetscTruth flg;

342:   PetscOptionsHasName(PETSC_NULL,"-mat_fd_coloring_view",&flg);
343:   if (flg) {
344:     MatFDColoringView(fd,PETSC_VIEWER_STDOUT_(fd->comm));
345:   }
346:   PetscOptionsHasName(PETSC_NULL,"-mat_fd_coloring_view_info",&flg);
347:   if (flg) {
348:     PetscViewerPushFormat(PETSC_VIEWER_STDOUT_(fd->comm),PETSC_VIEWER_ASCII_INFO);
349:     MatFDColoringView(fd,PETSC_VIEWER_STDOUT_(fd->comm));
350:     PetscViewerPopFormat(PETSC_VIEWER_STDOUT_(fd->comm));
351:   }
352:   PetscOptionsHasName(PETSC_NULL,"-mat_fd_coloring_view_draw",&flg);
353:   if (flg) {
354:     MatFDColoringView(fd,PETSC_VIEWER_DRAW_(fd->comm));
355:     PetscViewerFlush(PETSC_VIEWER_DRAW_(fd->comm));
356:   }
357:   return(0);
358: }

362: /*@C
363:    MatFDColoringCreate - Creates a matrix coloring context for finite difference 
364:    computation of Jacobians.

366:    Collective on Mat

368:    Input Parameters:
369: +  mat - the matrix containing the nonzero structure of the Jacobian
370: -  iscoloring - the coloring of the matrix

372:     Output Parameter:
373: .   color - the new coloring context
374:    
375:     Level: intermediate

377: .seealso: MatFDColoringDestroy(),SNESDefaultComputeJacobianColor(), ISColoringCreate(),
378:           MatFDColoringSetFunction(), MatFDColoringSetFromOptions(), MatFDColoringApply(),
379:           MatFDColoringSetFrequency(), MatFDColoringSetRecompute(), MatFDColoringView(),
380:           MatFDColoringSetParameters()
381: @*/
382: int MatFDColoringCreate(Mat mat,ISColoring iscoloring,MatFDColoring *color)
383: {
384:   MatFDColoring c;
385:   MPI_Comm      comm;
386:   int           ierr,M,N;

389:   PetscLogEventBegin(MAT_FDColoringCreate,mat,0,0,0);
390:   MatGetSize(mat,&M,&N);
391:   if (M != N) SETERRQ(PETSC_ERR_SUP,"Only for square matrices");

393:   PetscObjectGetComm((PetscObject)mat,&comm);
394:   PetscHeaderCreate(c,_p_MatFDColoring,int,MAT_FDCOLORING_COOKIE,0,"MatFDColoring",comm,MatFDColoringDestroy,MatFDColoringView);
395:   PetscLogObjectCreate(c);

397:   if (mat->ops->fdcoloringcreate) {
398:     (*mat->ops->fdcoloringcreate)(mat,iscoloring,c);
399:   } else {
400:     SETERRQ(PETSC_ERR_SUP,"Code not yet written for this matrix type");
401:   }

403:   c->error_rel         = PETSC_SQRT_MACHINE_EPSILON;
404:   c->umin              = 100.0*PETSC_SQRT_MACHINE_EPSILON;
405:   c->freq              = 1;
406:   c->usersetsrecompute = PETSC_FALSE;
407:   c->recompute         = PETSC_FALSE;
408:   c->currentcolor      = -1;

410:   *color = c;
411:   PetscLogEventEnd(MAT_FDColoringCreate,mat,0,0,0);
412:   return(0);
413: }

417: /*@C
418:     MatFDColoringDestroy - Destroys a matrix coloring context that was created
419:     via MatFDColoringCreate().

421:     Collective on MatFDColoring

423:     Input Parameter:
424: .   c - coloring context

426:     Level: intermediate

428: .seealso: MatFDColoringCreate()
429: @*/
430: int MatFDColoringDestroy(MatFDColoring c)
431: {
432:   int i,ierr;

435:   if (--c->refct > 0) return(0);

437:   for (i=0; i<c->ncolors; i++) {
438:     if (c->columns[i])         {PetscFree(c->columns[i]);}
439:     if (c->rows[i])            {PetscFree(c->rows[i]);}
440:     if (c->columnsforrow[i])   {PetscFree(c->columnsforrow[i]);}
441:     if (c->vscaleforrow && c->vscaleforrow[i]) {PetscFree(c->vscaleforrow[i]);}
442:   }
443:   PetscFree(c->ncolumns);
444:   PetscFree(c->columns);
445:   PetscFree(c->nrows);
446:   PetscFree(c->rows);
447:   PetscFree(c->columnsforrow);
448:   if (c->vscaleforrow) {PetscFree(c->vscaleforrow);}
449:   if (c->vscale)       {VecDestroy(c->vscale);}
450:   if (c->w1) {
451:     VecDestroy(c->w1);
452:     VecDestroy(c->w2);
453:     VecDestroy(c->w3);
454:   }
455:   PetscLogObjectDestroy(c);
456:   PetscHeaderDestroy(c);
457:   return(0);
458: }

462: /*@C
463:     MatFDColoringGetPerturbedColumns - Returns the indices of the columns that
464:       that are currently being perturbed.

466:     Not Collective

468:     Input Parameters:
469: .   coloring - coloring context created with MatFDColoringCreate()

471:     Output Parameters:
472: +   n - the number of local columns being perturbed
473: -   cols - the column indices, in global numbering

475:    Level: intermediate

477: .seealso: MatFDColoringCreate(), MatFDColoringDestroy(), MatFDColoringView(), MatFDColoringApply()

479: .keywords: coloring, Jacobian, finite differences
480: @*/
481: EXTERN int MatFDColoringGetPerturbedColumns(MatFDColoring coloring,int *n,int *cols[])
482: {
484:   if (coloring->currentcolor >= 0) {
485:     *n    = coloring->ncolumns[coloring->currentcolor];
486:     *cols = coloring->columns[coloring->currentcolor];
487:   } else {
488:     *n = 0;
489:   }
490:   return(0);
491: }

495: /*@
496:     MatFDColoringApply - Given a matrix for which a MatFDColoring context 
497:     has been created, computes the Jacobian for a function via finite differences.

499:     Collective on MatFDColoring

501:     Input Parameters:
502: +   mat - location to store Jacobian
503: .   coloring - coloring context created with MatFDColoringCreate()
504: .   x1 - location at which Jacobian is to be computed
505: -   sctx - optional context required by function (actually a SNES context)

507:     Options Database Keys:
508: +    -mat_fd_coloring_freq <freq> - Sets coloring frequency
509: .    -mat_fd_coloring_view - Activates basic viewing or coloring
510: .    -mat_fd_coloring_view_draw - Activates drawing of coloring
511: -    -mat_fd_coloring_view_info - Activates viewing of coloring info

513:     Level: intermediate

515: .seealso: MatFDColoringCreate(), MatFDColoringDestroy(), MatFDColoringView()

517: .keywords: coloring, Jacobian, finite differences
518: @*/
519: int MatFDColoringApply(Mat J,MatFDColoring coloring,Vec x1,MatStructure *flag,void *sctx)
520: {
521:   int           (*f)(void *,Vec,Vec,void*) = (int (*)(void *,Vec,Vec,void *))coloring->f;
522:   int           k,ierr,N,start,end,l,row,col,srow,**vscaleforrow,m1,m2;
523:   PetscScalar   dx,mone = -1.0,*y,*xx,*w3_array;
524:   PetscScalar   *vscale_array;
525:   PetscReal     epsilon = coloring->error_rel,umin = coloring->umin;
526:   Vec           w1,w2,w3;
527:   void          *fctx = coloring->fctx;
528:   PetscTruth    flg;



536:   if (coloring->usersetsrecompute) {
537:     if (!coloring->recompute) {
538:       *flag = SAME_PRECONDITIONER;
539:       PetscLogInfo(J,"MatFDColoringApply:Skipping Jacobian, since user called MatFDColorSetRecompute()\n");
540:       return(0);
541:     } else {
542:       coloring->recompute = PETSC_FALSE;
543:     }
544:   }

546:   PetscLogEventBegin(MAT_FDColoringApply,coloring,J,x1,0);
547:   if (J->ops->fdcoloringapply) {
548:     (*J->ops->fdcoloringapply)(J,coloring,x1,flag,sctx);
549:   } else {

551:     if (!coloring->w1) {
552:       VecDuplicate(x1,&coloring->w1);
553:       PetscLogObjectParent(coloring,coloring->w1);
554:       VecDuplicate(x1,&coloring->w2);
555:       PetscLogObjectParent(coloring,coloring->w2);
556:       VecDuplicate(x1,&coloring->w3);
557:       PetscLogObjectParent(coloring,coloring->w3);
558:     }
559:     w1 = coloring->w1; w2 = coloring->w2; w3 = coloring->w3;

561:     MatSetUnfactored(J);
562:     PetscOptionsHasName(PETSC_NULL,"-mat_fd_coloring_dont_rezero",&flg);
563:     if (flg) {
564:       PetscLogInfo(coloring,"MatFDColoringApply: Not calling MatZeroEntries()\n");
565:     } else {
566:       MatZeroEntries(J);
567:     }

569:     VecGetOwnershipRange(x1,&start,&end);
570:     VecGetSize(x1,&N);
571: 
572:     /*
573:       This is a horrible, horrible, hack. See DMMGComputeJacobian_Multigrid() it inproperly sets
574:       coloring->F for the coarser grids from the finest
575:     */
576:     if (coloring->F) {
577:       VecGetLocalSize(coloring->F,&m1);
578:       VecGetLocalSize(w1,&m2);
579:       if (m1 != m2) {
580:         coloring->F = 0;
581:       }
582:     }

584:     if (coloring->F) {
585:       w1          = coloring->F; /* use already computed value of function */
586:       coloring->F = 0;
587:     } else {
588:       PetscLogEventBegin(MAT_FDColoringFunction,0,0,0,0);
589:       (*f)(sctx,x1,w1,fctx);
590:       PetscLogEventEnd(MAT_FDColoringFunction,0,0,0,0);
591:     }

593:     /* 
594:        Compute all the scale factors and share with other processors
595:     */
596:     VecGetArray(x1,&xx);xx = xx - start;
597:     VecGetArray(coloring->vscale,&vscale_array);vscale_array = vscale_array - start;
598:     for (k=0; k<coloring->ncolors; k++) {
599:       /*
600:         Loop over each column associated with color adding the 
601:         perturbation to the vector w3.
602:       */
603:       for (l=0; l<coloring->ncolumns[k]; l++) {
604:         col = coloring->columns[k][l];    /* column of the matrix we are probing for */
605:         dx  = xx[col];
606:         if (dx == 0.0) dx = 1.0;
607: #if !defined(PETSC_USE_COMPLEX)
608:         if (dx < umin && dx >= 0.0)      dx = umin;
609:         else if (dx < 0.0 && dx > -umin) dx = -umin;
610: #else
611:         if (PetscAbsScalar(dx) < umin && PetscRealPart(dx) >= 0.0)     dx = umin;
612:         else if (PetscRealPart(dx) < 0.0 && PetscAbsScalar(dx) < umin) dx = -umin;
613: #endif
614:         dx                *= epsilon;
615:         vscale_array[col] = 1.0/dx;
616:       }
617:     }
618:     vscale_array = vscale_array + start;VecRestoreArray(coloring->vscale,&vscale_array);
619:     VecGhostUpdateBegin(coloring->vscale,INSERT_VALUES,SCATTER_FORWARD);
620:     VecGhostUpdateEnd(coloring->vscale,INSERT_VALUES,SCATTER_FORWARD);

622:     /*  VecView(coloring->vscale,PETSC_VIEWER_STDOUT_WORLD);
623:         VecView(x1,PETSC_VIEWER_STDOUT_WORLD);*/

625:     if (coloring->vscaleforrow) vscaleforrow = coloring->vscaleforrow;
626:     else                        vscaleforrow = coloring->columnsforrow;

628:     VecGetArray(coloring->vscale,&vscale_array);
629:     /*
630:       Loop over each color
631:     */
632:     for (k=0; k<coloring->ncolors; k++) {
633:       coloring->currentcolor = k;
634:       VecCopy(x1,w3);
635:       VecGetArray(w3,&w3_array);w3_array = w3_array - start;
636:       /*
637:         Loop over each column associated with color adding the 
638:         perturbation to the vector w3.
639:       */
640:       for (l=0; l<coloring->ncolumns[k]; l++) {
641:         col = coloring->columns[k][l];    /* column of the matrix we are probing for */
642:         dx  = xx[col];
643:         if (dx == 0.0) dx = 1.0;
644: #if !defined(PETSC_USE_COMPLEX)
645:         if (dx < umin && dx >= 0.0)      dx = umin;
646:         else if (dx < 0.0 && dx > -umin) dx = -umin;
647: #else
648:         if (PetscAbsScalar(dx) < umin && PetscRealPart(dx) >= 0.0)     dx = umin;
649:         else if (PetscRealPart(dx) < 0.0 && PetscAbsScalar(dx) < umin) dx = -umin;
650: #endif
651:         dx            *= epsilon;
652:         if (!PetscAbsScalar(dx)) SETERRQ(1,"Computed 0 differencing parameter");
653:         w3_array[col] += dx;
654:       }
655:       w3_array = w3_array + start; VecRestoreArray(w3,&w3_array);

657:       /*
658:         Evaluate function at x1 + dx (here dx is a vector of perturbations)
659:       */

661:       PetscLogEventBegin(MAT_FDColoringFunction,0,0,0,0);
662:       (*f)(sctx,w3,w2,fctx);
663:       PetscLogEventEnd(MAT_FDColoringFunction,0,0,0,0);
664:       VecAXPY(&mone,w1,w2);

666:       /*
667:         Loop over rows of vector, putting results into Jacobian matrix
668:       */
669:       VecGetArray(w2,&y);
670:       for (l=0; l<coloring->nrows[k]; l++) {
671:         row    = coloring->rows[k][l];
672:         col    = coloring->columnsforrow[k][l];
673:         y[row] *= vscale_array[vscaleforrow[k][l]];
674:         srow   = row + start;
675:         MatSetValues(J,1,&srow,1,&col,y+row,INSERT_VALUES);
676:       }
677:       VecRestoreArray(w2,&y);
678:     }
679:     coloring->currentcolor = -1;
680:     VecRestoreArray(coloring->vscale,&vscale_array);
681:     xx = xx + start; VecRestoreArray(x1,&xx);
682:     MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
683:     MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
684:   }
685:   PetscLogEventEnd(MAT_FDColoringApply,coloring,J,x1,0);

687:   PetscOptionsHasName(PETSC_NULL,"-mat_null_space_test",&flg);
688:   if (flg) {
689:     MatNullSpaceTest(J->nullsp,J);
690:   }
691:   MatFDColoringView_Private(coloring);

693:   return(0);
694: }

698: /*@
699:     MatFDColoringApplyTS - Given a matrix for which a MatFDColoring context 
700:     has been created, computes the Jacobian for a function via finite differences.

702:    Collective on Mat, MatFDColoring, and Vec

704:     Input Parameters:
705: +   mat - location to store Jacobian
706: .   coloring - coloring context created with MatFDColoringCreate()
707: .   x1 - location at which Jacobian is to be computed
708: -   sctx - optional context required by function (actually a SNES context)

710:    Options Database Keys:
711: .  -mat_fd_coloring_freq <freq> - Sets coloring frequency

713:    Level: intermediate

715: .seealso: MatFDColoringCreate(), MatFDColoringDestroy(), MatFDColoringView()

717: .keywords: coloring, Jacobian, finite differences
718: @*/
719: int MatFDColoringApplyTS(Mat J,MatFDColoring coloring,PetscReal t,Vec x1,MatStructure *flag,void *sctx)
720: {
721:   int           (*f)(void *,PetscReal,Vec,Vec,void*)=(int (*)(void *,PetscReal,Vec,Vec,void *))coloring->f;
722:   int           k,ierr,N,start,end,l,row,col,srow,**vscaleforrow;
723:   PetscScalar   dx,mone = -1.0,*y,*xx,*w3_array;
724:   PetscScalar   *vscale_array;
725:   PetscReal     epsilon = coloring->error_rel,umin = coloring->umin;
726:   Vec           w1,w2,w3;
727:   void          *fctx = coloring->fctx;
728:   PetscTruth    flg;


735:   PetscLogEventBegin(MAT_FDColoringApply,coloring,J,x1,0);
736:   if (!coloring->w1) {
737:     VecDuplicate(x1,&coloring->w1);
738:     PetscLogObjectParent(coloring,coloring->w1);
739:     VecDuplicate(x1,&coloring->w2);
740:     PetscLogObjectParent(coloring,coloring->w2);
741:     VecDuplicate(x1,&coloring->w3);
742:     PetscLogObjectParent(coloring,coloring->w3);
743:   }
744:   w1 = coloring->w1; w2 = coloring->w2; w3 = coloring->w3;

746:   MatSetUnfactored(J);
747:   PetscOptionsHasName(PETSC_NULL,"-mat_fd_coloring_dont_rezero",&flg);
748:   if (flg) {
749:     PetscLogInfo(coloring,"MatFDColoringApply: Not calling MatZeroEntries()\n");
750:   } else {
751:     MatZeroEntries(J);
752:   }

754:   VecGetOwnershipRange(x1,&start,&end);
755:   VecGetSize(x1,&N);
756:   PetscLogEventBegin(MAT_FDColoringFunction,0,0,0,0);
757:   (*f)(sctx,t,x1,w1,fctx);
758:   PetscLogEventEnd(MAT_FDColoringFunction,0,0,0,0);

760:   /* 
761:       Compute all the scale factors and share with other processors
762:   */
763:   VecGetArray(x1,&xx);xx = xx - start;
764:   VecGetArray(coloring->vscale,&vscale_array);vscale_array = vscale_array - start;
765:   for (k=0; k<coloring->ncolors; k++) {
766:     /*
767:        Loop over each column associated with color adding the 
768:        perturbation to the vector w3.
769:     */
770:     for (l=0; l<coloring->ncolumns[k]; l++) {
771:       col = coloring->columns[k][l];    /* column of the matrix we are probing for */
772:       dx  = xx[col];
773:       if (dx == 0.0) dx = 1.0;
774: #if !defined(PETSC_USE_COMPLEX)
775:       if (dx < umin && dx >= 0.0)      dx = umin;
776:       else if (dx < 0.0 && dx > -umin) dx = -umin;
777: #else
778:       if (PetscAbsScalar(dx) < umin && PetscRealPart(dx) >= 0.0)     dx = umin;
779:       else if (PetscRealPart(dx) < 0.0 && PetscAbsScalar(dx) < umin) dx = -umin;
780: #endif
781:       dx                *= epsilon;
782:       vscale_array[col] = 1.0/dx;
783:     }
784:   }
785:   vscale_array = vscale_array - start;VecRestoreArray(coloring->vscale,&vscale_array);
786:   VecGhostUpdateBegin(coloring->vscale,INSERT_VALUES,SCATTER_FORWARD);
787:   VecGhostUpdateEnd(coloring->vscale,INSERT_VALUES,SCATTER_FORWARD);

789:   if (coloring->vscaleforrow) vscaleforrow = coloring->vscaleforrow;
790:   else                        vscaleforrow = coloring->columnsforrow;

792:   VecGetArray(coloring->vscale,&vscale_array);
793:   /*
794:       Loop over each color
795:   */
796:   for (k=0; k<coloring->ncolors; k++) {
797:     VecCopy(x1,w3);
798:     VecGetArray(w3,&w3_array);w3_array = w3_array - start;
799:     /*
800:        Loop over each column associated with color adding the 
801:        perturbation to the vector w3.
802:     */
803:     for (l=0; l<coloring->ncolumns[k]; l++) {
804:       col = coloring->columns[k][l];    /* column of the matrix we are probing for */
805:       dx  = xx[col];
806:       if (dx == 0.0) dx = 1.0;
807: #if !defined(PETSC_USE_COMPLEX)
808:       if (dx < umin && dx >= 0.0)      dx = umin;
809:       else if (dx < 0.0 && dx > -umin) dx = -umin;
810: #else
811:       if (PetscAbsScalar(dx) < umin && PetscRealPart(dx) >= 0.0)     dx = umin;
812:       else if (PetscRealPart(dx) < 0.0 && PetscAbsScalar(dx) < umin) dx = -umin;
813: #endif
814:       dx            *= epsilon;
815:       w3_array[col] += dx;
816:     }
817:     w3_array = w3_array + start; VecRestoreArray(w3,&w3_array);

819:     /*
820:        Evaluate function at x1 + dx (here dx is a vector of perturbations)
821:     */
822:     PetscLogEventBegin(MAT_FDColoringFunction,0,0,0,0);
823:     (*f)(sctx,t,w3,w2,fctx);
824:     PetscLogEventEnd(MAT_FDColoringFunction,0,0,0,0);
825:     VecAXPY(&mone,w1,w2);

827:     /*
828:        Loop over rows of vector, putting results into Jacobian matrix
829:     */
830:     VecGetArray(w2,&y);
831:     for (l=0; l<coloring->nrows[k]; l++) {
832:       row    = coloring->rows[k][l];
833:       col    = coloring->columnsforrow[k][l];
834:       y[row] *= vscale_array[vscaleforrow[k][l]];
835:       srow   = row + start;
836:       MatSetValues(J,1,&srow,1,&col,y+row,INSERT_VALUES);
837:     }
838:     VecRestoreArray(w2,&y);
839:   }
840:   VecRestoreArray(coloring->vscale,&vscale_array);
841:   xx    = xx + start; VecRestoreArray(x1,&xx);
842:   MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
843:   MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
844:   PetscLogEventEnd(MAT_FDColoringApply,coloring,J,x1,0);
845:   return(0);
846: }


851: /*@C
852:    MatFDColoringSetRecompute - Indicates that the next time a Jacobian preconditioner
853:      is needed it sholuld be recomputed. Once this is called and the new Jacobian is computed
854:      no additional Jacobian's will be computed (the same one will be used) until this is
855:      called again.

857:    Collective on MatFDColoring

859:    Input  Parameters:
860: .  c - the coloring context

862:    Level: intermediate

864:    Notes: The MatFDColoringSetFrequency() is ignored once this is called

866: .seealso: MatFDColoringCreate(), MatFDColoringSetFrequency()

868: .keywords: Mat, finite differences, coloring
869: @*/
870: int MatFDColoringSetRecompute(MatFDColoring c)
871: {
874:   c->usersetsrecompute = PETSC_TRUE;
875:   c->recompute         = PETSC_TRUE;
876:   return(0);
877: }