Actual source code: ex40.c

slepc-3.18.3 2023-03-24
Report Typos and Errors
  1: /*
  2:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  3:    SLEPc - Scalable Library for Eigenvalue Problem Computations
  4:    Copyright (c) 2002-, Universitat Politecnica de Valencia, Spain

  6:    This file is part of SLEPc.
  7:    SLEPc is distributed under a 2-clause BSD license (see LICENSE).
  8:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  9: */

 11: static char help[] = "Checking the definite property in quadratic symmetric eigenproblem.\n\n"
 12:   "The command line options are:\n"
 13:   "  -n <n> ... dimension of the matrices.\n"
 14:   "  -transform... whether to transform to a hyperbolic problem or not.\n"
 15:   "  -nonhyperbolic... to test with a modified (definite) problem that is not hyperbolic.\n\n";

 17: #include <slepcpep.h>

 19: /*
 20:   This example is based on spring.c, for fixed values mu=1,tau=10,kappa=5

 22:   The transformations are based on the method proposed in [Niendorf and Voss, LAA 2010].
 23: */

 25: PetscErrorCode QEPDefiniteTransformGetMatrices(PEP,PetscBool,PetscReal,PetscReal,Mat[3]);
 26: PetscErrorCode QEPDefiniteTransformMap(PetscBool,PetscReal,PetscReal,PetscInt,PetscScalar*,PetscBool);
 27: PetscErrorCode QEPDefiniteCheckError(Mat*,PEP,PetscBool,PetscReal,PetscReal);
 28: PetscErrorCode TransformMatricesMoebius(Mat[3],MatStructure,PetscReal,PetscReal,PetscReal,PetscReal,Mat[3]);

 30: int main(int argc,char **argv)
 31: {
 32:   Mat            M,C,K,*Op,A[3],At[3],B[3]; /* problem matrices */
 33:   PEP            pep;        /* polynomial eigenproblem solver context */
 34:   ST             st;         /* spectral transformation context */
 35:   KSP            ksp;
 36:   PC             pc;
 37:   PEPProblemType type;
 38:   PetscBool      terse,transform=PETSC_FALSE,nohyp=PETSC_FALSE;
 39:   PetscInt       n=100,Istart,Iend,i,def=0,hyp;
 40:   PetscReal      muu=1,tau=10,kappa=5,inta,intb;
 41:   PetscReal      alpha,beta,xi,mu,at[2]={0.0,0.0},c=.857,s;
 42:   PetscScalar    target,targett,ats[2];

 45:   SlepcInitialize(&argc,&argv,(char*)0,help);

 47:   PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL);
 48:   PetscPrintf(PETSC_COMM_WORLD,"\nPEP example that checks definite property, n=%" PetscInt_FMT "\n\n",n);

 50:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 51:      Compute the matrices that define the eigensystem, (k^2*M+k*C+K)x=0
 52:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 54:   /* K is a tridiagonal */
 55:   MatCreate(PETSC_COMM_WORLD,&K);
 56:   MatSetSizes(K,PETSC_DECIDE,PETSC_DECIDE,n,n);
 57:   MatSetFromOptions(K);
 58:   MatSetUp(K);

 60:   MatGetOwnershipRange(K,&Istart,&Iend);
 61:   for (i=Istart;i<Iend;i++) {
 62:     if (i>0) MatSetValue(K,i,i-1,-kappa,INSERT_VALUES);
 63:     MatSetValue(K,i,i,kappa*3.0,INSERT_VALUES);
 64:     if (i<n-1) MatSetValue(K,i,i+1,-kappa,INSERT_VALUES);
 65:   }

 67:   MatAssemblyBegin(K,MAT_FINAL_ASSEMBLY);
 68:   MatAssemblyEnd(K,MAT_FINAL_ASSEMBLY);

 70:   /* C is a tridiagonal */
 71:   MatCreate(PETSC_COMM_WORLD,&C);
 72:   MatSetSizes(C,PETSC_DECIDE,PETSC_DECIDE,n,n);
 73:   MatSetFromOptions(C);
 74:   MatSetUp(C);

 76:   MatGetOwnershipRange(C,&Istart,&Iend);
 77:   for (i=Istart;i<Iend;i++) {
 78:     if (i>0) MatSetValue(C,i,i-1,-tau,INSERT_VALUES);
 79:     MatSetValue(C,i,i,tau*3.0,INSERT_VALUES);
 80:     if (i<n-1) MatSetValue(C,i,i+1,-tau,INSERT_VALUES);
 81:   }

 83:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
 84:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

 86:   /* M is a diagonal matrix */
 87:   MatCreate(PETSC_COMM_WORLD,&M);
 88:   MatSetSizes(M,PETSC_DECIDE,PETSC_DECIDE,n,n);
 89:   MatSetFromOptions(M);
 90:   MatSetUp(M);
 91:   MatGetOwnershipRange(M,&Istart,&Iend);
 92:   for (i=Istart;i<Iend;i++) MatSetValue(M,i,i,muu,INSERT_VALUES);
 93:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
 94:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);

 96:   PetscOptionsGetBool(NULL,NULL,"-nonhyperbolic",&nohyp,NULL);
 97:   A[0] = K; A[1] = C; A[2] = M;
 98:   if (nohyp) {
 99:     s = c*.6;
100:     TransformMatricesMoebius(A,UNKNOWN_NONZERO_PATTERN,c,s,-s,c,At);
101:     for (i=0;i<3;i++) MatDestroy(&A[i]);
102:     Op = At;
103:   } else Op = A;

105:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
106:                 Create the eigensolver and solve the problem
107:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

109:   /*
110:      Create eigensolver context
111:   */
112:   PEPCreate(PETSC_COMM_WORLD,&pep);
113:   PEPSetProblemType(pep,PEP_HERMITIAN);
114:   PEPSetType(pep,PEPSTOAR);
115:   /*
116:      Set operators and set problem type
117:   */
118:   PEPSetOperators(pep,3,Op);

120:   /*
121:      Set shift-and-invert with Cholesky; select MUMPS if available
122:   */
123:   PEPGetST(pep,&st);
124:   STGetKSP(st,&ksp);
125:   KSPSetType(ksp,KSPPREONLY);
126:   KSPGetPC(ksp,&pc);
127:   PCSetType(pc,PCCHOLESKY);

129:   /*
130:      Use MUMPS if available.
131:      Note that in complex scalars we cannot use MUMPS for spectrum slicing,
132:      because MatGetInertia() is not available in that case.
133:   */
134: #if defined(PETSC_HAVE_MUMPS) && !defined(PETSC_USE_COMPLEX)
135:   PCFactorSetMatSolverType(pc,MATSOLVERMUMPS);
136:   /*
137:      Add several MUMPS options (see ex43.c for a better way of setting them in program):
138:      '-st_mat_mumps_icntl_13 1': turn off ScaLAPACK for matrix inertia
139:   */
140:   PetscOptionsInsertString(NULL,"-st_mat_mumps_icntl_13 1 -st_mat_mumps_icntl_24 1 -st_mat_mumps_cntl_3 1e-12");
141: #endif

143:   /*
144:      Set solver parameters at runtime
145:   */
146:   PEPSetFromOptions(pep);

