xref: /petsc/src/mat/tests/ex148.c (revision 58d68138c660dfb4e9f5b03334792cd4f2ffd7cc)
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   PetscMPIInt rank, size;
8   PetscInt    N0 = 50, N1 = 50, N = N0 * N1;
9   PetscRandom rdm;
10   PetscReal   enorm;
11   Vec         x, y, z, input, output;
12   Mat         A;
13   PetscInt    DIM, dim[2];
14   PetscReal   fac;
15 
16   PetscFunctionBeginUser;
17   PetscCall(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   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
23   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
24 
25   /* Create and set PETSc vectors 'input' and 'output' */
26   PetscCall(PetscRandomCreate(PETSC_COMM_WORLD, &rdm));
27   PetscCall(PetscRandomSetFromOptions(rdm));
28 
29   PetscCall(VecCreate(PETSC_COMM_WORLD, &input));
30   PetscCall(VecSetSizes(input, PETSC_DECIDE, N0 * N1));
31   PetscCall(VecSetFromOptions(input));
32   PetscCall(VecSetRandom(input, rdm));
33   PetscCall(VecDuplicate(input, &output));
34   PetscCall(PetscObjectSetName((PetscObject)input, "Real space vector"));
35   PetscCall(PetscObjectSetName((PetscObject)output, "Reconstructed vector"));
36 
37   /* Get FFTW vectors 'x', 'y' and 'z' */
38   DIM    = 2;
39   dim[0] = N0;
40   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) { PetscCall(PetscPrintf(PETSC_COMM_SELF, "  Error norm of |x - z| %e\n", enorm)); }
62 
63   /* Free spaces */
64   PetscCall(PetscRandomDestroy(&rdm));
65   PetscCall(VecDestroy(&input));
66   PetscCall(VecDestroy(&output));
67   PetscCall(VecDestroy(&x));
68   PetscCall(VecDestroy(&y));
69   PetscCall(VecDestroy(&z));
70   PetscCall(MatDestroy(&A));
71 
72   PetscCall(PetscFinalize());
73   return 0;
74 }
75 
76 /*TEST
77 
78    build:
79       requires: fftw !complex
80 
81    test:
82       output_file: output/ex148.out
83 
84    test:
85       suffix: 2
86       nsize: 3
87       output_file: output/ex148.out
88 
89 TEST*/
90