Actual source code: ex49.c
petsc-3.6.1 2015-08-06
2: static char help[] = "Tests MatTranspose(), MatNorm(), and MatAXPY().\n\n";
4: #include <petscmat.h>
8: int main(int argc,char **argv)
9: {
10: Mat mat,tmat = 0;
11: PetscInt m = 4,n,i,j;
13: PetscMPIInt size,rank;
14: PetscInt rstart,rend,rect = 0;
15: PetscBool flg;
16: PetscScalar v;
17: PetscReal normf,normi,norm1;
18: MatInfo info;
20: PetscInitialize(&argc,&argv,(char*)0,help);
21: PetscOptionsGetInt(NULL,"-m",&m,NULL);
22: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
23: MPI_Comm_size(PETSC_COMM_WORLD,&size);
24: n = m;
25: PetscOptionsHasName(NULL,"-rect1",&flg);
26: if (flg) {n += 2; rect = 1;}
27: PetscOptionsHasName(NULL,"-rect2",&flg);
28: if (flg) {n -= 2; rect = 1;}
30: /* Create and assemble matrix */
31: MatCreate(PETSC_COMM_WORLD,&mat);
32: MatSetSizes(mat,PETSC_DECIDE,PETSC_DECIDE,m,n);
33: MatSetFromOptions(mat);
34: MatGetOwnershipRange(mat,&rstart,&rend);
35: for (i=rstart; i<rend; i++) {
36: for (j=0; j<n; j++) {
37: v = 10*i+j;
38: MatSetValues(mat,1,&i,1,&j,&v,INSERT_VALUES);
39: }
40: }
41: MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
42: MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
44: /* Print info about original matrix */
45: MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
46: PetscPrintf(PETSC_COMM_WORLD,"original matrix nonzeros = %D, allocated nonzeros = %D\n",
47: (PetscInt)info.nz_used,(PetscInt)info.nz_allocated);
48: MatNorm(mat,NORM_FROBENIUS,&normf);
49: MatNorm(mat,NORM_1,&norm1);
50: MatNorm(mat,NORM_INFINITY,&normi);
51: PetscPrintf(PETSC_COMM_WORLD,"original: Frobenious norm = %g, one norm = %g, infinity norm = %g\n",(double)normf,(double)norm1,(double)normi);
52: MatView(mat,PETSC_VIEWER_STDOUT_WORLD);
54: /* Form matrix transpose */
55: PetscOptionsHasName(NULL,"-in_place",&flg);
56: if (!rect && flg) {
57: MatTranspose(mat,MAT_REUSE_MATRIX,&mat); /* in-place transpose */
58: tmat = mat; mat = 0;
59: } else { /* out-of-place transpose */
60: MatTranspose(mat,MAT_INITIAL_MATRIX,&tmat);
61: }
63: /* Print info about transpose matrix */
64: MatGetInfo(tmat,MAT_GLOBAL_SUM,&info);
65: PetscPrintf(PETSC_COMM_WORLD,"transpose matrix nonzeros = %D, allocated nonzeros = %D\n",
66: (PetscInt)info.nz_used,(PetscInt)info.nz_allocated);
67: MatNorm(tmat,NORM_FROBENIUS,&normf);
68: MatNorm(tmat,NORM_1,&norm1);
69: MatNorm(tmat,NORM_INFINITY,&normi);
70: PetscPrintf(PETSC_COMM_WORLD,"transpose: Frobenious norm = %g, one norm = %g, infinity norm = %g\n",(double)normf,(double)norm1,(double)normi);
71: MatView(tmat,PETSC_VIEWER_STDOUT_WORLD);
74: /* Test MatAXPY */
75: if (mat && !rect) {
76: PetscScalar alpha = 1.0;
77: PetscOptionsGetScalar(NULL,"-alpha",&alpha,NULL);
78: PetscPrintf(PETSC_COMM_WORLD,"matrix addition: B = B + alpha * A\n");
79: MatAXPY(tmat,alpha,mat,DIFFERENT_NONZERO_PATTERN);
80: MatView(tmat,PETSC_VIEWER_STDOUT_WORLD);
81: }
83: /* Free data structures */
84: MatDestroy(&tmat);
85: if (mat) {MatDestroy(&mat);}
87: PetscFinalize();
88: return 0;
89: }