Actual source code: ex15.c
1: /*$Id: ex15.c,v 1.28 2001/08/07 21:30:50 bsmith Exp $*/
3: static char help[] = "KSP on an operator with a null space.\n\n";
5: #include petscksp.h
9: int main(int argc,char **args)
10: {
11: Vec x,b,u; /* approx solution, RHS, exact solution */
12: Mat A; /* linear system matrix */
13: KSP ksp; /* KSP context */
14: int ierr,i,n = 10,col[3],its,i1,i2;
15: PetscScalar none = -1.0,value[3],avalue;
16: PetscReal norm;
17: PC pc;
19: PetscInitialize(&argc,&args,(char *)0,help);
20: PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);
22: /* Create vectors */
23: VecCreate(PETSC_COMM_WORLD,&x);
24: VecSetSizes(x,PETSC_DECIDE,n);
25: VecSetFromOptions(x);
26: VecDuplicate(x,&b);
27: VecDuplicate(x,&u);
29: /* create a solution that is orthogonal to the constants */
30: VecGetOwnershipRange(u,&i1,&i2);
31: for (i=i1; i<i2; i++) {
32: avalue = i;
33: VecSetValues(u,1,&i,&avalue,INSERT_VALUES);
34: }
35: VecAssemblyBegin(u);
36: VecAssemblyEnd(u);
37: VecSum(u,&avalue);
38: avalue = -avalue/(PetscReal)n;
39: VecShift(&avalue,u);
41: /* Create and assemble matrix */
42: MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,n,n,&A);
43: MatSetFromOptions(A);
44: value[0] = -1.0; value[1] = 2.0; value[2] = -1.0;
45: for (i=1; i<n-1; i++) {
46: col[0] = i-1; col[1] = i; col[2] = i+1;
47: MatSetValues(A,1,&i,3,col,value,INSERT_VALUES);
48: }
49: i = n - 1; col[0] = n - 2; col[1] = n - 1; value[1] = 1.0;
50: MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
51: i = 0; col[0] = 0; col[1] = 1; value[0] = 1.0; value[1] = -1.0;
52: MatSetValues(A,1,&i,2,col,value,INSERT_VALUES);
53: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
54: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
55: MatMult(A,u,b);
57: /* Create KSP context; set operators and options; solve linear system */
58: KSPCreate(PETSC_COMM_WORLD,&ksp);
59: KSPSetOperators(ksp,A,A,DIFFERENT_NONZERO_PATTERN);
61: /* Insure that preconditioner has same null space as matrix */
62: /* currently does not do anything */
63: KSPGetPC(ksp,&pc);
65: KSPSetFromOptions(ksp);
66: KSPSetRhs(ksp,b);
67: KSPSetSolution(ksp,x);
68: KSPSolve(ksp);
69: /* KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD); */
71: /* Check error */
72: VecAXPY(&none,u,x);
73: VecNorm(x,NORM_2,&norm);
74: KSPGetIterationNumber(ksp,&its);
75: PetscPrintf(PETSC_COMM_WORLD,"Norm of error %A, Iterations %d\n",norm,its);
77: /* Free work space */
78: VecDestroy(x);VecDestroy(u);
79: VecDestroy(b);MatDestroy(A);
80: KSPDestroy(ksp);
81: PetscFinalize();
82: return 0;
83: }