Actual source code: snesnoise.c

      1: #define PETSCSNES_DLL

     3:  #include src/snes/snesimpl.h

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

     19: EXTERN PetscErrorCode JacMatMultCompare(SNES,Vec,Vec,double);
     20: EXTERN PetscErrorCode SNESDefaultMatrixFreeSetParameters2(Mat,double,double,double);
     21: EXTERN PetscErrorCode SNESUnSetMatrixFreeParameter(SNES snes);

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

     36:   PetscNew(DIFFPAR_MORE,&neP);
     37:   PetscLogObjectMemory(snes,sizeof(DIFFPAR_MORE));
     38:
     39:   neP->function_count = 0;
     40:   neP->fnoise_min     = 1.0e-20;
     41:   neP->hopt_min       = 1.0e-8;
     42:   neP->h_first_try    = 1.0e-3;
     43:   neP->fnoise_resets  = 0;
     44:   neP->hopt_resets    = 0;

     46:   /* Create work vectors */
     47:   VecDuplicateVecs(x,3,&neP->workv);
     48:   w = neP->workv[0];

     50:   /* Set components of vector w to random numbers */
     51:   PetscRandomCreate(snes->comm,RANDOM_DEFAULT,&rctx);
     52:   VecSetRandom(w,rctx);
     53:   PetscRandomDestroy(rctx);

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

     62:   *outneP = neP;
     63:   return(0);
     64: }

     68: PetscErrorCode DiffParameterDestroy_More(void *nePv)
     69: {
     70:   DIFFPAR_MORE   *neP = (DIFFPAR_MORE *)nePv;

     74:   /* Destroy work vectors and close output file */
     75:   VecDestroyVecs(neP->workv,3);
     76:   fclose(neP->fp);
     77:   PetscFree(neP);
     78:   return(0);
     79: }

     83: PetscErrorCode DiffParameterCompute_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;
     90:   double         rerrf, fder2;
     92:   PetscInt       iter, k, i, j,  info;
     93:   PetscInt       nf = 7;         /* number of function evaluations */
     94:   PetscInt       fcount;
     95:   MPI_Comm       comm = snes->comm;
     96:   FILE           *fp;
     97:   PetscTruth     noise_test;

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

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

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

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

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

    133:     /* Construct the difference table */
    134:     for (i=0; i<nf; i++) {
    135:       tab[i][0] = fval[i];
    136:     }
    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:     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",
    162:         eps[0],eps[1],eps[2],eps[3],eps[4],eps[5]);
    163:     PetscFPrintf(comm,fp,"h = %g, fnoise = %g, fder2 = %g, rerrf = %g, hopt = %g\n\n",
    164:             h, *fnoise, fder2, rerrf, *hopt);

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

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

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

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

    202:   PetscFPrintf(comm,fp,"Errors in derivative:\n");
    203:   PetscFPrintf(comm,fp,"f = %g, fnoise = %g, fder2 = %g, hopt = %g\n",f,*fnoise,fder2,*hopt);

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

    219:   PetscOptionsHasName(PETSC_NULL,"-noise_test",&noise_test);
    220:   if (noise_test) {
    221:     JacMatMultCompare(snes,x,p,*hopt);
    222:   }
    223:   return(0);
    224: }

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

    247:   /* Compute function and analytic Jacobian at x */
    248:   SNESGetJacobian(snes,&Jmf,&J,PETSC_NULL,PETSC_NULL);
    249:   SNESComputeJacobian(snes,x,&Jmf,&J,&sparsity);
    250:   SNESGetFunction(snes,&f,PETSC_NULL,PETSC_NULL);
    251:   SNESComputeFunction(snes,x,f);

    253:   /* Duplicate work vectors */
    254:   VecDuplicate(x,&yy2);
    255:   VecDuplicate(x,&yy1);

    257:   /* Compute true matrix-vector product */
    258:   MatMult(J,p,yy1);
    259:   VecNorm(yy1,NORM_2,&yy1n);

    261:   /* View product vector if desired */
    262:   PetscOptionsHasName(PETSC_NULL,"-print_vecs",&printv);
    263:   if (printv) {
    264:     PetscViewerASCIIOpen(comm,"y1.out",&view2);
    265:     PetscViewerSetFormat(view2,PETSC_VIEWER_ASCII_COMMON);
    266:     VecView(yy1,view2);
    267:     PetscViewerDestroy(view2);
    268:   }

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

    277:     /* Compute matrix-vector product via differencing approximation */
    278:     MatMult(Jmf,p,yy2);
    279:     VecNorm(yy2,NORM_2,&yy2n);

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

    290:     /* Compute relative error */
    291:     VecAXPY(yy2,alpha,yy1);
    292:     VecNorm(yy2,NORM_2,&enorm);
    293:     enorm = enorm/yy1n;
    294:     PetscFPrintf(comm,stdout,"h = %g: relative error = %g\n",h,enorm);
    295:     h *= 10.0;
    296:   }
    297:   return(0);
    298: }

    300: static PetscInt lin_its_total = 0;

    302: PetscErrorCode MyMonitor(SNES snes,PetscInt its,double fnorm,void *dummy)
    303: {
    305:   PetscInt       lin_its;

    308:   SNESGetNumberLinearIterations(snes,&lin_its);
    309:   lin_its_total += lin_its;
    310:   PetscPrintf(snes->comm, "iter = %D, SNES Function norm = %g, lin_its = %D, total_lin_its = %D\n",its,fnorm,lin_its,lin_its_total);

    312:   SNESUnSetMatrixFreeParameter(snes);
    313:   return(0);
    314: }