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