Date: 2025-03-29T05:58:55+00:00

Actual source code: ex12.c

      1: static char help[] = "Demonstrates VecStrideScatter() and VecStrideGather().\n\n";

      3: /*
      4:   Include "petscvec.h" so that we can use vectors.  Note that this file
      5:   automatically includes:
      6:      petscsys.h       - base PETSc routines   petscis.h     - index sets
      7:      petscviewer.h - viewers
      8: */

     10: #include <petscvec.h>

     12: int main(int argc, char **argv)
     13: {
     14:   Vec         v, s; /* vectors */
     15:   PetscInt    n   = 20;
     16:   PetscScalar one = 1.0;

     18:   PetscFunctionBeginUser;
     19:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
     20:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL));

     22:   /*
     23:       Create multi-component vector with 2 components
     24:   */
     25:   PetscCall(VecCreate(PETSC_COMM_WORLD, &v));
     26:   PetscCall(VecSetSizes(v, PETSC_DECIDE, n));
     27:   PetscCall(VecSetBlockSize(v, 2));
     28:   PetscCall(VecSetFromOptions(v));

     30:   /*
     31:       Create single-component vector
     32:   */
     33:   PetscCall(VecCreate(PETSC_COMM_WORLD, &s));
     34:   PetscCall(VecSetSizes(s, PETSC_DECIDE, n / 2));
     35:   PetscCall(VecSetFromOptions(s));

     37:   /*
     38:      Set the vectors to entries to a constant value.
     39:   */
     40:   PetscCall(VecSet(v, one));

     42:   /*
     43:      Get the first component from the multi-component vector to the single vector
     44:   */
     45:   PetscCall(VecStrideGather(v, 0, s, INSERT_VALUES));

     47:   PetscCall(VecView(s, PETSC_VIEWER_STDOUT_WORLD));

     49:   /*
     50:      Put the values back into the second component
     51:   */
     52:   PetscCall(VecStrideScatter(s, 1, v, ADD_VALUES));

     54:   PetscCall(VecView(v, PETSC_VIEWER_STDOUT_WORLD));

     56:   /*
     57:      Free work space.  All PETSc objects should be destroyed when they
     58:      are no longer needed.
     59:   */
     60:   PetscCall(VecDestroy(&v));
     61:   PetscCall(VecDestroy(&s));
     62:   PetscCall(PetscFinalize());
     63:   return 0;
     64: }

     66: /*TEST

     68:      test:
     69:        nsize: 2

     71: TEST*/