Actual source code: ex22.c

petsc-3.4.5 2014-06-29
  2: static const char help[] = "Solves PDE optimization problem using full-space method, interlaces state and adjoint variables.\n\n";

  4: #include <petscdmda.h>
  5: #include <petscdmredundant.h>
  6: #include <petscdmcomposite.h>
  7: #include <petscpf.h>
  8: #include <petscsnes.h>
  9: #include <petsc-private/dmimpl.h>

 11: /*

 13:        w - design variables (what we change to get an optimal solution)
 14:        u - state variables (i.e. the PDE solution)
 15:        lambda - the Lagrange multipliers

 17:             U = (w [u_0 lambda_0 u_1 lambda_1 .....])

 19:        fu, fw, flambda contain the gradient of L(w,u,lambda)

 21:             FU = (fw [fu_0 flambda_0 .....])

 23:        In this example the PDE is
 24:                              Uxx = 2,
 25:                             u(0) = w(0), thus this is the free parameter
 26:                             u(1) = 0
 27:        the function we wish to minimize is
 28:                             \integral u^{2}

 30:        The exact solution for u is given by u(x) = x*x - 1.25*x + .25

 32:        Use the usual centered finite differences.

 34:        Note we treat the problem as non-linear though it happens to be linear

 36:        See ex21.c for the same code, but that does NOT interlaces the u and the lambda

 38:        The vectors u_lambda and fu_lambda contain the u and the lambda interlaced
 39: */

 41: typedef struct {
 42:   PetscViewer u_lambda_viewer;
 43:   PetscViewer fu_lambda_viewer;
 44: } UserCtx;

 46: extern PetscErrorCode ComputeFunction(SNES,Vec,Vec,void*);
 47: extern PetscErrorCode ComputeJacobian_MF(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
 48: extern PetscErrorCode Monitor(SNES,PetscInt,PetscReal,void*);

 50: /*
 51:     Uses full multigrid preconditioner with GMRES (with no preconditioner inside the GMRES) as the
 52:   smoother on all levels. This is because (1) in the matrix free case no matrix entries are
 53:   available for doing Jacobi or SOR preconditioning and (2) the explicit matrix case the diagonal
 54:   entry for the control variable is zero which means default SOR will not work.

 56: */
 57: char common_options[] = "-ksp_type fgmres\
 58:                          -snes_grid_sequence 4 \
 59:                          -pc_type mg\
 60:                          -mg_levels_pc_type none \
 61:                          -mg_coarse_pc_type none \
 62:                          -pc_mg_type full \
 63:                          -mg_coarse_ksp_type gmres \
 64:                          -mg_levels_ksp_type gmres \
 65:                          -mg_coarse_ksp_max_it 6 \
 66:                          -mg_levels_ksp_max_it 3";

 68: char matrix_free_options[] = "-mat_mffd_compute_normu no \
 69:                               -mat_mffd_type wp";

 71: extern PetscErrorCode DMCreateMatrix_MF(DM,MatType,Mat*);

 75: int main(int argc,char **argv)
 76: {
 78:   UserCtx        user;
 79:   DM             red,da;
 80:   SNES           snes;
 81:   DM             packer;
 82:   PetscBool      use_monitor = PETSC_FALSE;

 84:   PetscInitialize(&argc,&argv,NULL,help);
 85:   PetscOptionsSetFromOptions();

 87:   /* Hardwire several options; can be changed at command line */
 88:   PetscOptionsInsertString(common_options);
 89:   PetscOptionsInsertString(matrix_free_options);
 90:   PetscOptionsInsert(&argc,&argv,NULL);
 91:   PetscOptionsGetBool(NULL,"-use_monitor",&use_monitor,PETSC_IGNORE);

 93:   /* Create a global vector that includes a single redundant array and two da arrays */
 94:   DMCompositeCreate(PETSC_COMM_WORLD,&packer);
 95:   DMRedundantCreate(PETSC_COMM_WORLD,0,1,&red);
 96:   DMSetOptionsPrefix(red,"red_");
 97:   DMCompositeAddDM(packer,red);
 98:   DMDACreate1d(PETSC_COMM_WORLD,DMDA_BOUNDARY_NONE,-5,2,1,NULL,&da);
 99:   DMSetOptionsPrefix(red,"da_");
100:   DMCompositeAddDM(packer,(DM)da);
101:   DMSetApplicationContext(packer,&user);

103:   packer->ops->creatematrix = DMCreateMatrix_MF;

105:   /* create nonlinear multi-level solver */
106:   SNESCreate(PETSC_COMM_WORLD,&snes);
107:   SNESSetDM(snes,packer);
108:   SNESSetFunction(snes,NULL,ComputeFunction,NULL);
109:   SNESSetJacobian(snes,NULL, NULL,ComputeJacobian_MF,NULL);

111:   SNESSetFromOptions(snes);

113:   if (use_monitor) {
114:     /* create graphics windows */
115:     PetscViewerDrawOpen(PETSC_COMM_WORLD,0,"u_lambda - state variables and Lagrange multipliers",-1,-1,-1,-1,&user.u_lambda_viewer);
116:     PetscViewerDrawOpen(PETSC_COMM_WORLD,0,"fu_lambda - derivate w.r.t. state variables and Lagrange multipliers",-1,-1,-1,-1,&user.fu_lambda_viewer);
117:     SNESMonitorSet(snes,Monitor,0,0);
118:   }

120:   SNESSolve(snes,NULL,NULL);
121:   SNESDestroy(&snes);

123:   DMDestroy(&red);
124:   DMDestroy(&da);
125:   DMDestroy(&packer);
126:   if (use_monitor) {
127:     PetscViewerDestroy(&user.u_lambda_viewer);
128:     PetscViewerDestroy(&user.fu_lambda_viewer);
129:   }
130:   PetscFinalize();
131:   return 0;
132: }

134: typedef struct {
135:   PetscScalar u;
136:   PetscScalar lambda;
137: } ULambda;

141: /*
142:       Evaluates FU = Gradiant(L(w,u,lambda))

144:      This local function acts on the ghosted version of U (accessed via DMCompositeGetLocalVectors() and
145:    DMCompositeScatter()) BUT the global, nonghosted version of FU (via DMCompositeGetAccess()).

147: */
148: PetscErrorCode ComputeFunction(SNES snes,Vec U,Vec FU,void *ctx)
149: {
151:   PetscInt       xs,xm,i,N;
152:   ULambda        *u_lambda,*fu_lambda;
153:   PetscScalar    d,h,*w,*fw;
154:   Vec            vw,vfw,vu_lambda,vfu_lambda;
155:   DM             packer,red,da;

158:   VecGetDM(U, &packer);
159:   DMCompositeGetEntries(packer,&red,&da);
160:   DMCompositeGetLocalVectors(packer,&vw,&vu_lambda);
161:   DMCompositeScatter(packer,U,vw,vu_lambda);
162:   DMCompositeGetAccess(packer,FU,&vfw,&vfu_lambda);

164:   DMDAGetCorners(da,&xs,NULL,NULL,&xm,NULL,NULL);
165:   DMDAGetInfo(da,0,&N,0,0,0,0,0,0,0,0,0,0,0);
166:   VecGetArray(vw,&w);
167:   VecGetArray(vfw,&fw);
168:   DMDAVecGetArray(da,vu_lambda,&u_lambda);
169:   DMDAVecGetArray(da,vfu_lambda,&fu_lambda);
170:   d    = N-1.0;
171:   h    = 1.0/d;

173:   /* derivative of L() w.r.t. w */
174:   if (xs == 0) { /* only first processor computes this */
175:     fw[0] = -2.0*d*u_lambda[0].lambda;
176:   }

178:   /* derivative of L() w.r.t. u */
179:   for (i=xs; i<xs+xm; i++) {
180:     if      (i == 0)   fu_lambda[0].lambda   =    h*u_lambda[0].u   + 2.*d*u_lambda[0].lambda   - d*u_lambda[1].lambda;
181:     else if (i == 1)   fu_lambda[1].lambda   = 2.*h*u_lambda[1].u   + 2.*d*u_lambda[1].lambda   - d*u_lambda[2].lambda;
182:     else if (i == N-1) fu_lambda[N-1].lambda =    h*u_lambda[N-1].u + 2.*d*u_lambda[N-1].lambda - d*u_lambda[N-2].lambda;
183:     else if (i == N-2) fu_lambda[N-2].lambda = 2.*h*u_lambda[N-2].u + 2.*d*u_lambda[N-2].lambda - d*u_lambda[N-3].lambda;
184:     else               fu_lambda[i].lambda   = 2.*h*u_lambda[i].u   - d*(u_lambda[i+1].lambda - 2.0*u_lambda[i].lambda + u_lambda[i-1].lambda);
185:   }

187:   /* derivative of L() w.r.t. lambda */
188:   for (i=xs; i<xs+xm; i++) {
189:     if      (i == 0)   fu_lambda[0].u   = 2.0*d*(u_lambda[0].u - w[0]);
190:     else if (i == N-1) fu_lambda[N-1].u = 2.0*d*u_lambda[N-1].u;
191:     else               fu_lambda[i].u   = -(d*(u_lambda[i+1].u - 2.0*u_lambda[i].u + u_lambda[i-1].u) - 2.0*h);
192:   }

194:   VecRestoreArray(vw,&w);
195:   VecRestoreArray(vfw,&fw);
196:   DMDAVecRestoreArray(da,vu_lambda,&u_lambda);
197:   DMDAVecRestoreArray(da,vfu_lambda,&fu_lambda);
198:   DMCompositeRestoreLocalVectors(packer,&vw,&vu_lambda);
199:   DMCompositeRestoreAccess(packer,FU,&vfw,&vfu_lambda);
200:   PetscLogFlops(13.0*N);
201:   return(0);
202: }

206: /*
207:     Computes the exact solution
208: */
209: PetscErrorCode u_solution(void *dummy,PetscInt n,const PetscScalar *x,PetscScalar *u)
210: {
211:   PetscInt i;

214:   for (i=0; i<n; i++) u[2*i] = x[i]*x[i] - 1.25*x[i] + .25;
215:   return(0);
216: }

220: PetscErrorCode ExactSolution(DM packer,Vec U)
221: {
222:   PF             pf;
223:   Vec            x,u_global;
224:   PetscScalar    *w;
225:   DM             da;
227:   PetscInt       m;

230:   DMCompositeGetEntries(packer,&m,&da);

232:   PFCreate(PETSC_COMM_WORLD,1,2,&pf);
233:   PFSetType(pf,PFQUICK,(void*)u_solution);
234:   DMGetCoordinates(da,&x);
235:   if (!x) {
236:     DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,0.0,1.0);
237:     DMGetCoordinates(da,&x);
238:   }
239:   DMCompositeGetAccess(packer,U,&w,&u_global,0);
240:   if (w) w[0] = .25;
241:   PFApplyVec(pf,x,u_global);
242:   PFDestroy(&pf);
243:   DMCompositeRestoreAccess(packer,U,&w,&u_global,0);
244:   return(0);
245: }

