xref: /petsc/src/mat/tests/ex148.c (revision ebead697dbf761eb322f829370bbe90b3bd93fa3)
1 static char help[]="This program illustrates the use of PETSc-fftw interface for real 2D DFT.\n\
2                     See ~petsc/src/mat/tests/ex158.c for general cases. \n\n";
3 
4 #include <petscmat.h>
5 
6 int main(int argc,char **args)
7 {
8   PetscMPIInt    rank,size;
9   PetscInt       N0=50,N1=50,N=N0*N1;
10   PetscRandom    rdm;
11   PetscReal      enorm;
12   Vec            x,y,z,input,output;
13   Mat            A;
14   PetscInt       DIM,dim[2];
15   PetscReal      fac;
16 
17   PetscFunctionBeginUser;
18   PetscCall(PetscInitialize(&argc,&args,(char*)0,help));
19 #if defined(PETSC_USE_COMPLEX)
20   SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP, "This example requires real numbers");
21 #endif
22 
23   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
24   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
25 
26   /* Create and set PETSc vectors 'input' and 'output' */
27   PetscCall(PetscRandomCreate(PETSC_COMM_WORLD, &rdm));
28   PetscCall(PetscRandomSetFromOptions(rdm));
29 
30   PetscCall(VecCreate(PETSC_COMM_WORLD,&input));
31   PetscCall(VecSetSizes(input,PETSC_DECIDE,N0*N1));
32   PetscCall(VecSetFromOptions(input));
33   PetscCall(VecSetRandom(input,rdm));
34   PetscCall(VecDuplicate(input,&output));
35   PetscCall(PetscObjectSetName((PetscObject)input, "Real space vector"));
36   PetscCall(PetscObjectSetName((PetscObject)output, "Reconstructed vector"));
37 
38   /* Get FFTW vectors 'x', 'y' and 'z' */
39   DIM    = 2;
40   dim[0] = N0; dim[1] = N1;
41   PetscCall(MatCreateFFT(PETSC_COMM_WORLD,DIM,dim,MATFFTW,&A));
42   PetscCall(MatCreateVecsFFTW(A,&x,&y,&z));
43 
44   /* Scatter PETSc vector 'input' to FFTW vector 'x' */
45   PetscCall(VecScatterPetscToFFTW(A,input,x));
46 
47   /* Apply forward FFT */
48   PetscCall(MatMult(A,x,y));
49 
50   /* Apply backward FFT */
51   PetscCall(MatMultTranspose(A,y,z));
52 
53   /* Scatter FFTW vector 'z' to PETSc vector 'output' */
54   PetscCall(VecScatterFFTWToPetsc(A,z,output));
55 
56   /* Check accuracy */
57   fac  = 1.0/(PetscReal)N;
58   PetscCall(VecScale(output,fac));
59   PetscCall(VecAXPY(output,-1.0,input));
60   PetscCall(VecNorm(output,NORM_1,&enorm));
61   if (enorm > 1.e-11 && rank == 0) {
62     PetscCall(PetscPrintf(PETSC_COMM_SELF,"  Error norm of |x - z| %e\n",enorm));
63   }
64 
65   /* Free spaces */
66   PetscCall(PetscRandomDestroy(&rdm));
67   PetscCall(VecDestroy(&input));
68   PetscCall(VecDestroy(&output));
69   PetscCall(VecDestroy(&x));
70   PetscCall(VecDestroy(&y));
71   PetscCall(VecDestroy(&z));
72   PetscCall(MatDestroy(&A));
73 
74   PetscCall(PetscFinalize());
75   return 0;
76 }
77 
78 /*TEST
79 
80    build:
81       requires: fftw !complex
82 
83    test:
84       output_file: output/ex148.out
85 
86    test:
87       suffix: 2
88       nsize: 3
89       output_file: output/ex148.out
90 
91 TEST*/
92