xref: /petsc/src/dm/tutorials/ex5.c (revision d5b43468fb8780a8feea140ccd6fa3e6a50411cc)
1 
2 static char help[] = "Tests DMDAGetElements() and VecView() contour plotting for 2d DMDAs.\n\n";
3 
4 #include <petscdm.h>
5 #include <petscdmda.h>
6 #include <petscdraw.h>
7 
8 int main(int argc, char **argv)
9 {
10   PetscInt        M = 10, N = 8, ne, nc, i;
11   const PetscInt *e;
12   PetscBool       flg = PETSC_FALSE;
13   DM              da;
14   PetscViewer     viewer;
15   Vec             local, global;
16   PetscScalar     value;
17   DMBoundaryType  bx = DM_BOUNDARY_NONE, by = DM_BOUNDARY_NONE;
18   DMDAStencilType stype = DMDA_STENCIL_BOX;
19   PetscScalar    *lv;
20 
21   PetscFunctionBeginUser;
22   PetscCall(PetscInitialize(&argc, &argv, (char *)0, help));
23   PetscCall(PetscViewerDrawOpen(PETSC_COMM_WORLD, 0, "", 300, 0, 300, 300, &viewer));
24 
25   /* Read options */
26   PetscCall(PetscOptionsGetInt(NULL, NULL, "-M", &M, NULL));
27   PetscCall(PetscOptionsGetInt(NULL, NULL, "-N", &N, NULL));
28   PetscCall(PetscOptionsGetBool(NULL, NULL, "-star_stencil", &flg, NULL));
29   if (flg) stype = DMDA_STENCIL_STAR;
30 
31   /* Create distributed array and get vectors */
32   PetscCall(DMDACreate2d(PETSC_COMM_WORLD, bx, by, stype, M, N, PETSC_DECIDE, PETSC_DECIDE, 1, 1, NULL, NULL, &da));
33   PetscCall(DMSetFromOptions(da));
34   PetscCall(DMSetUp(da));
35   PetscCall(DMCreateGlobalVector(da, &global));
36   PetscCall(DMCreateLocalVector(da, &local));
37 
38   value = -3.0;
39   PetscCall(VecSet(global, value));
40   PetscCall(DMGlobalToLocalBegin(da, global, INSERT_VALUES, local));
41   PetscCall(DMGlobalToLocalEnd(da, global, INSERT_VALUES, local));
42 
43   PetscCall(DMDASetElementType(da, DMDA_ELEMENT_P1));
44   PetscCall(DMDAGetElements(da, &ne, &nc, &e));
45   PetscCall(VecGetArray(local, &lv));
46   for (i = 0; i < ne; i++) {
47     PetscCall(PetscSynchronizedPrintf(PETSC_COMM_WORLD, "i %" PetscInt_FMT " e[3*i] %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT "\n", i, e[3 * i], e[3 * i + 1], e[3 * i + 2]));
48     lv[e[3 * i]] = i;
49   }
50   PetscCall(PetscSynchronizedFlush(PETSC_COMM_WORLD, stdout));
51   PetscCall(VecRestoreArray(local, &lv));
52   PetscCall(DMDARestoreElements(da, &ne, &nc, &e));
53 
54   PetscCall(DMLocalToGlobalBegin(da, local, ADD_VALUES, global));
55   PetscCall(DMLocalToGlobalEnd(da, local, ADD_VALUES, global));
56 
57   PetscCall(DMView(da, viewer));
58   PetscCall(VecView(global, viewer));
59 
60   /* Free memory */
61   PetscCall(PetscViewerDestroy(&viewer));
62   PetscCall(VecDestroy(&local));
63   PetscCall(VecDestroy(&global));
64   PetscCall(DMDestroy(&da));
65   PetscCall(PetscFinalize());
66   return 0;
67 }
68 
69 /*TEST
70 
71    test:
72      requires: x
73 
74    test:
75      suffix: 2
76      nsize: 2
77      requires: x
78 
79 TEST*/
80