249: PetscErrorCode Monitor(SNES snes,PetscInt its,PetscReal rnorm,void *dummy)
250: {
251:   UserCtx        *user;
253:   PetscInt       m,N;
254:   PetscScalar    *w,*dw;
255:   Vec            u_lambda,U,F,Uexact;
256:   DM             packer;
257:   PetscReal      norm;
258:   DM             da;

261:   SNESGetDM(snes,&packer);
262:   DMGetApplicationContext(packer,&user);
263:   SNESGetSolution(snes,&U);
264:   DMCompositeGetAccess(packer,U,&w,&u_lambda);
265:   VecView(u_lambda,user->u_lambda_viewer);
266:   DMCompositeRestoreAccess(packer,U,&w,&u_lambda);

268:   SNESGetFunction(snes,&F,0,0);
269:   DMCompositeGetAccess(packer,F,&w,&u_lambda);
270:   /* VecView(u_lambda,user->fu_lambda_viewer); */
271:   DMCompositeRestoreAccess(packer,U,&w,&u_lambda);

273:   DMCompositeGetEntries(packer,&m,&da);
274:   DMDAGetInfo(da,0,&N,0,0,0,0,0,0,0,0,0,0,0);
275:   VecDuplicate(U,&Uexact);
276:   ExactSolution(packer,Uexact);
277:   VecAXPY(Uexact,-1.0,U);
278:   DMCompositeGetAccess(packer,Uexact,&dw,&u_lambda);
279:   VecStrideNorm(u_lambda,0,NORM_2,&norm);
280:   norm = norm/sqrt(N-1.);
281:   if (dw) PetscPrintf(PETSC_COMM_WORLD,"Norm of error %G Error at x = 0 %G\n",norm,PetscRealPart(dw[0]));
282:   VecView(u_lambda,user->fu_lambda_viewer);
283:   DMCompositeRestoreAccess(packer,Uexact,&dw,&u_lambda);
284:   VecDestroy(&Uexact);
285:   return(0);
286: }

290: PetscErrorCode DMCreateMatrix_MF(DM packer,MatType stype,Mat *A)
291: {
293:   Vec            t;
294:   PetscInt       m;

297:   DMGetGlobalVector(packer,&t);
298:   VecGetLocalSize(t,&m);
299:   DMRestoreGlobalVector(packer,&t);
300:   MatCreateMFFD(PETSC_COMM_WORLD,m,m,PETSC_DETERMINE,PETSC_DETERMINE,A);
301:   MatSetUp(*A);
302:   return(0);
303: }

307: PetscErrorCode ComputeJacobian_MF(SNES snes,Vec x,Mat *A,Mat *B,MatStructure *str,void *ctx)
308: {

312:   MatMFFDSetFunction(*A,(PetscErrorCode (*)(void*,Vec,Vec))SNESComputeFunction,snes);
313:   MatMFFDSetBase(*A,x,NULL);
314:   return(0);
315: }