Actual source code: ex2.c
1: static char help[] = "Builds a parallel vector with 1 component on the first processor, 2 on the second, etc.\n\
2: Then each processor adds one to all elements except the last rank.\n\n";
4: /*
5: Include "petscvec.h" so that we can use vectors. Note that this file
6: automatically includes:
7: petscsys.h - base PETSc routines petscis.h - index sets
8: */
9: #include <petscvec.h>
11: int main(int argc, char **argv)
12: {
13: PetscMPIInt rank;
14: PetscInt N;
15: PetscScalar one = 1.0;
16: Vec x;
18: PetscFunctionBeginUser;
19: PetscCall(PetscInitialize(&argc, &argv, NULL, help));
20: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
22: /*
23: Create a parallel vector.
24: - In this case, we specify the size of each processor's local
25: portion, and PETSc computes the global size. Alternatively,
26: if we pass the global size and use PETSC_DECIDE for the
27: local size PETSc will choose a reasonable partition trying
28: to put nearly an equal number of elements on each processor.
29: */
30: PetscCall(VecCreate(PETSC_COMM_WORLD, &x));
31: PetscCall(VecSetSizes(x, rank + 1, PETSC_DECIDE));
32: PetscCall(VecSetFromOptions(x));
33: PetscCall(VecGetSize(x, &N));
34: PetscCall(VecSet(x, one));
36: /*
37: Set the vector elements.
38: - Always specify global locations of vector entries.
39: - Each processor can contribute any vector entries,
40: regardless of which processor "owns" them; any nonlocal
41: contributions will be transferred to the appropriate processor
42: during the assembly process.
43: - In this example, the flag ADD_VALUES indicates that all
44: contributions will be added together.
45: */
46: for (PetscInt i = 0; i < N - rank; i++) PetscCall(VecSetValues(x, 1, &i, &one, ADD_VALUES));
48: /*
49: Assemble vector, using the 2-step process:
50: VecAssemblyBegin(), VecAssemblyEnd()
51: Computations can be done while messages are in transition
52: by placing code between these two statements.
53: */
54: PetscCall(VecAssemblyBegin(x));
55: PetscCall(VecAssemblyEnd(x));
57: /*
58: View the vector; then destroy it.
59: */
60: PetscCall(VecView(x, PETSC_VIEWER_STDOUT_WORLD));
61: PetscCall(VecDestroy(&x));
63: PetscCall(PetscFinalize());
64: return 0;
65: }
67: /*TEST
69: test:
70: nsize: 2
72: TEST*/