148:   PetscOptionsGetBool(NULL,NULL,"-transform",&transform,NULL);
149:   if (transform) {
150:     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
151:                     Check if the problem is definite
152:        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
153:     PEPCheckDefiniteQEP(pep,&xi,&mu,&def,&hyp);
154:     switch (def) {
155:       case 1:
156:         if (hyp==1) PetscPrintf(PETSC_COMM_WORLD,"Hyperbolic Problem xi=%g\n",(double)xi);
157:         else PetscPrintf(PETSC_COMM_WORLD,"Definite Problem xi=%g mu=%g\n",(double)xi,(double)mu);
158:         break;
159:       case -1:
160:         PetscPrintf(PETSC_COMM_WORLD,"Not Definite Problem\n");
161:         break;
162:       default:
163:         PetscPrintf(PETSC_COMM_WORLD,"Cannot determine definiteness\n");
164:         break;
165:     }

167:     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
168:       Transform the QEP to have a definite inner product in the linearization
169:        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
170:     if (def==1) {
171:       QEPDefiniteTransformGetMatrices(pep,hyp==1?PETSC_TRUE:PETSC_FALSE,xi,mu,B);
172:       PEPSetOperators(pep,3,B);
173:       PEPGetTarget(pep,&target);
174:       targett = target;
175:       QEPDefiniteTransformMap(hyp==1?PETSC_TRUE:PETSC_FALSE,xi,mu,1,&targett,PETSC_FALSE);
176:       PEPSetTarget(pep,targett);
177:       PEPGetProblemType(pep,&type);
178:       PEPSetProblemType(pep,PEP_HYPERBOLIC);
179:       PEPSTOARGetLinearization(pep,&alpha,&beta);
180:       PEPSTOARSetLinearization(pep,1.0,0.0);
181:       PEPGetInterval(pep,&inta,&intb);
182:       if (inta!=intb) {
183:         ats[0] = inta; ats[1] = intb;
184:         QEPDefiniteTransformMap(hyp==1?PETSC_TRUE:PETSC_FALSE,xi,mu,2,ats,PETSC_FALSE);
185:         at[0] = PetscRealPart(ats[0]); at[1] = PetscRealPart(ats[1]);
186:         if (at[0]<at[1]) PEPSetInterval(pep,at[0],at[1]);
187:         else PEPSetInterval(pep,PETSC_MIN_REAL,at[1]);
188:       }
189:     }
190:   }

192:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
193:                       Solve the eigensystem
194:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
195:   PEPSolve(pep);

197:   /* show detailed info unless -terse option is given by user */
198:   if (def!=1) {
199:     PetscOptionsHasName(NULL,NULL,"-terse",&terse);
200:     if (terse) PEPErrorView(pep,PEP_ERROR_BACKWARD,NULL);
201:     else {
202:       PetscViewerPushFormat(PETSC_VIEWER_STDOUT_WORLD,PETSC_VIEWER_ASCII_INFO_DETAIL);
203:       PEPConvergedReasonView(pep,PETSC_VIEWER_STDOUT_WORLD);
204:       PEPErrorView(pep,PEP_ERROR_RELATIVE,PETSC_VIEWER_STDOUT_WORLD);
205:       PetscViewerPopFormat(PETSC_VIEWER_STDOUT_WORLD);
206:     }
207:   } else {
208:     /* Map the solution */
209:     PEPConvergedReasonView(pep,PETSC_VIEWER_STDOUT_WORLD);
210:     QEPDefiniteCheckError(Op,pep,hyp==1?PETSC_TRUE:PETSC_FALSE,xi,mu);
211:     for (i=0;i<3;i++) MatDestroy(B+i);
212:   }
213:   if (at[0]>at[1]) {
214:     PEPSetInterval(pep,at[0],PETSC_MAX_REAL);
215:     PEPSolve(pep);
216:     PEPConvergedReasonView(pep,PETSC_VIEWER_STDOUT_WORLD);
217:     /* Map the solution */
218:     QEPDefiniteCheckError(Op,pep,hyp==1?PETSC_TRUE:PETSC_FALSE,xi,mu);
219:   }
220:   if (def==1) {
221:     PEPSetTarget(pep,target);
222:     PEPSetProblemType(pep,type);
223:     PEPSTOARSetLinearization(pep,alpha,beta);
224:     if (inta!=intb) PEPSetInterval(pep,inta,intb);
225:   }

227:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
228:                     Clean up
229:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
230:   PEPDestroy(&pep);
231:   for (i=0;i<3;i++) MatDestroy(Op+i);
232:   SlepcFinalize();
233:   return 0;
234: }

236: /* ------------------------------------------------------------------- */
237: /*
238:   QEPDefiniteTransformMap_Initial - map a scalar value with a certain Moebius transform

240:                    a theta + b
241:          lambda = --------------
242:                    c theta + d

244:   Input:
245:     xi,mu: real values such that Q(xi)<0 and Q(mu)>0
246:     hyperbolic: if true the problem is assumed hyperbolic (mu is not used)
247:   Input/Output:
248:     val (array of length n)
249:     if backtransform=true returns lambda from theta, else returns theta from lambda
250: */
251: static PetscErrorCode QEPDefiniteTransformMap_Initial(PetscBool hyperbolic,PetscReal xi,PetscReal mu,PetscInt n,PetscScalar *val,PetscBool backtransform)
252: {
253:   PetscInt  i;
254:   PetscReal a,b,c,d,s;

256:   if (hyperbolic) { a = 1.0; b = xi; c =0.0; d = 1.0; }
257:   else { a = mu; b = mu*xi-1; c = 1.0; d = xi+mu; }
258:   if (!backtransform) { s = a; a = -d; d = -s; }
259:   for (i=0;i<n;i++) {
260:     if (PetscRealPart(val[i]) >= PETSC_MAX_REAL || PetscRealPart(val[i]) <= PETSC_MIN_REAL) val[i] = a/c;
261:     else if (val[i] == -d/c) val[i] = PETSC_MAX_REAL;
262:     else val[i] = (a*val[i]+b)/(c*val[i]+d);
263:   }
264:   return 0;
265: }

267: /* ------------------------------------------------------------------- */
268: /*
269:   QEPDefiniteTransformMap - perform the mapping if the problem is hyperbolic, otherwise
270:   modify the value of xi in advance
271: */
272: PetscErrorCode QEPDefiniteTransformMap(PetscBool hyperbolic,PetscReal xi,PetscReal mu,PetscInt n,PetscScalar *val,PetscBool backtransform)
273: {
274:   PetscReal      xit;
275:   PetscScalar    alpha;

277:   xit = xi;
278:   if (!hyperbolic) {
279:     alpha = xi;
280:     QEPDefiniteTransformMap_Initial(PETSC_FALSE,0.0,mu,1,&alpha,PETSC_FALSE);
281:     xit = PetscRealPart(alpha);
282:   }
283:   QEPDefiniteTransformMap_Initial(hyperbolic,xit,mu,n,val,backtransform);
284:   return 0;
285: }

287: /* ------------------------------------------------------------------- */
288: /*
289:   TransformMatricesMoebius - transform the coefficient matrices of a QEP

291:   Input:
292:     A: coefficient matrices of the original QEP
293:     a,b,c,d: parameters of the Moebius transform
294:     str: structure flag for MatAXPY operations
295:   Output:
296:     B: transformed matrices
297: */
298: PetscErrorCode TransformMatricesMoebius(Mat A[3],MatStructure str,PetscReal a,PetscReal b,PetscReal c,PetscReal d,Mat B[3])
299: {
300:   PetscInt       i,k;
301:   PetscReal      cf[9];

303:   for (i=0;i<3;i++) MatDuplicate(A[2],MAT_COPY_VALUES,&B[i]);
304:   /* Ct = b*b*A+b*d*B+d*d*C */
305:   cf[0] = d*d; cf[1] = b*d; cf[2] = b*b;
306:   /* Bt = 2*a*b*A+(b*c+a*d)*B+2*c*d*C*/
307:   cf[3] = 2*c*d; cf[4] = b*c+a*d; cf[5] = 2*a*b;
308:   /* At = a*a*A+a*c*B+c*c*C */
309:   cf[6] = c*c; cf[7] = a*c; cf[8] = a*a;
310:   for (k=0;k<3;k++) {
311:     MatScale(B[k],cf[k*3+2]);
312:     for (i=0;i<2;i++) MatAXPY(B[k],cf[3*k+i],A[i],str);
313:   }
314:   return 0;
315: }

