Date: 2013-07-02T14:49:22+00:00

Actual source code: snesnoise.c
petsc-3.4.2 2013-07-02

      2: #include <petsc-private/snesimpl.h>

      4: /* Data used by Jorge's diff parameter computation method */
      5: typedef struct {
      6:   Vec      *workv;           /* work vectors */
      7:   FILE     *fp;              /* output file */
      8:   int      function_count;   /* count of function evaluations for diff param estimation */
      9:   double   fnoise_min;       /* minimim allowable noise */
     10:   double   hopt_min;         /* minimum allowable hopt */
     11:   double   h_first_try;      /* first try for h used in diff parameter estimate */
     12:   PetscInt fnoise_resets;    /* number of times we've reset the noise estimate */
     13:   PetscInt hopt_resets;      /* number of times we've reset the hopt estimate */
     14: } DIFFPAR_MORE;

     17: extern PetscErrorCode SNESNoise_dnest_(PetscInt*,PetscScalar*,PetscScalar*,PetscScalar*,PetscScalar*,PetscScalar*,PetscInt*,PetscScalar*);
     18: static PetscErrorCode JacMatMultCompare(SNES,Vec,Vec,double);
     19: extern PetscErrorCode SNESDefaultMatrixFreeSetParameters2(Mat,double,double,double);
     20: extern PetscErrorCode SNESUnSetMatrixFreeParameter(SNES snes);

     24: PetscErrorCode SNESDiffParameterCreate_More(SNES snes,Vec x,void **outneP)
     25: {
     26:   DIFFPAR_MORE   *neP;
     27:   Vec            w;
     28:   PetscRandom    rctx;  /* random number generator context */
     30:   PetscBool      flg;
     31:   char           noise_file[PETSC_MAX_PATH_LEN];

     34:   PetscNewLog(snes,DIFFPAR_MORE,&neP);

     36:   neP->function_count = 0;
     37:   neP->fnoise_min     = 1.0e-20;
     38:   neP->hopt_min       = 1.0e-8;
     39:   neP->h_first_try    = 1.0e-3;
     40:   neP->fnoise_resets  = 0;
     41:   neP->hopt_resets    = 0;

     43:   /* Create work vectors */
     44:   VecDuplicateVecs(x,3,&neP->workv);
     45:   w    = neP->workv[0];

     47:   /* Set components of vector w to random numbers */
     48:   PetscRandomCreate(PetscObjectComm((PetscObject)snes),&rctx);
     49:   PetscRandomSetFromOptions(rctx);
     50:   VecSetRandom(w,rctx);
     51:   PetscRandomDestroy(&rctx);

     53:   /* Open output file */
     54:   PetscOptionsGetString(((PetscObject)snes)->prefix,"-snes_mf_noise_file",noise_file,PETSC_MAX_PATH_LEN,&flg);
     55:   if (flg) neP->fp = fopen(noise_file,"w");
     56:   else     neP->fp = fopen("noise.out","w");
     57:   if (!neP->fp) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,"Cannot open file");
     58:   PetscInfo(snes,"Creating Jorge's differencing parameter context\n");

     60:   *outneP = neP;
     61:   return(0);
     62: }

     66: PetscErrorCode SNESDiffParameterDestroy_More(void *nePv)
     67: {
     68:   DIFFPAR_MORE   *neP = (DIFFPAR_MORE*)nePv;
     70:   int            err;

     73:   /* Destroy work vectors and close output file */
     74:   VecDestroyVecs(3,&neP->workv);
     75:   err  = fclose(neP->fp);
     76:   if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fclose() failed on file");
     77:   PetscFree(neP);
     78:   return(0);
     79: }

     83: PetscErrorCode SNESDiffParameterCompute_More(SNES snes,void *nePv,Vec x,Vec p,double *fnoise,double *hopt)
     84: {
     85:   DIFFPAR_MORE   *neP = (DIFFPAR_MORE*)nePv;
     86:   Vec            w, xp, fvec;    /* work vectors to use in computing h */
     87:   double         zero = 0.0, hl, hu, h, fnoise_s, fder2_s;
     88:   PetscScalar    alpha;
     89:   PetscScalar    fval[7], tab[7][7], eps[7], f = -1;
     90:   double         rerrf = -1., fder2;
     92:   PetscInt       iter, k, i, j,  info;
     93:   PetscInt       nf = 7;         /* number of function evaluations */
     94:   PetscInt       fcount;
     95:   MPI_Comm       comm;
     96:   FILE           *fp;
     97:   PetscBool      noise_test = PETSC_FALSE;

    100:   PetscObjectGetComm((PetscObject)snes,&comm);
    101:   /* Call to SNESSetUp() just to set data structures in SNES context */
    102:   if (!snes->setupcalled) {SNESSetUp(snes);}

    104:   w    = neP->workv[0];
    105:   xp   = neP->workv[1];
    106:   fvec = neP->workv[2];
    107:   fp   = neP->fp;

    109:   /* Initialize parameters */
    110:   hl       = zero;
    111:   hu       = zero;
    112:   h        = neP->h_first_try;
    113:   fnoise_s = zero;
    114:   fder2_s  = zero;
    115:   fcount   = neP->function_count;

    117:   /* We have 5 tries to attempt to compute a good hopt value */
    118:   SNESGetIterationNumber(snes,&i);
    119:   PetscFPrintf(comm,fp,"\n ------- SNES iteration %D ---------\n",i);
    120:   for (iter=0; iter<5; iter++) {
    121:     neP->h_first_try = h;

    123:     /* Compute the nf function values needed to estimate the noise from
    124:        the difference table */
    125:     for (k=0; k<nf; k++) {
    126:       alpha = h * (k+1 - (nf+1)/2);
    127:       VecWAXPY(xp,alpha,p,x);
    128:       SNESComputeFunction(snes,xp,fvec);
    129:       neP->function_count++;
    130:       VecDot(fvec,w,&fval[k]);
    131:     }
    132:     f = fval[(nf+1)/2 - 1];

    134:     /* Construct the difference table */
    135:     for (i=0; i<nf; i++) tab[i][0] = fval[i];

    137:     for (j=0; j<6; j++) {
    138:       for (i=0; i<nf-j; i++) {
    139:         tab[i][j+1] = tab[i+1][j] - tab[i][j];
    140:       }
    141:     }

    143:     /* Print the difference table */
    144:     PetscFPrintf(comm,fp,"Difference Table: iter = %D\n",iter);
    145:     for (i=0; i<nf; i++) {
    146:       for (j=0; j<nf-i; j++) {
    147:         PetscFPrintf(comm,fp," %10.2e ",tab[i][j]);
    148:       }
    149:       PetscFPrintf(comm,fp,"\n");
    150:     }

    152:     /* Call the noise estimator */
    153:     SNESNoise_dnest_(&nf,fval,&h,fnoise,&fder2,hopt,&info,eps);

    155:     /* Output statements */
    156:     rerrf = *fnoise/PetscAbsScalar(f);
    157:     if (info == 1) {PetscFPrintf(comm,fp,"%s\n","Noise detected");}
    158:     if (info == 2) {PetscFPrintf(comm,fp,"%s\n","Noise not detected; h is too small");}
    159:     if (info == 3) {PetscFPrintf(comm,fp,"%s\n","Noise not detected; h is too large");}
    160:     if (info == 4) {PetscFPrintf(comm,fp,"%s\n","Noise detected, but unreliable hopt");}
    161:     PetscFPrintf(comm,fp,"Approximate epsfcn %G  %G  %G  %G  %G  %G\n",eps[0],eps[1],eps[2],eps[3],eps[4],eps[5]);
    162:     PetscFPrintf(comm,fp,"h = %G, fnoise = %G, fder2 = %G, rerrf = %G, hopt = %G\n\n",h, *fnoise, fder2, rerrf, *hopt);

    164:     /* Save fnoise and fder2. */
    165:     if (*fnoise) fnoise_s = *fnoise;
    166:     if (fder2) fder2_s = fder2;

    168:     /* Check for noise detection. */
    169:     if (fnoise_s && fder2_s) {
    170:       *fnoise = fnoise_s;
    171:       fder2   = fder2_s;
    172:       *hopt   = 1.68*sqrt(*fnoise/PetscAbsScalar(fder2));
    173:       goto theend;
    174:     } else {

    176:       /* Update hl and hu, and determine new h */
    177:       if (info == 2 || info == 4) {
    178:         hl = h;
    179:         if (hu == zero) h = 100*h;
    180:         else            h = PetscMin(100*h,0.1*hu);
    181:       } else if (info == 3) {
    182:         hu = h;
    183:         h  = PetscMax(1.0e-3,sqrt(hl/hu))*hu;
    184:       }
    185:     }
    186:   }
    187: theend:

    189:   if (*fnoise < neP->fnoise_min) {
    190:     PetscFPrintf(comm,fp,"Resetting fnoise: fnoise1 = %G, fnoise_min = %G\n",*fnoise,neP->fnoise_min);
    191:     *fnoise = neP->fnoise_min;
    192:     neP->fnoise_resets++;
    193:   }
    194:   if (*hopt < neP->hopt_min) {
    195:     PetscFPrintf(comm,fp,"Resetting hopt: hopt1 = %G, hopt_min = %G\n",*hopt,neP->hopt_min);
    196:     *hopt = neP->hopt_min;
    197:     neP->hopt_resets++;
    198:   }

    200:   PetscFPrintf(comm,fp,"Errors in derivative:\n");
    201:   PetscFPrintf(comm,fp,"f = %G, fnoise = %G, fder2 = %G, hopt = %G\n",f,*fnoise,fder2,*hopt);

    203:   /* For now, compute h **each** MV Mult!! */
    204:   /*
    205:   PetscOptionsHasName(NULL,"-matrix_free_jorge_each_mvp",&flg);
    206:   if (!flg) {
    207:     Mat mat;
    208:     SNESGetJacobian(snes,&mat,NULL,NULL);
    209:     SNESDefaultMatrixFreeSetParameters2(mat,PETSC_DEFAULT,PETSC_DEFAULT,*hopt);
    210:   }
    211:   */
    212:   fcount = neP->function_count - fcount;
    213:   PetscInfo5(snes,"fct_now = %D, fct_cum = %D, rerrf=%G, sqrt(noise)=%G, h_more=%G\n",fcount,neP->function_count,rerrf,sqrt(*fnoise),*hopt);

    215:   PetscOptionsGetBool(NULL,"-noise_test",&noise_test,NULL);
    216:   if (noise_test) {
    217:     JacMatMultCompare(snes,x,p,*hopt);
    218:   }
    219:   return(0);
    220: }

    224: PetscErrorCode JacMatMultCompare(SNES snes,Vec x,Vec p,double hopt)
    225: {
    226:   Vec            yy1, yy2; /* work vectors */
    227:   PetscViewer    view2;    /* viewer */
    228:   Mat            J;        /* analytic Jacobian (set as preconditioner matrix) */
    229:   Mat            Jmf;      /* matrix-free Jacobian (set as true system matrix) */
    230:   double         h;        /* differencing parameter */
    231:   Vec            f;
    232:   MatStructure   sparsity = DIFFERENT_NONZERO_PATTERN;
    233:   PetscScalar    alpha;
    234:   PetscReal      yy1n,yy2n,enorm;
    236:   PetscInt       i;
    237:   PetscBool      printv = PETSC_FALSE;
    238:   char           filename[32];
    239:   MPI_Comm       comm;

    242:   PetscObjectGetComm((PetscObject)snes,&comm);
    243:   /* Compute function and analytic Jacobian at x */
    244:   SNESGetJacobian(snes,&Jmf,&J,NULL,NULL);
    245:   SNESComputeJacobian(snes,x,&Jmf,&J,&sparsity);
    246:   SNESGetFunction(snes,&f,NULL,NULL);
    247:   SNESComputeFunction(snes,x,f);

    249:   /* Duplicate work vectors */
    250:   VecDuplicate(x,&yy2);
    251:   VecDuplicate(x,&yy1);

    253:   /* Compute true matrix-vector product */
    254:   MatMult(J,p,yy1);
    255:   VecNorm(yy1,NORM_2,&yy1n);

    257:   /* View product vector if desired */
    258:   PetscOptionsGetBool(NULL,"-print_vecs",&printv,NULL);
    259:   if (printv) {
    260:     PetscViewerASCIIOpen(comm,"y1.out",&view2);
    261:     PetscViewerSetFormat(view2,PETSC_VIEWER_ASCII_COMMON);
    262:     VecView(yy1,view2);
    263:     PetscViewerDestroy(&view2);
    264:   }

    266:   /* Test Jacobian-vector product computation */
    267:   alpha = -1.0;
    268:   h     = 0.01 * hopt;
    269:   for (i=0; i<5; i++) {
    270:     /* Set differencing parameter for matrix-free multiplication */
    271:     SNESDefaultMatrixFreeSetParameters2(Jmf,PETSC_DEFAULT,PETSC_DEFAULT,h);

    273:     /* Compute matrix-vector product via differencing approximation */
    274:     MatMult(Jmf,p,yy2);
    275:     VecNorm(yy2,NORM_2,&yy2n);

    277:     /* View product vector if desired */
    278:     if (printv) {
    279:       sprintf(filename,"y2.%d.out",(int)i);
    280:       PetscViewerASCIIOpen(comm,filename,&view2);
    281:       PetscViewerSetFormat(view2,PETSC_VIEWER_ASCII_COMMON);
    282:       VecView(yy2,view2);
    283:       PetscViewerDestroy(&view2);
    284:     }

    286:     /* Compute relative error */
    287:     VecAXPY(yy2,alpha,yy1);
    288:     VecNorm(yy2,NORM_2,&enorm);
    289:     enorm = enorm/yy1n;
    290:     PetscFPrintf(comm,stdout,"h = %G: relative error = %G\n",h,enorm);
    291:     h    *= 10.0;
    292:   }
    293:   return(0);
    294: }

    296: static PetscInt lin_its_total = 0;

    298: PetscErrorCode SNESNoiseMonitor(SNES snes,PetscInt its,double fnorm,void *dummy)
    299: {
    301:   PetscInt       lin_its;

    304:   SNESGetLinearSolveIterations(snes,&lin_its);
    305:   lin_its_total += lin_its;
    306:   PetscPrintf(PetscObjectComm((PetscObject)snes), "iter = %D, SNES Function norm = %G, lin_its = %D, total_lin_its = %D\n",its,fnorm,lin_its,lin_its_total);

    308:   SNESUnSetMatrixFreeParameter(snes);
    309:   return(0);
    310: }