xref: /petsc/src/snes/interface/noise/snesnoise.c (revision 22612f2f7cceb60caedd65384cdf99fc989f2aeb)
1 #define PETSCSNES_DLL
2 
3 #include "include/private/snesimpl.h"
4 
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;
16 
17 
18 extern PetscErrorCode dnest_(PetscInt*,PetscScalar*,PetscScalar*,PetscScalar*,PetscScalar*,PetscScalar*,PetscInt*,PetscScalar*);
19 EXTERN PetscErrorCode JacMatMultCompare(SNES,Vec,Vec,double);
20 EXTERN PetscErrorCode SNESDefaultMatrixFreeSetParameters2(Mat,double,double,double);
21 EXTERN PetscErrorCode SNESUnSetMatrixFreeParameter(SNES snes);
22 
23 #undef __FUNCT__
24 #define __FUNCT__ "DiffParameterCreate_More"
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 */
30   PetscErrorCode ierr;
31   PetscTruth     flg;
32   char           noise_file[PETSC_MAX_PATH_LEN];
33 
34   PetscFunctionBegin;
35 
36   ierr = PetscNewLog(snes,DIFFPAR_MORE,&neP);CHKERRQ(ierr);
37   neP->function_count = 0;
38   neP->fnoise_min     = 1.0e-20;
39   neP->hopt_min       = 1.0e-8;
40   neP->h_first_try    = 1.0e-3;
41   neP->fnoise_resets  = 0;
42   neP->hopt_resets    = 0;
43 
44   /* Create work vectors */
45   ierr = VecDuplicateVecs(x,3,&neP->workv);CHKERRQ(ierr);
46   w = neP->workv[0];
47 
48   /* Set components of vector w to random numbers */
49   ierr = PetscRandomCreate(snes->comm,&rctx);CHKERRQ(ierr);
50   ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr);
51   ierr = VecSetRandom(w,rctx);CHKERRQ(ierr);
52   ierr = PetscRandomDestroy(rctx);CHKERRQ(ierr);
53 
54   /* Open output file */
55   ierr = PetscOptionsGetString(snes->prefix,"-snes_mf_noise_file",noise_file,PETSC_MAX_PATH_LEN-1,&flg);CHKERRQ(ierr);
56   if (flg) neP->fp = fopen(noise_file,"w");
57   else     neP->fp = fopen("noise.out","w");
58   if (!neP->fp) SETERRQ(PETSC_ERR_FILE_OPEN,"Cannot open file");
59   ierr = PetscInfo(snes,"Creating Jorge's differencing parameter context\n");CHKERRQ(ierr);
60 
61   *outneP = neP;
62   PetscFunctionReturn(0);
63 }
64 
65 #undef __FUNCT__
66 #define __FUNCT__ "DiffParameterDestroy_More"
67 PetscErrorCode DiffParameterDestroy_More(void *nePv)
68 {
69   DIFFPAR_MORE   *neP = (DIFFPAR_MORE *)nePv;
70   PetscErrorCode ierr;
71 
72   PetscFunctionBegin;
73   /* Destroy work vectors and close output file */
74   ierr = VecDestroyVecs(neP->workv,3);CHKERRQ(ierr);
75   fclose(neP->fp);
76   ierr = PetscFree(neP);CHKERRQ(ierr);
77   PetscFunctionReturn(0);
78 }
79 
80 #undef __FUNCT__
81 #define __FUNCT__ "DiffParameterCompute_More"
82 PetscErrorCode DiffParameterCompute_More(SNES snes,void *nePv,Vec x,Vec p,double *fnoise,double *hopt)
83 {
84   DIFFPAR_MORE   *neP = (DIFFPAR_MORE *)nePv;
85   Vec            w, xp, fvec;    /* work vectors to use in computing h */
86   double         zero = 0.0, hl, hu, h, fnoise_s, fder2_s;
87   PetscScalar    alpha;
88   PetscScalar    fval[7], tab[7][7], eps[7], f;
89   double         rerrf, fder2;
90   PetscErrorCode ierr;
91   PetscInt       iter, k, i, j,  info;
92   PetscInt       nf = 7;         /* number of function evaluations */
93   PetscInt       fcount;
94   MPI_Comm       comm = snes->comm;
95   FILE           *fp;
96   PetscTruth     noise_test;
97 
98   PetscFunctionBegin;
99   /* Call to SNESSetUp() just to set data structures in SNES context */
100   if (!snes->setupcalled) {ierr = SNESSetUp(snes);CHKERRQ(ierr);}
101 
102   w    = neP->workv[0];
103   xp   = neP->workv[1];
104   fvec = neP->workv[2];
105   fp   = neP->fp;
106 
107   /* Initialize parameters */
108   hl       = zero;
109   hu       = zero;
110   h        = neP->h_first_try;
111   fnoise_s = zero;
112   fder2_s  = zero;
113   fcount   = neP->function_count;
114 
115   /* We have 5 tries to attempt to compute a good hopt value */
116   ierr = SNESGetIterationNumber(snes,&i);CHKERRQ(ierr);
117   ierr = PetscFPrintf(comm,fp,"\n ------- SNES iteration %D ---------\n",i);CHKERRQ(ierr);
118   for (iter=0; iter<5; iter++) {
119     neP->h_first_try = h;
120 
121     /* Compute the nf function values needed to estimate the noise from
122        the difference table */
123     for (k=0; k<nf; k++) {
124       alpha = h * ( k+1 - (nf+1)/2 );
125       ierr = VecWAXPY(xp,alpha,p,x);CHKERRQ(ierr);
126       ierr = SNESComputeFunction(snes,xp,fvec);CHKERRQ(ierr);
127       neP->function_count++;
128       ierr = VecDot(fvec,w,&fval[k]);CHKERRQ(ierr);
129     }
130     f = fval[(nf+1)/2 - 1];
131 
132     /* Construct the difference table */
133     for (i=0; i<nf; i++) {
134       tab[i][0] = fval[i];
135     }
136     for (j=0; j<6; j++) {
137       for (i=0; i<nf-j; i++) {
138         tab[i][j+1] = tab[i+1][j] - tab[i][j];
139       }
140     }
141 
142     /* Print the difference table */
143     ierr = PetscFPrintf(comm,fp,"Difference Table: iter = %D\n",iter);CHKERRQ(ierr);
144     for (i=0; i<nf; i++) {
145       for (j=0; j<nf-i; j++) {
146         ierr = PetscFPrintf(comm,fp," %10.2e ",tab[i][j]);CHKERRQ(ierr);
147       }
148       ierr = PetscFPrintf(comm,fp,"\n");CHKERRQ(ierr);
149     }
150 
151     /* Call the noise estimator */
152     ierr = dnest_(&nf,fval,&h,fnoise,&fder2,hopt,&info,eps);CHKERRQ(ierr);
153 
154     /* Output statements */
155     rerrf = *fnoise/PetscAbsScalar(f);
156     if (info == 1) {ierr = PetscFPrintf(comm,fp,"%s\n","Noise detected");CHKERRQ(ierr);}
157     if (info == 2) {ierr = PetscFPrintf(comm,fp,"%s\n","Noise not detected; h is too small");CHKERRQ(ierr);}
158     if (info == 3) {ierr = PetscFPrintf(comm,fp,"%s\n","Noise not detected; h is too large");CHKERRQ(ierr);}
159     if (info == 4) {ierr = PetscFPrintf(comm,fp,"%s\n","Noise detected, but unreliable hopt");CHKERRQ(ierr);}
160     ierr = PetscFPrintf(comm,fp,"Approximate epsfcn %G  %G  %G  %G  %G  %G\n",
161         eps[0],eps[1],eps[2],eps[3],eps[4],eps[5]);CHKERRQ(ierr);
162     ierr = PetscFPrintf(comm,fp,"h = %G, fnoise = %G, fder2 = %G, rerrf = %G, hopt = %G\n\n",
163             h, *fnoise, fder2, rerrf, *hopt);CHKERRQ(ierr);
164 
165     /* Save fnoise and fder2. */
166     if (*fnoise) fnoise_s = *fnoise;
167     if (fder2)  fder2_s = fder2;
168 
169     /* Check for noise detection. */
170     if (fnoise_s && fder2_s) {
171       *fnoise = fnoise_s;
172       fder2 = fder2_s;
173       *hopt = 1.68*sqrt(*fnoise/PetscAbsScalar(fder2));
174       goto theend;
175     } else {
176 
177       /* Update hl and hu, and determine new h */
178       if (info == 2 || info == 4) {
179         hl = h;
180         if (hu == zero) h = 100*h;
181         else            h = PetscMin(100*h,0.1*hu);
182        } else if (info == 3) {
183         hu = h;
184         h = PetscMax(1.0e-3,sqrt(hl/hu))*hu;
185       }
186     }
187   }
188   theend:
189 
190   if (*fnoise < neP->fnoise_min) {
191     ierr = PetscFPrintf(comm,fp,"Resetting fnoise: fnoise1 = %G, fnoise_min = %G\n",*fnoise,neP->fnoise_min);CHKERRQ(ierr);
192     *fnoise = neP->fnoise_min;
193     neP->fnoise_resets++;
194   }
195   if (*hopt < neP->hopt_min) {
196     ierr = PetscFPrintf(comm,fp,"Resetting hopt: hopt1 = %G, hopt_min = %G\n",*hopt,neP->hopt_min);CHKERRQ(ierr);
197     *hopt = neP->hopt_min;
198     neP->hopt_resets++;
199   }
200 
201   ierr = PetscFPrintf(comm,fp,"Errors in derivative:\n");CHKERRQ(ierr);
202   ierr = PetscFPrintf(comm,fp,"f = %G, fnoise = %G, fder2 = %G, hopt = %G\n",f,*fnoise,fder2,*hopt);CHKERRQ(ierr);
203 
204   /* For now, compute h **each** MV Mult!! */
205   /*
206   ierr = PetscOptionsHasName(PETSC_NULL,"-matrix_free_jorge_each_mvp",&flg);CHKERRQ(ierr);
207   if (!flg) {
208     Mat mat;
209     ierr = SNESGetJacobian(snes,&mat,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
210     ierr = SNESDefaultMatrixFreeSetParameters2(mat,PETSC_DEFAULT,PETSC_DEFAULT,*hopt);CHKERRQ(ierr);
211   }
212   */
213   fcount = neP->function_count - fcount;
214   ierr = 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);CHKERRQ(ierr);
215 
216   ierr = PetscOptionsHasName(PETSC_NULL,"-noise_test",&noise_test);CHKERRQ(ierr);
217   if (noise_test) {
218     ierr = JacMatMultCompare(snes,x,p,*hopt);CHKERRQ(ierr);
219   }
220   PetscFunctionReturn(0);
221 }
222 
223 #undef __FUNCT__
224 #define __FUNCT__ "JacMatMultCompare"
225 PetscErrorCode JacMatMultCompare(SNES snes,Vec x,Vec p,double hopt)
226 {
227   Vec            yy1, yy2; /* work vectors */
228   PetscViewer    view2;    /* viewer */
229   Mat            J;        /* analytic Jacobian (set as preconditioner matrix) */
230   Mat            Jmf;      /* matrix-free Jacobian (set as true system matrix) */
231   double         h;        /* differencing parameter */
232   Vec            f;
233   MatStructure   sparsity = DIFFERENT_NONZERO_PATTERN;
234   PetscScalar    alpha;
235   PetscReal      yy1n,yy2n,enorm;
236   PetscErrorCode ierr;
237   PetscInt       i;
238   PetscTruth     printv;
239   char           filename[32];
240   MPI_Comm       comm = snes->comm;
241 
242   PetscFunctionBegin;
243 
244   /* Compute function and analytic Jacobian at x */
245   ierr = SNESGetJacobian(snes,&Jmf,&J,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
246   ierr = SNESComputeJacobian(snes,x,&Jmf,&J,&sparsity);CHKERRQ(ierr);
247   ierr = SNESGetFunction(snes,&f,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);
248   ierr = SNESComputeFunction(snes,x,f);CHKERRQ(ierr);
249 
250   /* Duplicate work vectors */
251   ierr = VecDuplicate(x,&yy2);CHKERRQ(ierr);
252   ierr = VecDuplicate(x,&yy1);CHKERRQ(ierr);
253 
254   /* Compute true matrix-vector product */
255   ierr = MatMult(J,p,yy1);CHKERRQ(ierr);
256   ierr = VecNorm(yy1,NORM_2,&yy1n);CHKERRQ(ierr);
257 
258   /* View product vector if desired */
259   ierr = PetscOptionsHasName(PETSC_NULL,"-print_vecs",&printv);CHKERRQ(ierr);
260   if (printv) {
261     ierr = PetscViewerASCIIOpen(comm,"y1.out",&view2);CHKERRQ(ierr);
262     ierr = PetscViewerSetFormat(view2,PETSC_VIEWER_ASCII_COMMON);CHKERRQ(ierr);
263     ierr = VecView(yy1,view2);CHKERRQ(ierr);
264     ierr = PetscViewerDestroy(view2);CHKERRQ(ierr);
265   }
266 
267   /* Test Jacobian-vector product computation */
268   alpha = -1.0;
269   h = 0.01 * hopt;
270   for (i=0; i<5; i++) {
271     /* Set differencing parameter for matrix-free multiplication */
272     ierr = SNESDefaultMatrixFreeSetParameters2(Jmf,PETSC_DEFAULT,PETSC_DEFAULT,h);CHKERRQ(ierr);
273 
274     /* Compute matrix-vector product via differencing approximation */
275     ierr = MatMult(Jmf,p,yy2);CHKERRQ(ierr);
276     ierr = VecNorm(yy2,NORM_2,&yy2n);CHKERRQ(ierr);
277 
278     /* View product vector if desired */
279     if (printv) {
280       sprintf(filename,"y2.%d.out",(int)i);
281       ierr = PetscViewerASCIIOpen(comm,filename,&view2);CHKERRQ(ierr);
282       ierr = PetscViewerSetFormat(view2,PETSC_VIEWER_ASCII_COMMON);CHKERRQ(ierr);
283       ierr = VecView(yy2,view2);CHKERRQ(ierr);
284       ierr = PetscViewerDestroy(view2);CHKERRQ(ierr);
285     }
286 
287     /* Compute relative error */
288     ierr = VecAXPY(yy2,alpha,yy1);CHKERRQ(ierr);
289     ierr = VecNorm(yy2,NORM_2,&enorm);CHKERRQ(ierr);
290     enorm = enorm/yy1n;
291     ierr = PetscFPrintf(comm,stdout,"h = %G: relative error = %G\n",h,enorm);CHKERRQ(ierr);
292     h *= 10.0;
293   }
294   PetscFunctionReturn(0);
295 }
296 
297 static PetscInt lin_its_total = 0;
298 
299 PetscErrorCode MyMonitor(SNES snes,PetscInt its,double fnorm,void *dummy)
300 {
301   PetscErrorCode ierr;
302   PetscInt       lin_its;
303 
304   PetscFunctionBegin;
305   ierr = SNESGetLinearSolveIterations(snes,&lin_its);CHKERRQ(ierr);
306   lin_its_total += lin_its;
307   ierr = PetscPrintf(snes->comm, "iter = %D, SNES Function norm = %G, lin_its = %D, total_lin_its = %D\n",its,fnorm,lin_its,lin_its_total);CHKERRQ(ierr);
308 
309   ierr = SNESUnSetMatrixFreeParameter(snes);CHKERRQ(ierr);
310   PetscFunctionReturn(0);
311 }
312