317: /* ------------------------------------------------------------------- */
318: /*
319:   QEPDefiniteTransformGetMatrices - given a PEP of degree 2, transform the three
320:   matrices with TransformMatricesMoebius

322:   Input:
323:     pep: polynomial eigenproblem to be transformed, with Q(.) being the quadratic polynomial
324:     xi,mu: real values such that Q(xi)<0 and Q(mu)>0
325:     hyperbolic: if true the problem is assumed hyperbolic (mu is not used)
326:   Output:
327:     T: coefficient matrices of the transformed polynomial
328: */
329: PetscErrorCode QEPDefiniteTransformGetMatrices(PEP pep,PetscBool hyperbolic,PetscReal xi,PetscReal mu,Mat T[3])
330: {
331:   MatStructure   str;
332:   ST             st;
333:   PetscInt       i;
334:   PetscReal      a,b,c,d;
335:   PetscScalar    xit;
336:   Mat            A[3];

338:   for (i=2;i>=0;i--) PEPGetOperators(pep,i,&A[i]);
339:   if (hyperbolic) { a = 1.0; b = xi; c =0.0; d = 1.0; }
340:   else {
341:     xit = xi;
342:     QEPDefiniteTransformMap_Initial(PETSC_FALSE,0.0,mu,1,&xit,PETSC_FALSE);
343:     a = mu; b = mu*PetscRealPart(xit)-1.0; c = 1.0; d = PetscRealPart(xit)+mu;
344:   }
345:   PEPGetST(pep,&st);
346:   STGetMatStructure(st,&str);
347:   TransformMatricesMoebius(A,str,a,b,c,d,T);
348:   return 0;
349: }

351: /* ------------------------------------------------------------------- */
352: /*
353:   Auxiliary function to compute the residual norm of an eigenpair of a QEP defined
354:   by coefficient matrices A
355: */
356: static PetscErrorCode PEPResidualNorm(Mat *A,PetscScalar kr,PetscScalar ki,Vec xr,Vec xi,Vec *z,PetscReal *norm)
357: {
358:   PetscInt       i,nmat=3;
359:   PetscScalar    vals[3];
360:   Vec            u,w;
361: #if !defined(PETSC_USE_COMPLEX)
362:   Vec            ui,wi;
363:   PetscReal      ni;
364:   PetscBool      imag;
365:   PetscScalar    ivals[3];
366: #endif

368:   u = z[0]; w = z[1];
369:   VecSet(u,0.0);
370: #if !defined(PETSC_USE_COMPLEX)
371:   ui = z[2]; wi = z[3];
372: #endif
373:   vals[0] = 1.0;
374:   vals[1] = kr;
375:   vals[2] = kr*kr-ki*ki;
376: #if !defined(PETSC_USE_COMPLEX)
377:   ivals[0] = 0.0;
378:   ivals[1] = ki;
379:   ivals[2] = 2.0*kr*ki;
380:   if (ki == 0 || PetscAbsScalar(ki) < PetscAbsScalar(kr*PETSC_MACHINE_EPSILON))
381:     imag = PETSC_FALSE;
382:   else {
383:     imag = PETSC_TRUE;
384:     VecSet(ui,0.0);
385:   }
386: #endif
387:   for (i=0;i<nmat;i++) {
388:     if (vals[i]!=0.0) {
389:       MatMult(A[i],xr,w);
390:       VecAXPY(u,vals[i],w);
391:     }
392: #if !defined(PETSC_USE_COMPLEX)
393:     if (imag) {
394:       if (ivals[i]!=0 || vals[i]!=0) {
395:         MatMult(A[i],xi,wi);
396:         if (vals[i]==0) MatMult(A[i],xr,w);
397:       }
398:       if (ivals[i]!=0) {
399:         VecAXPY(u,-ivals[i],wi);
400:         VecAXPY(ui,ivals[i],w);
401:       }
402:       if (vals[i]!=0) VecAXPY(ui,vals[i],wi);
403:     }
404: #endif
405:   }
406:   VecNorm(u,NORM_2,norm);
407: #if !defined(PETSC_USE_COMPLEX)
408:   if (imag) {
409:     VecNorm(ui,NORM_2,&ni);
410:     *norm = SlepcAbsEigenvalue(*norm,ni);
411:   }
412: #endif
413:   return 0;
414: }

