xref: /petsc/doc/manual/vec.md (revision 174dc0c8cee294b82b85e4dd3b331b29396264fc)
1(ch_vectors)=
2
3# Vectors and Parallel Data
4
5Vectors (denoted by `Vec`) are used to store discrete PDE solutions, right-hand sides for
6linear systems, etc. Users can create and manipulate entries in vectors directly with a basic, low-level interface or
7they can use the PETSc `DM` objects to connect actions on vectors to the type of discretization and grid that they are
8working with. These higher-level interfaces handle much of the details of the interactions with vectors and hence, are preferred
9in most situations. This chapter is organized as follows:
10
11- {any}`sec_veccreate`
12
13  - User managed
14  - {any}`sec_struct`
15  - {any}`sec_stag`
16  - {any}`sec_unstruct`
17  - {any}`sec_network`
18
19- Setting vector values
20
21  - For generic vectors
22  - {any}`sec_struct_set`
23  - {any}`sec_stag_set`
24  - {any}`sec_unstruct_set`
25  - {any}`sec_network_set`
26
27- {any}`sec_vecbasic`
28
29- {any}`sec_localglobal`
30
31- {any}`sec_scatter`
32
33  - {any}`sec_islocaltoglobalmap`
34  - {any}`sec_vecghost`
35
36- {any}`sec_ao`
37
38(sec_veccreate)=
39
40## Creating Vectors
41
42PETSc provides many ways to create vectors. The most basic, where the user is responsible for managing the
43parallel distribution of the vector entries, and a variety of higher-level approaches, based on `DM`, for classes of problems such
44as structured grids, staggered grids, unstructured grids, networks, and particles.
45
46The most basic way to create a vector with a local size of `m` and a global size of `M`, is to
47use
48
49```
50VecCreate(MPI_Comm comm,Vec *v);
51VecSetSizes(Vec v, PetscInt m, PetscInt M);
52VecSetFromOptions(Vec v);
53```
54
55which automatically generates the appropriate vector type (sequential or
56parallel) over all processes in `comm`. The option `-vec_type <type>`
57can be used in conjunction with
58`VecSetFromOptions()` to specify the use of a particular type of vector. For example, for NVIDIA GPU CUDA, use `cuda`.
59The GPU-based vectors allow
60one to set values on either the CPU or GPU but do their computations on the GPU.
61
62We emphasize that all processes in `comm` *must* call the vector
63creation routines since these routines are collective on all
64processes in the communicator. If you are unfamiliar with MPI
65communicators, see the discussion in {any}`sec_writing`. In addition, if a sequence of creation routines is
66used, they must be called in the same order for each process in the
67communicator.
68
69Instead of, or before calling `VecSetFromOptions()`, one can call
70
71```
72VecSetType(Vec v,VecType <VECCUDA, VECHIP, VECKOKKOS etc>)
73```
74
75One can create vectors whose entries are stored on GPUs using the convenience routine,
76
77```
78VecCreateMPICUDA(MPI_Comm comm,PetscInt m,PetscInt M,Vec *x);
79```
80
81There are convenience creation routines for almost all vector types; we recommend using the more verbose form because it allows
82selecting CPU or GPU simulations at runtime.
83
84For applications running in parallel that involve multi-dimensional structured grids, unstructured grids, networks, etc, it is cumbersome for users to explicitly manage the needed local and global sizes of the vectors.
85Hence, PETSc provides two powerful abstract objects (lower level) `PetscSection` (see {any}`ch_petscsection`) and (higher level) `DM` (see {any}`ch_dmbase`) to help manage the vectors and matrices needed for such applications. Using `DM`, parallel vectors can be created easily with
86
87```
88DMCreateGlobalVector(DM dm,Vec *v)
89```
90
91The `DM` object, see {any}`sec_struct`, {any}`sec_stag`, and {any}`ch_unstructured` for more details on `DM` for structured grids, staggered
92structured grids, and for unstructured grids,
93manages creating the correctly sized parallel vectors efficiently. One controls the type of vector that `DM` creates by calling
94
95```
96DMSetVecType(DM dm,VecType vt)
97```
98
99or by calling `DMSetFromOptions(DM dm)` and using the option `-dm_vec_type <standard or cuda or kokkos etc>`
100
101(sec_struct)=
102
103### DMDA - Creating vectors for structured grids
104
105Each `DM` type is suitable for a family of problems. The first of these, `DMDA`
106are intended for use with *logically structured rectangular grids*
107when communication of nonlocal data is needed before certain local
108computations can occur. `DMDA` is designed only for
109the case in which data can be thought of as being stored in a standard
110multidimensional array; thus, `DMDA` are *not* intended for
111parallelizing unstructured grid problems, etc.
112
113For example, a typical situation one encounters in solving PDEs in
114parallel is that, to evaluate a local function, `f(x)`, each process
115requires its local portion of the vector `x` as well as its ghost
116points (the bordering portions of the vector that are owned by
117neighboring processes). Figure {any}`fig_ghosts` illustrates the
118ghost points for the seventh process of a two-dimensional, structured
119parallel grid. Each box represents a process; the ghost points for the
120seventh process’s local part of a parallel array are shown in gray.
121
122:::{figure} /images/manual/ghost.*
123:alt: Ghost Points for Two Stencil Types on the Seventh Process
124:name: fig_ghosts
125
126Ghost Points for Two Stencil Types on the Seventh Process
127:::
128
129The `DMDA` object
130contains parallel data layout information and communication
131information and is used to create vectors and matrices with
132the proper layout.
133
134One creates a `DMDA` two
135dimensions with the convenience routine
136
137```
138DMDACreate2d(MPI_Comm comm,DMBoundaryType xperiod,DMBoundaryType yperiod,DMDAStencilType st,PetscInt M, PetscInt N,PetscInt m,PetscInt n,PetscInt dof,PetscInt s,PetscInt *lx,PetscInt *ly,DM *da);
139```
140
141The arguments `M` and `N` indicate the global numbers of grid points
142in each direction, while `m` and `n` denote the process partition in
143each direction; `m*n` must equal the number of processes in the MPI
144communicator, `comm`. Instead of specifying the process layout, one
145may use `PETSC_DECIDE` for `m` and `n` so that PETSc will
146select the partition. The type of periodicity of the array
147is specified by `xperiod` and `yperiod`, which can be
148`DM_BOUNDARY_NONE` (no periodicity), `DM_BOUNDARY_PERIODIC`
149(periodic in that direction), `DM_BOUNDARY_TWIST` (periodic in that
150direction, but identified in reverse order), `DM_BOUNDARY_GHOSTED` ,
151or `DM_BOUNDARY_MIRROR`. The argument `dof` indicates the number of
152degrees of freedom at each array point, and `s` is the stencil width
153(i.e., the width of the ghost point region). The optional arrays `lx`
154and `ly` may contain the number of nodes along the x and y axis for
155each cell, i.e. the dimension of `lx` is `m` and the dimension of
156`ly` is `n`; alternately, `NULL` may be passed in.
157
158Two types of `DMDA` communication data structures can be
159created, as specified by `st`. Star-type stencils that radiate outward
160only in the coordinate directions are indicated by
161`DMDA_STENCIL_STAR`, while box-type stencils are specified by
162`DMDA_STENCIL_BOX`. For example, for the two-dimensional case,
163`DMDA_STENCIL_STAR` with width 1 corresponds to the standard 5-point
164stencil, while `DMDA_STENCIL_BOX` with width 1 denotes the standard
1659-point stencil. In both instances, the ghost points are identical, the
166only difference being that with star-type stencils, certain ghost points
167are ignored, substantially decreasing the number of messages sent. Note
168that the `DMDA_STENCIL_STAR` stencils can save interprocess
169communication in two and three dimensions.
170
171These `DMDA` stencils have nothing directly to do with a specific finite
172difference stencil one might choose to use for discretization; they
173only ensure that the correct values are in place for the application of a
174user-defined finite difference stencil (or any other discretization
175technique).
176
177The commands for creating `DMDA`
178in one and three dimensions are analogous:
179
180```
181DMDACreate1d(MPI_Comm comm,DMBoundaryType xperiod,PetscInt M,PetscInt w,PetscInt s,PetscInt *lc,DM *inra);
182```
183
184```
185DMDACreate3d(MPI_Comm comm,DMBoundaryType xperiod,DMBoundaryType yperiod,DMBoundaryType zperiod, DMDAStencilType stencil_type,PetscInt M,PetscInt N,PetscInt P,PetscInt m,PetscInt n,PetscInt p,PetscInt w,PetscInt s,PetscInt *lx,PetscInt *ly,PetscInt *lz,DM *inra);
186```
187
188The routines to create a `DM` are collective so that all
189processes in the communicator `comm` must call the same creation routines in the same order.
190
191A `DM` may be created, and its type set with
192
193```
194DMCreate(comm,&dm);
195DMSetType(dm,"Typename");  // for example, "DMDA"
196```
197
198Then `DMType` specific operations can be performed to provide information from which the specifics of the
199`DM` will be provided. For example,
200
201```
202DMSetDimension(dm, 1);
203DMDASetSizes(dm, M, 1, 1));
204DMDASetDof(dm, 1));
205DMSetUp(dm);
206```
207
208We now very briefly introduce a few more `DMType`.
209
210(sec_stag)=
211
212### DMSTAG - Creating vectors for staggered grids
213
214For structured grids with staggered data (living on elements, faces, edges,
215and/or vertices), the `DMSTAG` object is available. It behaves much
216like `DMDA`.
217See {any}`ch_stag` for discussion of creating vectors with `DMSTAG`.
218
219(sec_unstruct)=
220
221### DMPLEX - Creating vectors for unstructured grids
222
223See {any}`ch_unstructured` for a discussion of creating vectors with `DMPLEX`.
224
225(sec_network)=
226
227### DMNETWORK - Creating vectors for networks
228
229See {any}`ch_network` for discussion of creating vectors with `DMNETWORK`.
230
231## Common vector functions and operations
232
233One can examine (print out) a vector with the command
234
235```
236VecView(Vec x,PetscViewer v);
237```
238
239To print the vector to the screen, one can use the viewer
240`PETSC_VIEWER_STDOUT_WORLD`, which ensures that parallel vectors are
241printed correctly to `stdout`. To display the vector in an X-window,
242one can use the default X-windows viewer `PETSC_VIEWER_DRAW_WORLD`, or
243one can create a viewer with the routine `PetscViewerDrawOpen()`. A
244variety of viewers are discussed further in
245{any}`sec_viewers`.
246
247To create a new vector of the same format and parallel layout as an existing vector,
248use
249
250```
251VecDuplicate(Vec old,Vec *new);
252```
253
254To create several new vectors of the same format as an existing vector,
255use
256
257```
258VecDuplicateVecs(Vec old,PetscInt n,Vec **new);
259```
260
261This routine creates an array of pointers to vectors. The two routines
262are useful because they allow one to write library code that does
263not depend on the particular format of the vectors being used. Instead,
264the subroutines can automatically create work vectors based on
265the specified existing vector.
266
267When a vector is no longer needed, it should be destroyed with the
268command
269
270```
271VecDestroy(Vec *x);
272```
273
274To destroy an array of vectors, use the command
275
276```
277VecDestroyVecs(PetscInt n,Vec **vecs);
278```
279
280It is also possible to create vectors that use an array the user provides rather than having PETSc internally allocate the array space. Such
281vectors can be created with the routines such as
282
283```
284VecCreateSeqWithArray(PETSC_COMM_SELF,PetscInt bs,PetscInt n,PetscScalar *array,Vec *V);
285```
286
287```
288VecCreateMPIWithArray(MPI_Comm comm,PetscInt bs,PetscInt n,PetscInt N,PetscScalar *array,Vec *V);
289```
290
291```
292VecCreateMPICUDAWithArray(MPI_Comm comm,PetscInt bs,PetscInt n,PetscInt N,PetscScalar *array,Vec *V);
293```
294
295The `array` pointer should be a GPU memory location for GPU vectors.
296
297Note that here, one must provide the value `n`; it cannot be
298`PETSC_DECIDE` and the user is responsible for providing enough space
299in the array; `n*sizeof(PetscScalar)`.
300
301## Assembling (putting values in) vectors
302
303One can assign a single value to all components of a vector with
304
305```
306VecSet(Vec x,PetscScalar value);
307```
308
309Assigning values to individual vector components is more
310complicated to make it possible to write efficient parallel
311code. Assigning a set of components on a CPU is a two-step process: one first
312calls
313
314```
315VecSetValues(Vec x,PetscInt n,PetscInt *indices,PetscScalar *values,INSERT_VALUES);
316```
317
318any number of times on any or all of the processes. The argument `n`
319gives the number of components being set in this insertion. The integer
320array `indices` contains the *global component indices*, and
321`values` is the array of values to be inserted at those global component index locations. Any process can set
322any vector components; PETSc ensures that they are automatically
323stored in the correct location. Once all of the values have been
324inserted with `VecSetValues()`, one must call
325
326```
327VecAssemblyBegin(Vec x);
328```
329
330followed by
331
332```
333VecAssemblyEnd(Vec x);
334```
335
336to perform any needed message passing of nonlocal components. In order
337to allow the overlap of communication and calculation, the user’s code
338can perform any series of other actions between these two calls while
339the messages are in transition.
340
341Example usage of `VecSetValues()` may be found in
342<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tutorials/ex2.c.html">src/vec/vec/tutorials/ex2.c</a>
343or <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/vec/vec/tutorials/ex2f.F90.html">src/vec/vec/tutorials/exf.F90</a>.
344
345Rather than inserting elements in a vector, one may wish to add
346values. This process is also done with the command
347
348```
349VecSetValues(Vec x,PetscInt n,PetscInt *indices, PetscScalar *values,ADD_VALUES);
350```
351
352Again, one must call the assembly routines `VecAssemblyBegin()` and
353`VecAssemblyEnd()` after all of the values have been added. Note that
354addition and insertion calls to `VecSetValues()` *cannot* be mixed.
355Instead, one must add and insert vector elements in phases, with
356intervening calls to the assembly routines. This phased assembly
357procedure overcomes the nondeterministic behavior that would occur if
358two different processes generated values for the same location, with one
359process adding while the other is inserting its value. (In this case, the
360addition and insertion actions could be performed in either order, thus
361resulting in different values at the particular location. Since PETSc
362does not allow the simultaneous use of `INSERT_VALUES` and
363`ADD_VALUES` this nondeterministic behavior will not occur in PETSc.)
364
365You can call `VecGetValues()` to pull local values from a vector (but
366not off-process values).
367
368For vectors obtained with `DMCreateGlobalVector()`, one can use `VecSetValuesLocal()` to set values into
369a global vector but using the local (ghosted) vector indexing of the vector entries. See also {any}`sec_islocaltoglobalmap`
370that allows one to provide arbitrary local-to-global mapping when not working with a `DM`.
371
372It is also possible to interact directly with the arrays that the vector values are stored
373in. The routine `VecGetArray()` returns a pointer to the elements local to
374the process:
375
376```
377VecGetArray(Vec v,PetscScalar **array);
378```
379
380When access to the array is no longer needed, the user should call
381
382```
383VecRestoreArray(Vec v, PetscScalar **array);
384```
385
386If the values do not need to be modified, the routines
387
388```
389VecGetArrayRead(Vec v, const PetscScalar **array);
390VecRestoreArrayRead(Vec v, const PetscScalar **array);
391```
392
393should be used instead.
394
395:::{admonition} Listing: <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex1.c.html">SNES Tutorial src/snes/tutorials/ex1.c</a>
396```{literalinclude} /../src/snes/tutorials/ex1.c
397:end-at: PetscFunctionReturn(PETSC_SUCCESS);
398:name: snesex1
399:start-at: PetscErrorCode FormFunction1(SNES snes, Vec x, Vec f, void *ctx)
400```
401:::
402
403Minor differences exist in the Fortran interface for `VecGetArray()`
404and `VecRestoreArray()`, as discussed in
405{any}`sec_fortranarrays`. It is important to note that
406`VecGetArray()` and `VecRestoreArray()` do *not* copy the vector
407elements; they merely give users direct access to the vector elements.
408Thus, these routines require essentially no time to call and can be used
409efficiently.
410
411For GPU vectors, one can access either the values on the CPU as described above or one
412can call, for example,
413
414```
415VecCUDAGetArray(Vec v, PetscScalar **array);
416```
417
418:::{admonition} Listing: <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex47cu.cu.html">SNES Tutorial src/snes/tutorials/ex47cu.cu</a>
419```{literalinclude} /../src/snes/tutorials/ex47cu.cu
420:end-at: '}'
421:name: snesex47
422:start-at: PetscCall(VecCUDAGetArrayRead(xlocal, &xarray));
423```
424:::
425
426or
427
428```
429VecGetArrayAndMemType(Vec v, PetscScalar **array,PetscMemType *mtype);
430```
431
432which, in the first case, returns a GPU memory address and, in the second case, returns either a CPU or GPU memory
433address depending on the type of the vector. One can then launch a GPU kernel function that accesses the
434vector's memory for usage with GPUs. When computing on GPUs, `VecSetValues()` is not used! One always accesses the vector's arrays and passes them
435to the GPU code.
436
437It can also be convenient to treat the vector entries as a Kokkos view. One first creates Kokkos vectors and then calls
438
439```
440VecGetKokkosView(Vec v, Kokkos::View<const PetscScalar*,MemorySpace> *kv)
441```
442
443to set or access the vector entries.
444
445Of course, to provide the correct values to a vector, one must know what parts of the vector are owned by each MPI process.
446For parallel vectors, either CPU or GPU-based, it is possible to determine a process’s local range with the
447routine
448
449```
450VecGetOwnershipRange(Vec vec,PetscInt *start,PetscInt *end);
451```
452
453The argument `start` indicates the first component owned by the local
454process, while `end` specifies *one more than* the last owned by the
455local process. This command is useful, for instance, in assembling
456parallel vectors.
457
458If the `Vec` was obtained from a `DM` with `DMCreateGlobalVector()`, then the range values are determined by the specific `DM`.
459If the `Vec` was created directly, the range values are determined by the local size passed to `VecSetSizes()` or `VecCreateMPI()`.
460If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
461For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
462the local values in the vector.
463
464Very occasionally, all MPI processes need to know all the range values, these can be obtained with
465
466```
467VecGetOwnershipRanges(Vec vec,PetscInt range[]);
468```
469
470The number of elements stored locally can be accessed with
471
472```
473VecGetLocalSize(Vec v,PetscInt *size);
474```
475
476The global vector length can be determined by
477
478```
479VecGetSize(Vec v,PetscInt *size);
480```
481
482(sec_struct_set)=
483
484### DMDA - Setting vector values
485
486PETSc provides an easy way to set values into the `DMDA` vectors and
487access them using the natural grid indexing. This is done with the
488routines
489
490```
491DMDAVecGetArray(DM da,Vec l,void *array);
492... use the array indexing it with 1, 2, or 3 dimensions ...
493... depending on the dimension of the DMDA ...
494DMDAVecRestoreArray(DM da,Vec l,void *array);
495DMDAVecGetArrayRead(DM da,Vec l,void *array);
496... use the array indexing it with 1, 2, or 3 dimensions ...
497... depending on the dimension of the DMDA ...
498DMDAVecRestoreArrayRead(DM da,Vec l,void *array);
499```
500
501where `array` is a multidimensional C array with the same dimension as `da`, and
502
503```
504DMDAVecGetArrayDOF(DM da,Vec l,void *array);
505... use the array indexing it with 2, 3, or 4 dimensions ...
506... depending on the dimension of the DMDA ...
507DMDAVecRestoreArrayDOF(DM da,Vec l,void *array);
508DMDAVecGetArrayDOFRead(DM da,Vec l,void *array);
509... use the array indexing it with 2, 3, or 4 dimensions ...
510... depending on the dimension of the DMDA ...
511DMDAVecRestoreArrayDOFRead(DM da,Vec l,void *array);
512```
513
514where `array` is a multidimensional C array with one more dimension than
515`da`. The vector `l` can be either a global vector or a local
516vector. The `array` is accessed using the usual *global* indexing on
517the entire grid, but the user may *only* refer to this array's local and ghost
518entries as all other entries are undefined. For example,
519for a scalar problem in two dimensions, one could use
520
521```
522PetscScalar **f,**u;
523...
524DMDAVecGetArrayRead(DM da,Vec local,&u);
525DMDAVecGetArray(DM da,Vec global,&f);
526...
527  f[i][j] = u[i][j] - ...
528...
529DMDAVecRestoreArrayRead(DM da,Vec local,&u);
530DMDAVecRestoreArray(DM da,Vec global,&f);
531```
532
533:::{admonition} Listing: <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex3.c.html">SNES Tutorial src/snes/tutorials/ex3.c</a>
534```{literalinclude} /../src/snes/tutorials/ex3.c
535:end-at: PetscFunctionReturn(PETSC_SUCCESS);
536:name: snesex3
537:start-at: PetscErrorCode FormFunction(SNES snes, Vec x, Vec f, void *ctx)
538```
539:::
540
541The recommended approach for multi-component PDEs is to declare a
542`struct` representing the fields defined at each node of the grid,
543e.g.
544
545```
546typedef struct {
547  PetscScalar u,v,omega,temperature;
548} Node;
549```
550
551and write the residual evaluation using
552
553```
554Node **f,**u;
555DMDAVecGetArray(DM da,Vec local,&u);
556DMDAVecGetArray(DM da,Vec global,&f);
557 ...
558    f[i][j].omega = ...
559 ...
560DMDAVecRestoreArray(DM da,Vec local,&u);
561DMDAVecRestoreArray(DM da,Vec global,&f);
562```
563
564The `DMDAVecGetArray` routines are also provided for GPU access with CUDA, HIP, and Kokkos. For example,
565
566```
567DMDAVecGetKokkosOffsetView(DM da,Vec vec,Kokkos::View<const PetscScalar*XX*,MemorySpace> *ov)
568```
569
570where `*XX*` can contain any number of `*`. This allows one to write very natural Kokkos multi-dimensional parallel for kernels
571that act on the local portion of `DMDA` vectors.
572
573:::{admonition} Listing: <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex3k.kokkos.cxx.html">SNES Tutorial src/snes/tutorials/ex3k.kokkos.cxx</a>
574:name: snes-ex3-kokkos
575
576```{literalinclude} /../src/snes/tutorials/ex3k.kokkos.cxx
577:end-at: PetscFunctionReturn(PETSC_SUCCESS);
578:start-at: PetscErrorCode KokkosFunction(SNES snes, Vec x, Vec r, void *ctx)
579```
580:::
581
582The global indices of the lower left corner of the local portion of vectors obtained from `DMDA`
583as well as the local array size can be obtained with the commands
584
585```
586DMDAGetCorners(DM da,PetscInt *x,PetscInt *y,PetscInt *z,PetscInt *m,PetscInt *n,PetscInt *p);
587DMDAGetGhostCorners(DM da,PetscInt *x,PetscInt *y,PetscInt *z,PetscInt *m,PetscInt *n,PetscInt *p);
588```
589
590These values can then be used as loop bounds for local function evaluations as demonstrated in the function examples above.
591
592The first version excludes ghost points, while the second
593includes them. The routine `DMDAGetGhostCorners()` deals with the fact
594that subarrays along boundaries of the problem domain have ghost points
595only on their interior edges, but not on their boundary edges.
596
597When either type of stencil is used, `DMDA_STENCIL_STAR` or
598`DMDA_STENCIL_BOX`, the local vectors (with the ghost points)
599represent rectangular arrays, including the extra corner elements in the
600`DMDA_STENCIL_STAR` case. This configuration provides simple access to
601the elements by employing two- (or three--) dimensional indexing. The
602only difference between the two cases is that when `DMDA_STENCIL_STAR`
603is used, the extra corner components are *not* scattered between the
604processes and thus contain undefined values that should *not* be used.
605
606(sec_stag_set)=
607
608### DMSTAG - Setting vector values
609
610For structured grids with staggered data (living on elements, faces, edges,
611and/or vertices), the `DMStag` object is available. It behaves
612like `DMDA`; see the `DMSTAG` manual page for more information.
613
614:::{admonition} Listing: <a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/dm/impls/stag/tutorials/ex6.c.html">SNES Tutorial src/dm/impls/stag/tutorials/ex6.c</a>
615```{literalinclude} /../src/dm/impls/stag/tutorials/ex6.c
616:end-at: /* Update x-velocity */
617:name: stagex6
618:start-at: static PetscErrorCode UpdateVelocity_2d(const Ctx *ctx, Vec velocity, Vec
619:  stress, Vec buoyancy)
620```
621:::
622
623(sec_unstruct_set)=
624
625### DMPLEX - Setting vector values
626
627See {any}`ch_unstructured` for a discussion on setting vector values with `DMPLEX`.
628
629(sec_network_set)=
630
631### DMNETWORK - Setting vector values
632
633See {any}`ch_network` for a discussion on setting vector values with `DMNETWORK`.
634
635(sec_vecbasic)=
636
637## Basic Vector Operations
638
639% Should make the table more attractive by using, for example, cloud_sptheme.ext.table_styling and the lines below
640% :column-alignment: left left
641% :widths: 72 28
642
643:::{container}
644:name: fig_vectorops
645
646```{eval-rst}
647.. table:: PETSc Vector Operations
648
649   +-----------------------------------------------------------+-----------------------------------+
650   | **Function Name**                                         | **Operation**                     |
651   +===========================================================+===================================+
652   | ``VecAXPY(Vec y,PetscScalar a,Vec x);``                   | :math:`y = y + a*x`               |
653   +-----------------------------------------------------------+-----------------------------------+
654   | ``VecAYPX(Vec y,PetscScalar a,Vec x);``                   | :math:`y = x + a*y`               |
655   +-----------------------------------------------------------+-----------------------------------+
656   | ``VecWAXPY(Vec  w,PetscScalar a,Vec x,Vec y);``           | :math:`w = a*x + y`               |
657   +-----------------------------------------------------------+-----------------------------------+
658   | ``VecAXPBY(Vec y,PetscScalar a,PetscScalar b,Vec x);``    | :math:`y = a*x + b*y`             |
659   +-----------------------------------------------------------+-----------------------------------+
660   | ``VecAXPBYPCZ(Vec z,PetscScalar a,PetscScalar b,          | :math:`z = a*x + b*y + c*z`       |
661   | PetscScalar c,Vec x,Vec y);``                             |                                   |
662   +-----------------------------------------------------------+-----------------------------------+
663   | ``VecScale(Vec x, PetscScalar a);``                       | :math:`x = a*x`                   |
664   +-----------------------------------------------------------+-----------------------------------+
665   | ``VecDot(Vec x, Vec y, PetscScalar *r);``                 | :math:`r = \bar{x}^T*y`           |
666   +-----------------------------------------------------------+-----------------------------------+
667   | ``VecTDot(Vec x, Vec y, PetscScalar *r);``                | :math:`r = x'*y`                  |
668   +-----------------------------------------------------------+-----------------------------------+
669   | ``VecNorm(Vec x, NormType type,  PetscReal *r);``         | :math:`r = ||x||_{type}`          |
670   +-----------------------------------------------------------+-----------------------------------+
671   | ``VecSum(Vec x, PetscScalar *r);``                        | :math:`r = \sum x_{i}`            |
672   +-----------------------------------------------------------+-----------------------------------+
673   | ``VecCopy(Vec x, Vec y);``                                | :math:`y = x`                     |
674   +-----------------------------------------------------------+-----------------------------------+
675   | ``VecSwap(Vec x, Vec y);``                                | :math:`y = x` while               |
676   |                                                           | :math:`x = y`                     |
677   +-----------------------------------------------------------+-----------------------------------+
678   | ``VecPointwiseMult(Vec w,Vec x,Vec y);``                  | :math:`w_{i} = x_{i}*y_{i}`       |
679   +-----------------------------------------------------------+-----------------------------------+
680   | ``VecPointwiseDivide(Vec w,Vec x,Vec y);``                | :math:`w_{i} = x_{i}/y_{i}`       |
681   +-----------------------------------------------------------+-----------------------------------+
682   | ``VecMDot(Vec x,PetscInt n,Vec y[],PetscScalar *r);``     | :math:`r[i] = \bar{x}^T*y[i]`     |
683   +-----------------------------------------------------------+-----------------------------------+
684   | ``VecMTDot(Vec x,PetscInt n,Vec y[],PetscScalar *r);``    | :math:`r[i] = x^T*y[i]`           |
685   +-----------------------------------------------------------+-----------------------------------+
686   | ``VecMAXPY(Vec y,PetscInt n, PetscScalar *a, Vec x[]);``  | :math:`y = y + \sum_i a_{i}*x[i]` |
687   +-----------------------------------------------------------+-----------------------------------+
688   | ``VecMax(Vec x, PetscInt *idx, PetscReal *r);``           | :math:`r = \max x_{i}`            |
689   +-----------------------------------------------------------+-----------------------------------+
690   | ``VecMin(Vec x, PetscInt *idx, PetscReal *r);``           | :math:`r = \min x_{i}`            |
691   +-----------------------------------------------------------+-----------------------------------+
692   | ``VecAbs(Vec x);``                                        | :math:`x_i = |x_{i}|`             |
693   +-----------------------------------------------------------+-----------------------------------+
694   | ``VecReciprocal(Vec x);``                                 | :math:`x_i = 1/x_{i}`             |
695   +-----------------------------------------------------------+-----------------------------------+
696   | ``VecShift(Vec x,PetscScalar s);``                        | :math:`x_i = s + x_{i}`           |
697   +-----------------------------------------------------------+-----------------------------------+
698   | ``VecSet(Vec x,PetscScalar alpha);``                      | :math:`x_i = \alpha`              |
699   +-----------------------------------------------------------+-----------------------------------+
700```
701:::
702
703As the table lists, we have chosen certain
704basic vector operations to support within the PETSc vector library.
705These operations were selected because they often arise in application
706codes. The `NormType` argument to `VecNorm()` is one of `NORM_1`,
707`NORM_2`, or `NORM_INFINITY`. The 1-norm is $\sum_i |x_{i}|$,
708the 2-norm is $( \sum_{i} x_{i}^{2})^{1/2}$ and the infinity norm
709is $\max_{i} |x_{i}|$.
710
711In addition to `VecDot()` and `VecMDot()` and `VecNorm()`, PETSc
712provides split phase versions of this functionality that allow several independent
713inner products and/or norms to share the same communication (thus
714improving parallel efficiency). For example, one may have code such as
715
716```
717VecDot(Vec x,Vec y,PetscScalar *dot);
718VecMDot(Vec x,PetscInt nv, Vec y[],PetscScalar *dot);
719VecNorm(Vec x,NormType NORM_2,PetscReal *norm2);
720VecNorm(Vec x,NormType NORM_1,PetscReal *norm1);
721```
722
723This code works fine, but it performs four separate parallel
724communication operations. Instead, one can write
725
726```
727VecDotBegin(Vec x,Vec y,PetscScalar *dot);
728VecMDotBegin(Vec x, PetscInt nv,Vec y[],PetscScalar *dot);
729VecNormBegin(Vec x,NormType NORM_2,PetscReal *norm2);
730VecNormBegin(Vec x,NormType NORM_1,PetscReal *norm1);
731VecDotEnd(Vec x,Vec y,PetscScalar *dot);
732VecMDotEnd(Vec x, PetscInt nv,Vec y[],PetscScalar *dot);
733VecNormEnd(Vec x,NormType NORM_2,PetscReal *norm2);
734VecNormEnd(Vec x,NormType NORM_1,PetscReal *norm1);
735```
736
737With this code, the communication is delayed until the first call to
738`VecxxxEnd()` at which a single MPI reduction is used to communicate
739all the values. It is required that the calls to the
740`VecxxxEnd()` are performed in the same order as the calls to the
741`VecxxxBegin()`; however, if you mistakenly make the calls in the
742wrong order, PETSc will generate an error informing you of this. There
743are additional routines `VecTDotBegin()` and `VecTDotEnd()`,
744`VecMTDotBegin()`, `VecMTDotEnd()`.
745
746For GPU vectors (like CUDA), the numerical computations will, by default, run on the GPU. Any
747scalar output, like the result of a `VecDot()` are placed in CPU memory.
748
749(sec_localglobal)=
750
751## Local/global vectors and communicating between vectors
752
753Many PDE problems require ghost (or halo) values in each MPI process or even more general parallel communication
754of vector values. These values are needed
755to perform function evaluation on that MPI process. The exact structure of the ghost values needed
756depends on the type of grid being used. `DM` provides a uniform API for communicating the needed
757values. We introduce the concept in detail for `DMDA`.
758
759Each `DM` object defines the layout of two vectors: a distributed
760global vector and a local vector that includes room for the appropriate
761ghost points. The `DM` object provides information about the size
762and layout of these vectors. The user can create
763vector objects that use the `DM` layout information with the
764routines
765
766```
767DMCreateGlobalVector(DM da,Vec *g);
768DMCreateLocalVector(DM da,Vec *l);
769```
770
771These vectors will generally serve as the building blocks for local and
772global PDE solutions, etc. If additional vectors with such layout
773information are needed in a code, they can be obtained by duplicating
774`l` or `g` via `VecDuplicate()` or `VecDuplicateVecs()`.
775
776We emphasize that a `DM` provides the information needed to
777communicate the ghost value information between processes. In most
778cases, several different vectors can share the same communication
779information (or, in other words, can share a given `DM`). The design
780of the `DM` object makes this easy, as each `DM` operation may
781operate on vectors of the appropriate size, as obtained via
782`DMCreateLocalVector()` and `DMCreateGlobalVector()` or as produced
783by `VecDuplicate()`.
784
785At certain stages of many applications, there is a need to work on a
786local portion of the vector that includes the ghost points. This may be
787done by scattering a global vector into its local parts by using the
788two-stage commands
789
790```
791DMGlobalToLocalBegin(DM da,Vec g,InsertMode iora,Vec l);
792DMGlobalToLocalEnd(DM da,Vec g,InsertMode iora,Vec l);
793```
794
795which allows the overlap of communication and computation. Since the
796global and local vectors, given by `g` and `l`, respectively, must
797be compatible with the `DM`, `da`, they should be
798generated by `DMCreateGlobalVector()` and `DMCreateLocalVector()`
799(or be duplicates of such a vector obtained via `VecDuplicate()`). The
800`InsertMode` can be `ADD_VALUES` or `INSERT_VALUES` among other possible values.
801
802One can scatter the local vectors into the distributed global vector with the
803command
804
805```
806DMLocalToGlobal(DM da,Vec l,InsertMode mode,Vec g);
807```
808
809or the commands
810
811```
812DMLocalToGlobalBegin(DM da,Vec l,InsertMode mode,Vec g);
813/* (Computation to overlap with communication) */
814DMLocalToGlobalEnd(DM da,Vec l,InsertMode mode,Vec g);
815```
816
817In general this is used with an `InsertMode` of `ADD_VALUES`,
818because if one wishes to insert values into the global vector, they
819should access the global vector directly and put in the values.
820
821A third type of `DM` scatter is from a local vector
822(including ghost points that contain irrelevant values) to a local
823vector with correct ghost point values. This scatter may be done with
824the commands
825
826```
827DMLocalToLocalBegin(DM da,Vec l1,InsertMode iora,Vec l2);
828DMLocalToLocalEnd(DM da,Vec l1,InsertMode iora,Vec l2);
829```
830
831Since both local vectors, `l1` and `l2`, must be compatible with `da`, they should be generated by
832`DMCreateLocalVector()` (or be duplicates of such vectors obtained via
833`VecDuplicate()`). The `InsertMode` can be either `ADD_VALUES` or
834`INSERT_VALUES`.
835
836In most applications, the local ghosted vectors are only needed temporarily during
837user “function evaluations”. PETSc provides an easy, light-weight
838(requiring essentially no CPU time) way to temporarily obtain these work vectors and
839return them when no longer needed. This is done with the
840routines
841
842```
843DMGetLocalVector(DM da,Vec *l);
844... use the local vector l ...
845DMRestoreLocalVector(DM da,Vec *l);
846```
847
848(sec_scatter)=
849
850## Low-level Vector Communication
851
852Most users of PETSc who can utilize a `DM` will not need to utilize the lower-level routines discussed in the rest of this section
853and should skip ahead to {any}`ch_matrices`.
854
855To facilitate creating general vector scatters and gathers used, for example, in
856updating ghost points for problems for which no `DM` currently exists
857PETSc employs the concept of an *index set*, via the `IS` class. An
858index set, a generalization of a set of integer indices, is
859used to define scatters, gathers, and similar operations on vectors and
860matrices. Much of the underlying code that implements `DMGlobalToLocal` communication is built
861on the infrastructure discussed below.
862
863The following command creates an index set based on a list of integers:
864
865```
866ISCreateGeneral(MPI_Comm comm,PetscInt n,PetscInt *indices,PetscCopyMode mode, IS *is);
867```
868
869When `mode` is `PETSC_COPY_VALUES`, this routine copies the `n`
870indices passed to it by the integer array `indices`. Thus, the user
871should be sure to free the integer array `indices` when it is no
872longer needed, perhaps directly after the call to `ISCreateGeneral()`.
873The communicator, `comm`, should include all processes
874using the `IS`.
875
876Another standard index set is defined by a starting point (`first`)
877and a stride (`step`), and can be created with the command
878
879```
880ISCreateStride(MPI_Comm comm,PetscInt n,PetscInt first,PetscInt step,IS *is);
881```
882
883The meaning of `n`, `first`, and `step` correspond to the MATLAB notation
884`first:step:first+n*step`.
885
886Index sets can be destroyed with the command
887
888```
889ISDestroy(IS &is);
890```
891
892On rare occasions, the user may need to access information directly from
893an index set. Several commands assist in this process:
894
895```
896ISGetSize(IS is,PetscInt *size);
897ISStrideGetInfo(IS is,PetscInt *first,PetscInt *stride);
898ISGetIndices(IS is,PetscInt **indices);
899```
900
901The function `ISGetIndices()` returns a pointer to a list of the
902indices in the index set. For certain index sets, this may be a
903temporary array of indices created specifically for the call.
904Thus, once the user finishes using the array of indices, the routine
905
906```
907ISRestoreIndices(IS is, PetscInt **indices);
908```
909
910should be called to ensure that the system can free the space it may
911have used to generate the list of indices.
912
913A blocked version of index sets can be created with the command
914
915```
916ISCreateBlock(MPI_Comm comm,PetscInt bs,PetscInt n,PetscInt *indices,PetscCopyMode mode, IS *is);
917```
918
919This version is used for defining operations in which each element of
920the index set refers to a block of `bs` vector entries. Related
921routines analogous to those described above exist as well, including
922`ISBlockGetIndices()`, `ISBlockGetSize()`,
923`ISBlockGetLocalSize()`, `ISGetBlockSize()`.
924
925Most PETSc applications use a particular `DM` object to manage the communication details needed for their grids.
926In some rare cases, however, codes need to directly set up their required communication patterns. This is done using
927PETSc's `VecScatter` and `PetscSF` (for more general data than vectors). One
928can select any subset of the components of a vector to insert or add to
929any subset of the components of another vector. We refer to these
930operations as *generalized scatters*, though they are a
931combination of scatters and gathers.
932
933To copy selected components from one vector to another, one uses the
934following set of commands:
935
936```
937VecScatterCreate(Vec x,IS ix,Vec y,IS iy,VecScatter *ctx);
938VecScatterBegin(VecScatter ctx,Vec x,Vec y,INSERT_VALUES,SCATTER_FORWARD);
939VecScatterEnd(VecScatter ctx,Vec x,Vec y,INSERT_VALUES,SCATTER_FORWARD);
940VecScatterDestroy(VecScatter *ctx);
941```
942
943Here `ix` denotes the index set of the first vector, while `iy`
944indicates the index set of the destination vector. The vectors can be
945parallel or sequential. The only requirements are that the number of
946entries in the index set of the first vector, `ix`, equals the number
947in the destination index set, `iy`, and that the vectors be long
948enough to contain all the indices referred to in the index sets. If both
949`x` and `y` are parallel, their communicator must have the same set
950of processes, but their process order can differ. The argument
951`INSERT_VALUES` specifies that the vector elements will be inserted
952into the specified locations of the destination vector, overwriting any
953existing values. To add the components, rather than insert them, the
954user should select the option `ADD_VALUES` instead of
955`INSERT_VALUES`. One can also use `MAX_VALUES` or `MIN_VALUES` to
956replace the destination with the maximal or minimal of its current value and
957the scattered values.
958
959To perform a conventional gather operation, the user makes the
960destination index set, `iy`, be a stride index set with a stride of
961one. Similarly, a conventional scatter can be done with an initial
962(sending) index set consisting of a stride. The scatter routines are
963collective operations (i.e. all processes that own a parallel vector
964*must* call the scatter routines). When scattering from a parallel
965vector to sequential vectors, each process has its own sequential vector
966that receives values from locations as indicated in its own index set.
967Similarly, in scattering from sequential vectors to a parallel vector,
968each process has its own sequential vector that contributes to
969the parallel vector.
970
971*Caution*: When `INSERT_VALUES` is used, if two different processes
972contribute different values to the same component in a parallel vector,
973either value may be inserted. When `ADD_VALUES` is used, the
974correct sum is added to the correct location.
975
976In some cases, one may wish to “undo” a scatter, that is, perform the
977scatter backward, switching the roles of the sender and receiver. This
978is done by using
979
980```
981VecScatterBegin(VecScatter ctx,Vec y,Vec x,INSERT_VALUES,SCATTER_REVERSE);
982VecScatterEnd(VecScatter ctx,Vec y,Vec x,INSERT_VALUES,SCATTER_REVERSE);
983```
984
985Note that the roles of the first two arguments to these routines must be
986swapped whenever the `SCATTER_REVERSE` option is used.
987
988Once a `VecScatter` object has been created, it may be used with any
989vectors that have the same parallel data layout. That is, one can
990call `VecScatterBegin()` and `VecScatterEnd()` with different
991vectors than used in the call to `VecScatterCreate()` as long as they
992have the same parallel layout (the number of elements on each process are
993the same). Usually, these “different” vectors would have been obtained
994via calls to `VecDuplicate()` from the original vectors used in the
995call to `VecScatterCreate()`.
996
997`VecGetValues()` can only access
998local values from the vector. To get off-process values, the user should
999create a new vector where the components will be stored and then
1000perform the appropriate vector scatter. For example, if one desires to
1001obtain the values of the 100th and 200th entries of a parallel vector,
1002`p`, one could use a code such as that below. In this example, the
1003values of the 100th and 200th components are placed in the array values.
1004In this example, each process now has the 100th and 200th component, but
1005obviously, each process could gather any elements it needed, or none by
1006creating an index set with no entries.
1007
1008```
1009Vec         p, x;         /* initial vector, destination vector */
1010VecScatter  scatter;      /* scatter context */
1011IS          from, to;     /* index sets that define the scatter */
1012PetscScalar *values;
1013PetscInt    idx_from[] = {100,200}, idx_to[] = {0,1};
1014
1015VecCreateSeq(PETSC_COMM_SELF,2,&x);
1016ISCreateGeneral(PETSC_COMM_SELF,2,idx_from,PETSC_COPY_VALUES,&from);
1017ISCreateGeneral(PETSC_COMM_SELF,2,idx_to,PETSC_COPY_VALUES,&to);
1018VecScatterCreate(p,from,x,to,&scatter);
1019VecScatterBegin(scatter,p,x,INSERT_VALUES,SCATTER_FORWARD);
1020VecScatterEnd(scatter,p,x,INSERT_VALUES,SCATTER_FORWARD);
1021VecGetArray(x,&values);
1022ISDestroy(&from);
1023ISDestroy(&to);
1024VecScatterDestroy(&scatter);
1025```
1026
1027The scatter comprises two stages to allow for the overlap of
1028communication and computation. The introduction of the `VecScatter`
1029context allows the communication patterns for the scatter to be computed
1030once and reused repeatedly. Generally, even setting up the
1031communication for a scatter requires communication; hence, it is best to
1032reuse such information when possible.
1033
1034Scatters provide a very general method for managing the
1035communication of required ghost values for unstructured grid
1036computations. One scatters the global vector into a local “ghosted” work
1037vector, performs the computation on the local work vectors, and then
1038scatters back into the global solution vector. In the simplest case, this
1039may be written as
1040
1041```
1042VecScatterBegin(VecScatter scatter,Vec globalin,Vec localin,InsertMode INSERT_VALUES, ScatterMode SCATTER_FORWARD);
1043VecScatterEnd(VecScatter scatter,Vec globalin,Vec localin,InsertMode INSERT_VALUES,ScatterMode SCATTER_FORWARD);
1044/* For example, do local calculations from localin to localout */
1045...
1046VecScatterBegin(VecScatter scatter,Vec localout,Vec globalout,InsertMode ADD_VALUES,ScatterMode SCATTER_REVERSE);
1047VecScatterEnd(VecScatter scatter,Vec localout,Vec globalout,InsertMode ADD_VALUES,ScatterMode SCATTER_REVERSE);
1048```
1049
1050In this case, the scatter is used in a way similar to the usage of `DMGlobalToLocal()` and `DMLocalToGlobal()` discussed above.
1051
1052(sec_islocaltoglobalmap)=
1053
1054### Local to global mappings
1055
1056When working with a global representation of a vector
1057(usually on a vector obtained with `DMCreateGlobalVector()`) and a local
1058representation of the same vector that includes ghost points required
1059for local computation (obtained with `DMCreateLocalVector()`). PETSc provides routines to help map indices from
1060a local numbering scheme to the PETSc global numbering scheme, recall their use above for the routine `VecSetValuesLocal()` introduced above.
1061This is done via the following routines
1062
1063```
1064ISLocalToGlobalMappingCreate(MPI_Comm comm,PetscInt bs,PetscInt N,PetscInt* globalnum,PetscCopyMode mode,ISLocalToGlobalMapping* ctx);
1065ISLocalToGlobalMappingApply(ISLocalToGlobalMapping ctx,PetscInt n,PetscInt *in,PetscInt *out);
1066ISLocalToGlobalMappingApplyIS(ISLocalToGlobalMapping ctx,IS isin,IS* isout);
1067ISLocalToGlobalMappingDestroy(ISLocalToGlobalMapping *ctx);
1068```
1069
1070Here `N` denotes the number of local indices, `globalnum` contains
1071the global number of each local number, and `ISLocalToGlobalMapping`
1072is the resulting PETSc object that contains the information needed to
1073apply the mapping with either `ISLocalToGlobalMappingApply()` or
1074`ISLocalToGlobalMappingApplyIS()`.
1075
1076Note that the `ISLocalToGlobalMapping` routines serve a different
1077purpose than the `AO` routines. In the former case, they provide a
1078mapping from a local numbering scheme (including ghost points) to a
1079global numbering scheme, while in the latter, they provide a mapping
1080between two global numbering schemes. Many applications may use
1081both `AO` and `ISLocalToGlobalMapping` routines. The `AO` routines
1082are first used to map from an application global ordering (that has no
1083relationship to parallel processing, etc.) to the PETSc ordering scheme
1084(where each process has a contiguous set of indices in the numbering).
1085Then, to perform function or Jacobian evaluations locally on
1086each process, one works with a local numbering scheme that includes
1087ghost points. The mapping from this local numbering scheme back to the
1088global PETSc numbering can be handled with the
1089`ISLocalToGlobalMapping` routines.
1090
1091If one is given a list of block indices in a global numbering, the
1092routine
1093
1094```
1095ISGlobalToLocalMappingApplyBlock(ISLocalToGlobalMapping ctx,ISGlobalToLocalMappingMode type,PetscInt nin,PetscInt idxin[],PetscInt *nout,PetscInt idxout[]);
1096```
1097
1098will provide a new list of indices in the local numbering. Again,
1099negative values in `idxin` are left unmapped. But in addition, if
1100`type` is set to `IS_GTOLM_MASK` , then `nout` is set to `nin`
1101and all global values in `idxin` that are not represented in the local
1102to global mapping are replaced by -1. When `type` is set to
1103`IS_GTOLM_DROP`, the values in `idxin` that are not represented
1104locally in the mapping are not included in `idxout`, so that
1105potentially `nout` is smaller than `nin`. One must pass in an array
1106long enough to hold all the indices. One can call
1107`ISGlobalToLocalMappingApplyBlock()` with `idxout` equal to `NULL`
1108to determine the required length (returned in `nout`) and then
1109allocate the required space and call
1110`ISGlobalToLocalMappingApplyBlock()` a second time to set the values.
1111
1112Often it is convenient to set elements into a vector using the local
1113node numbering rather than the global node numbering (e.g., each process
1114may maintain its own sublist of vertices and elements and number them
1115locally). To set values into a vector with the local numbering, one must
1116first call
1117
1118```
1119VecSetLocalToGlobalMapping(Vec v,ISLocalToGlobalMapping ctx);
1120```
1121
1122and then call
1123
1124```
1125VecSetValuesLocal(Vec x,PetscInt n,const PetscInt indices[],const PetscScalar values[],INSERT_VALUES);
1126```
1127
1128Now the `indices` use the local numbering rather than the global,
1129meaning the entries lie in $[0,n)$ where $n$ is the local
1130size of the vector. Global vectors obtained from a `DM` already have the global to local mapping
1131provided by the `DM`.
1132
1133One can use global indices
1134with `MatSetValues()` or `MatSetValuesStencil()` to assemble global stiffness matrices. Alternately, the
1135global node number of each local node, including the ghost nodes, can be
1136obtained by calling
1137
1138```
1139DMGetLocalToGlobalMapping(DM da,ISLocalToGlobalMapping *map);
1140```
1141
1142followed by
1143
1144```
1145VecSetLocalToGlobalMapping(Vec v,ISLocalToGlobalMapping map);
1146MatSetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping);
1147```
1148
1149Now, entries may be added to the vector and matrix using the local
1150numbering and `VecSetValuesLocal()` and `MatSetValuesLocal()`.
1151
1152The example
1153<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex5.c.html">SNES Tutorial ex5</a>
1154illustrates the use of a `DMDA` in the solution of a
1155nonlinear problem. The analogous Fortran program is
1156<a href="PETSC_DOC_OUT_ROOT_PLACEHOLDER/src/snes/tutorials/ex5f90.F90.html">SNES Tutorial ex5f90</a>;
1157see {any}`ch_snes` for a discussion of the
1158nonlinear solvers.
1159
1160(sec_vecghost)=
1161
1162### Global Vectors with locations for ghost values
1163
1164There are two minor drawbacks to the basic approach described above for unstructured grids:
1165
1166- the extra memory requirement for the local work vector, `localin`,
1167  which duplicates the local values in the memory in `globalin`, and
1168- the extra time required to copy the local values from `localin` to
1169  `globalin`.
1170
1171An alternative approach is to allocate global vectors with space
1172preallocated for the ghost values.
1173
1174```
1175VecCreateGhost(MPI_Comm comm,PetscInt n,PetscInt N,PetscInt nghost,PetscInt *ghosts,Vec *vv)
1176```
1177
1178or
1179
1180```
1181VecCreateGhostWithArray(MPI_Comm comm,PetscInt n,PetscInt N,PetscInt nghost,PetscInt *ghosts,PetscScalar *array,Vec *vv)
1182```
1183
1184Here `n` is the number of local vector entries, `N` is the number of
1185global entries (or `NULL`), and `nghost` is the number of ghost
1186entries. The array `ghosts` is of size `nghost` and contains the
1187global vector location for each local ghost location. Using
1188`VecDuplicate()` or `VecDuplicateVecs()` on a ghosted vector will
1189generate additional ghosted vectors.
1190
1191In many ways, a ghosted vector behaves like any other MPI vector
1192created by `VecCreateMPI()`. The difference is that the ghosted vector
1193has an additional “local” representation that allows one to access the
1194ghost locations. This is done through the call to
1195
1196```
1197VecGhostGetLocalForm(Vec g,Vec *l);
1198```
1199
1200The vector `l` is a sequential representation of the parallel vector
1201`g` that shares the same array space (and hence numerical values); but
1202allows one to access the “ghost” values past “the end of the” array.
1203Note that one accesses the entries in `l` using the local numbering of
1204elements and ghosts, while they are accessed in `g` using the global
1205numbering.
1206
1207A common usage of a ghosted vector is given by
1208
1209```
1210VecGhostUpdateBegin(Vec globalin,InsertMode INSERT_VALUES, ScatterMode SCATTER_FORWARD);
1211VecGhostUpdateEnd(Vec globalin,InsertMode INSERT_VALUES, ScatterMode SCATTER_FORWARD);
1212VecGhostGetLocalForm(Vec globalin,Vec *localin);
1213VecGhostGetLocalForm(Vec globalout,Vec *localout);
1214...  Do local calculations from localin to localout ...
1215VecGhostRestoreLocalForm(Vec globalin,Vec *localin);
1216VecGhostRestoreLocalForm(Vec globalout,Vec *localout);
1217VecGhostUpdateBegin(Vec globalout,InsertMode ADD_VALUES, ScatterMode SCATTER_REVERSE);
1218VecGhostUpdateEnd(Vec globalout,InsertMode ADD_VALUES, ScatterMode SCATTER_REVERSE);
1219```
1220
1221The routines `VecGhostUpdateBegin()` and `VecGhostUpdateEnd()` are
1222equivalent to the routines `VecScatterBegin()` and `VecScatterEnd()`
1223above, except that since they are scattering into the ghost locations,
1224they do not need to copy the local vector values, which are already in
1225place. In addition, the user does not have to allocate the local work
1226vector since the ghosted vector already has allocated slots to contain
1227the ghost values.
1228
1229The input arguments `INSERT_VALUES` and `SCATTER_FORWARD` cause the
1230ghost values to be correctly updated from the appropriate process. The
1231arguments `ADD_VALUES` and `SCATTER_REVERSE` update the “local”
1232portions of the vector from all the other processes’ ghost values. This
1233would be appropriate, for example, when performing a finite element
1234assembly of a load vector. One can also use `MAX_VALUES` or
1235`MIN_VALUES` with `SCATTER_REVERSE`.
1236
1237`DMPLEX` does not yet support ghosted vectors sharing memory with the global representation.
1238This is a work in progress; if you are interested in this feature, please contact the PETSc community members.
1239
1240{any}`sec_partitioning` discusses the important topic of
1241partitioning an unstructured grid.
1242
1243(sec_ao)=
1244
1245## Application Orderings
1246
1247When writing parallel PDE codes, there is extra complexity caused by
1248having multiple ways of indexing (numbering) and ordering objects such
1249as vertices and degrees of freedom. For example, a grid generator or
1250partitioner may renumber the nodes, requiring adjustment of the other
1251data structures that refer to these objects; see Figure
1252{any}`fig_daao`.
1253PETSc provides various tools to help manage the mapping amongst
1254the various numbering systems. The most basic is the `AO`
1255(application ordering), which enables mapping between different global
1256(cross-process) numbering schemes.
1257
1258In many applications, it is desirable to work with one or more
1259“orderings” (or numberings) of degrees of freedom, cells, nodes, etc.
1260Doing so in a parallel environment is complicated by the fact that each
1261process cannot keep complete lists of the mappings between different
1262orderings. In addition, the orderings used in the PETSc linear algebra
1263routines (often contiguous ranges) may not correspond to the “natural”
1264orderings for the application.
1265
1266PETSc provides certain utility routines that allow one to deal cleanly
1267and efficiently with the various orderings. To define a new application
1268ordering (called an `AO` in PETSc), one can call the routine
1269
1270```
1271AOCreateBasic(MPI_Comm comm,PetscInt n,const PetscInt apordering[],const PetscInt petscordering[],AO *ao);
1272```
1273
1274The arrays `apordering` and `petscordering`, respectively, contain a
1275list of integers in the application ordering and their corresponding
1276mapped values in the PETSc ordering. Each process can provide whatever
1277subset of the ordering it chooses, but multiple processes should never
1278contribute duplicate values. The argument `n` indicates the number of
1279local contributed values.
1280
1281For example, consider a vector of length 5, where node 0 in the
1282application ordering corresponds to node 3 in the PETSc ordering. In
1283addition, nodes 1, 2, 3, and 4 of the application ordering correspond,
1284respectively, to nodes 2, 1, 4, and 0 of the PETSc ordering. We can
1285write this correspondence as
1286
1287$$
1288\{ 0, 1, 2, 3, 4 \}  \to  \{ 3, 2, 1, 4, 0 \}.
1289$$
1290
1291The user can create the PETSc `AO` mappings in several ways. For
1292example, if using two processes, one could call
1293
1294```
1295AOCreateBasic(PETSC_COMM_WORLD,2,{0,3},{3,4},&ao);
1296```
1297
1298on the first process and
1299
1300```
1301AOCreateBasic(PETSC_COMM_WORLD,3,{1,2,4},{2,1,0},&ao);
1302```
1303
1304on the other process.
1305
1306Once the application ordering has been created, it can be used with
1307either of the commands
1308
1309```
1310AOPetscToApplication(AO ao,PetscInt n,PetscInt *indices);
1311AOApplicationToPetsc(AO ao,PetscInt n,PetscInt *indices);
1312```
1313
1314Upon input, the `n`-dimensional array `indices` specifies the
1315indices to be mapped, while upon output, `indices` contains the mapped
1316values. Since we, in general, employ a parallel database for the `AO`
1317mappings, it is crucial that all processes that called
1318`AOCreateBasic()` also call these routines; these routines *cannot* be
1319called by just a subset of processes in the MPI communicator that was
1320used in the call to `AOCreateBasic()`.
1321
1322An alternative routine to create the application ordering, `AO`, is
1323
1324```
1325AOCreateBasicIS(IS apordering,IS petscordering,AO *ao);
1326```
1327
1328where index sets are used
1329instead of integer arrays.
1330
1331The mapping routines
1332
1333```
1334AOPetscToApplicationIS(AO ao,IS indices);
1335AOApplicationToPetscIS(AO ao,IS indices);
1336```
1337
1338will map index sets (`IS` objects) between orderings. Both the
1339`AOXxxToYyy()` and `AOXxxToYyyIS()` routines can be used regardless
1340of whether the `AO` was created with a `AOCreateBasic()` or
1341`AOCreateBasicIS()`.
1342
1343The `AO` context should be destroyed with `AODestroy(AO *ao)` and
1344viewed with `AOView(AO ao,PetscViewer viewer)`.
1345
1346Although we refer to the two orderings as “PETSc” and “application”
1347orderings, the user is free to use them both for application orderings
1348and to maintain relationships among a variety of orderings by employing
1349several `AO` contexts.
1350
1351The `AOxxToxx()` routines allow negative entries in the input integer
1352array. These entries are not mapped; they remain unchanged. This
1353functionality enables, for example, mapping neighbor lists that use
1354negative numbers to indicate nonexistent neighbors due to boundary
1355conditions, etc.
1356
1357Since the global ordering that PETSc uses to manage its parallel vectors
1358(and matrices) does not usually correspond to the “natural” ordering of
1359a two- or three-dimensional array, the `DMDA` structure provides an
1360application ordering `AO` (see {any}`sec_ao`) that maps
1361between the natural ordering on a rectangular grid and the ordering
1362PETSc uses to parallelize. This ordering context can be obtained with
1363the command
1364
1365```
1366DMDAGetAO(DM da,AO *ao);
1367```
1368
1369In Figure {any}`fig_daao`, we indicate the orderings for a
1370two-dimensional `DMDA`, divided among four processes.
1371
1372:::{figure} /images/manual/danumbering.*
1373:alt: Natural Ordering and PETSc Ordering for a 2D Distributed Array (Four Processes)
1374:name: fig_daao
1375
1376Natural Ordering and PETSc Ordering for a 2D Distributed Array (Four
1377Processes)
1378:::
1379