xref: /petsc/src/dm/tests/ex12.c (revision b122ec5aa1bd4469eb4e0673542fb7de3f411254)
1 
2 /*
3    Simple example to show how PETSc programs can be run from MATLAB.
4   See ex12.m.
5 */
6 
7 static char help[] = "Solves the one dimensional heat equation.\n\n";
8 
9 #include <petscdm.h>
10 #include <petscdmda.h>
11 
12 int main(int argc,char **argv)
13 {
14   PetscMPIInt    rank,size;
15   PetscInt       M = 14,time_steps = 20,w=1,s=1,localsize,j,i,mybase,myend,globalsize;
16   DM             da;
17   Vec            global,local;
18   PetscScalar    *globalptr,*localptr;
19   PetscReal      h,k;
20 
21   CHKERRQ(PetscInitialize(&argc,&argv,(char*)0,help));
22   CHKERRQ(PetscOptionsGetInt(NULL,NULL,"-M",&M,NULL));
23   CHKERRQ(PetscOptionsGetInt(NULL,NULL,"-time",&time_steps,NULL));
24 
25   /* Set up the array */
26   CHKERRQ(DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,M,w,s,NULL,&da));
27   CHKERRQ(DMSetFromOptions(da));
28   CHKERRQ(DMSetUp(da));
29   CHKERRQ(DMCreateGlobalVector(da,&global));
30   CHKERRMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
31   CHKERRMPI(MPI_Comm_size(PETSC_COMM_WORLD,&size));
32 
33   /* Make copy of local array for doing updates */
34   CHKERRQ(DMCreateLocalVector(da,&local));
35 
36   /* determine starting point of each processor */
37   CHKERRQ(VecGetOwnershipRange(global,&mybase,&myend));
38 
39   /* Initialize the Array */
40   CHKERRQ(VecGetLocalSize (global,&globalsize));
41   CHKERRQ(VecGetArray (global,&globalptr));
42 
43   for (i=0; i<globalsize; i++) {
44     j = i + mybase;
45 
46     globalptr[i] = PetscSinReal((PETSC_PI*j*6)/((PetscReal)M) + 1.2 * PetscSinReal((PETSC_PI*j*2)/((PetscReal)M))) * 4+4;
47   }
48 
49   CHKERRQ(VecRestoreArray(global,&localptr));
50 
51   /* Assign Parameters */
52   h= 1.0/M;
53   k= h*h/2.2;
54   CHKERRQ(VecGetLocalSize(local,&localsize));
55 
56   for (j=0; j<time_steps; j++) {
57 
58     /* Global to Local */
59     CHKERRQ(DMGlobalToLocalBegin(da,global,INSERT_VALUES,local));
60     CHKERRQ(DMGlobalToLocalEnd(da,global,INSERT_VALUES,local));
61 
62     /*Extract local array */
63     CHKERRQ(VecGetArray(local,&localptr));
64     CHKERRQ(VecGetArray (global,&globalptr));
65 
66     /* Update Locally - Make array of new values */
67     /* Note: I don't do anything for the first and last entry */
68     for (i=1; i< localsize-1; i++) {
69       globalptr[i-1] = localptr[i] + (k/(h*h)) * (localptr[i+1]-2.0*localptr[i]+localptr[i-1]);
70     }
71 
72     CHKERRQ(VecRestoreArray (global,&globalptr));
73     CHKERRQ(VecRestoreArray(local,&localptr));
74 
75     /* View Wave */
76     /* Set Up Display to Show Heat Graph */
77 #if defined(PETSC_USE_SOCKET_VIEWER)
78     CHKERRQ(VecView(global,PETSC_VIEWER_SOCKET_WORLD));
79 #endif
80   }
81 
82   CHKERRQ(VecDestroy(&local));
83   CHKERRQ(VecDestroy(&global));
84   CHKERRQ(DMDestroy(&da));
85   CHKERRQ(PetscFinalize());
86   return 0;
87 }
88