416: /* ------------------------------------------------------------------- */
417: /*
418:   QEPDefiniteCheckError - check and print the residual norm of a transformed PEP

420:   Input:
421:     A: coefficient matrices of the original problem
422:     pep: solver containing the computed solution of the transformed problem
423:     xi,mu,hyperbolic: parameters used in transformation
424: */
425: PetscErrorCode QEPDefiniteCheckError(Mat *A,PEP pep,PetscBool hyperbolic,PetscReal xi,PetscReal mu)
426: {
427:   PetscScalar    er,ei;
428:   PetscReal      re,im,error;
429:   Vec            vr,vi,w[4];
430:   PetscInt       i,nconv;
431:   BV             bv;
432:   char           ex[30],sep[]=" ---------------------- --------------------\n";

434:   PetscSNPrintf(ex,sizeof(ex),"||P(k)x||/||kx||");
435:   PetscPrintf(PETSC_COMM_WORLD,"%s            k             %s\n%s",sep,ex,sep);
436:   PEPGetConverged(pep,&nconv);
437:   PEPGetBV(pep,&bv);
438:   BVCreateVec(bv,w);
439:   VecDuplicate(w[0],&vr);
440:   VecDuplicate(w[0],&vi);
441:   for (i=1;i<4;i++) VecDuplicate(w[0],w+i);
442:   for (i=0;i<nconv;i++) {
443:     PEPGetEigenpair(pep,i,&er,&ei,vr,vi);
444:     QEPDefiniteTransformMap(hyperbolic,xi,mu,1,&er,PETSC_TRUE);
445:     PEPResidualNorm(A,er,0.0,vr,vi,w,&error);
446:     error /= SlepcAbsEigenvalue(er,0.0);
447: #if defined(PETSC_USE_COMPLEX)
448:     re = PetscRealPart(er);
449:     im = PetscImaginaryPart(ei);
450: #else
451:     re = er;
452:     im = ei;
453: #endif
454:     if (im!=0.0) PetscPrintf(PETSC_COMM_WORLD,"  % 9f%+9fi      %12g\n",(double)re,(double)im,(double)error);
455:     else PetscPrintf(PETSC_COMM_WORLD,"    % 12f           %12g\n",(double)re,(double)error);
456:   }
457:   PetscPrintf(PETSC_COMM_WORLD,"%s",sep);
458:   for (i=0;i<4;i++) VecDestroy(w+i);
459:   VecDestroy(&vi);
460:   VecDestroy(&vr);
461:   return 0;
462: }

464: /*TEST

466:    testset:
467:       requires: !single
468:       args: -pep_nev 3 -nonhyperbolic -pep_target 2
469:       output_file: output/ex40_1.out
470:       filter: grep -v "Definite" | sed -e "s/iterations [0-9]\([0-9]*\)/iterations xx/g" | sed -e "s/[0-9]\.[0-9]*e[+-]\([0-9]*\)/removed/g"
471:       test:
472:          suffix: 1
473:          requires: !complex
474:       test:
475:          suffix: 1_complex
476:          requires: complex !mumps
477:       test:
478:          suffix: 1_transform
479:          requires: !complex
480:          args: -transform
481:       test:
482:          suffix: 1_transform_complex
483:          requires: complex !mumps
484:          args: -transform

486: TEST*/