Actual source code: vector.c

petsc-master 2019-12-13
Report Typos and Errors
  1: /*
  2:      Provides the interface functions for vector operations that do NOT have PetscScalar/PetscReal in the signature
  3:    These are the vector functions the user calls.
  4: */
  5:  #include <petsc/private/vecimpl.h>

  7: /* Logging support */
  8: PetscClassId  VEC_CLASSID;
  9: PetscLogEvent VEC_View, VEC_Max, VEC_Min, VEC_Dot, VEC_MDot, VEC_TDot;
 10: PetscLogEvent VEC_Norm, VEC_Normalize, VEC_Scale, VEC_Copy, VEC_Set, VEC_AXPY, VEC_AYPX, VEC_WAXPY;
 11: PetscLogEvent VEC_MTDot, VEC_MAXPY, VEC_Swap, VEC_AssemblyBegin, VEC_ScatterBegin, VEC_ScatterEnd;
 12: PetscLogEvent VEC_AssemblyEnd, VEC_PointwiseMult, VEC_SetValues, VEC_Load;
 13: PetscLogEvent VEC_SetRandom, VEC_ReduceArithmetic, VEC_ReduceCommunication,VEC_ReduceBegin,VEC_ReduceEnd,VEC_Ops;
 14: PetscLogEvent VEC_DotNorm2, VEC_AXPBYPCZ;
 15: PetscLogEvent VEC_ViennaCLCopyFromGPU, VEC_ViennaCLCopyToGPU;
 16: PetscLogEvent VEC_CUDACopyFromGPU, VEC_CUDACopyToGPU;
 17: PetscLogEvent VEC_CUDACopyFromGPUSome, VEC_CUDACopyToGPUSome;

 19: /*@
 20:    VecStashGetInfo - Gets how many values are currently in the vector stash, i.e. need
 21:        to be communicated to other processors during the VecAssemblyBegin/End() process

 23:     Not collective

 25:    Input Parameter:
 26: .   vec - the vector

 28:    Output Parameters:
 29: +   nstash   - the size of the stash
 30: .   reallocs - the number of additional mallocs incurred.
 31: .   bnstash   - the size of the block stash
 32: -   breallocs - the number of additional mallocs incurred.in the block stash

 34:    Level: advanced

 36: .seealso: VecAssemblyBegin(), VecAssemblyEnd(), Vec, VecStashSetInitialSize(), VecStashView()

 38: @*/
 39: PetscErrorCode  VecStashGetInfo(Vec vec,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
 40: {

 44:   VecStashGetInfo_Private(&vec->stash,nstash,reallocs);
 45:   VecStashGetInfo_Private(&vec->bstash,bnstash,breallocs);
 46:   return(0);
 47: }

 49: /*@
 50:    VecSetLocalToGlobalMapping - Sets a local numbering to global numbering used
 51:    by the routine VecSetValuesLocal() to allow users to insert vector entries
 52:    using a local (per-processor) numbering.

 54:    Logically Collective on Vec

 56:    Input Parameters:
 57: +  x - vector
 58: -  mapping - mapping created with ISLocalToGlobalMappingCreate() or ISLocalToGlobalMappingCreateIS()

 60:    Notes:
 61:    All vectors obtained with VecDuplicate() from this vector inherit the same mapping.

 63:    Level: intermediate

 65: seealso:  VecAssemblyBegin(), VecAssemblyEnd(), VecSetValues(), VecSetValuesLocal(),
 66:            VecSetLocalToGlobalMapping(), VecSetValuesBlockedLocal()
 67: @*/
 68: PetscErrorCode  VecSetLocalToGlobalMapping(Vec x,ISLocalToGlobalMapping mapping)
 69: {


 76:   if (x->ops->setlocaltoglobalmapping) {
 77:     (*x->ops->setlocaltoglobalmapping)(x,mapping);
 78:   } else {
 79:     PetscLayoutSetISLocalToGlobalMapping(x->map,mapping);
 80:   }
 81:   return(0);
 82: }

 84: /*@
 85:    VecGetLocalToGlobalMapping - Gets the local-to-global numbering set by VecSetLocalToGlobalMapping()

 87:    Not Collective

 89:    Input Parameter:
 90: .  X - the vector

 92:    Output Parameter:
 93: .  mapping - the mapping

 95:    Level: advanced


 98: .seealso:  VecSetValuesLocal()
 99: @*/
100: PetscErrorCode VecGetLocalToGlobalMapping(Vec X,ISLocalToGlobalMapping *mapping)
101: {
106:   *mapping = X->map->mapping;
107:   return(0);
108: }

110: /*@
111:    VecAssemblyBegin - Begins assembling the vector.  This routine should
112:    be called after completing all calls to VecSetValues().

114:    Collective on Vec

116:    Input Parameter:
117: .  vec - the vector

119:    Level: beginner

121: .seealso: VecAssemblyEnd(), VecSetValues()
122: @*/
123: PetscErrorCode  VecAssemblyBegin(Vec vec)
124: {

130:   VecStashViewFromOptions(vec,NULL,"-vec_view_stash");
131:   PetscLogEventBegin(VEC_AssemblyBegin,vec,0,0,0);
132:   if (vec->ops->assemblybegin) {
133:     (*vec->ops->assemblybegin)(vec);
134:   }
135:   PetscLogEventEnd(VEC_AssemblyBegin,vec,0,0,0);
136:   PetscObjectStateIncrease((PetscObject)vec);
137:   return(0);
138: }

140: /*@
141:    VecAssemblyEnd - Completes assembling the vector.  This routine should
142:    be called after VecAssemblyBegin().

144:    Collective on Vec

146:    Input Parameter:
147: .  vec - the vector

149:    Options Database Keys:
150: +  -vec_view - Prints vector in ASCII format
151: .  -vec_view ::ascii_matlab - Prints vector in ASCII MATLAB format to stdout
152: .  -vec_view matlab:filename - Prints vector in MATLAB format to matlaboutput.mat
153: .  -vec_view draw - Activates vector viewing using drawing tools
154: .  -display <name> - Sets display name (default is host)
155: .  -draw_pause <sec> - Sets number of seconds to pause after display
156: -  -vec_view socket - Activates vector viewing using a socket

158:    Level: beginner

160: .seealso: VecAssemblyBegin(), VecSetValues()
161: @*/
162: PetscErrorCode  VecAssemblyEnd(Vec vec)
163: {

168:   PetscLogEventBegin(VEC_AssemblyEnd,vec,0,0,0);
170:   if (vec->ops->assemblyend) {
171:     (*vec->ops->assemblyend)(vec);
172:   }
173:   PetscLogEventEnd(VEC_AssemblyEnd,vec,0,0,0);
174:   VecViewFromOptions(vec,NULL,"-vec_view");
175:   return(0);
176: }

178: /*@
179:    VecPointwiseMax - Computes the componentwise maximum w_i = max(x_i, y_i).

181:    Logically Collective on Vec

183:    Input Parameters:
184: .  x, y  - the vectors

186:    Output Parameter:
187: .  w - the result

189:    Level: advanced

191:    Notes:
192:     any subset of the x, y, and w may be the same vector.
193:           For complex numbers compares only the real part

195: .seealso: VecPointwiseDivide(), VecPointwiseMult(), VecPointwiseMin(), VecPointwiseMaxAbs(), VecMaxPointwiseDivide()
196: @*/
197: PetscErrorCode  VecPointwiseMax(Vec w,Vec x,Vec y)
198: {

210:   VecCheckSameSize(w,1,x,2);
211:   VecCheckSameSize(w,1,y,3);
212:   (*w->ops->pointwisemax)(w,x,y);
213:   PetscObjectStateIncrease((PetscObject)w);
214:   return(0);
215: }


218: /*@
219:    VecPointwiseMin - Computes the componentwise minimum w_i = min(x_i, y_i).

221:    Logically Collective on Vec

223:    Input Parameters:
224: .  x, y  - the vectors

226:    Output Parameter:
227: .  w - the result

229:    Level: advanced

231:    Notes:
232:     any subset of the x, y, and w may be the same vector.
233:           For complex numbers compares only the real part

235: .seealso: VecPointwiseDivide(), VecPointwiseMult(), VecPointwiseMin(), VecPointwiseMaxAbs(), VecMaxPointwiseDivide()
236: @*/
237: PetscErrorCode  VecPointwiseMin(Vec w,Vec x,Vec y)
238: {

250:   VecCheckSameSize(w,1,x,2);
251:   VecCheckSameSize(w,1,y,3);
252:   (*w->ops->pointwisemin)(w,x,y);
253:   PetscObjectStateIncrease((PetscObject)w);
254:   return(0);
255: }

257: /*@
258:    VecPointwiseMaxAbs - Computes the componentwise maximum of the absolute values w_i = max(abs(x_i), abs(y_i)).

260:    Logically Collective on Vec

262:    Input Parameters:
263: .  x, y  - the vectors

265:    Output Parameter:
266: .  w - the result

268:    Level: advanced

270:    Notes:
271:     any subset of the x, y, and w may be the same vector.

273: .seealso: VecPointwiseDivide(), VecPointwiseMult(), VecPointwiseMin(), VecPointwiseMax(), VecMaxPointwiseDivide()
274: @*/
275: PetscErrorCode  VecPointwiseMaxAbs(Vec w,Vec x,Vec y)
276: {

288:   VecCheckSameSize(w,1,x,2);
289:   VecCheckSameSize(w,1,y,3);
290:   (*w->ops->pointwisemaxabs)(w,x,y);
291:   PetscObjectStateIncrease((PetscObject)w);
292:   return(0);
293: }

295: /*@
296:    VecPointwiseDivide - Computes the componentwise division w = x/y.

298:    Logically Collective on Vec

300:    Input Parameters:
301: .  x, y  - the vectors

303:    Output Parameter:
304: .  w - the result

306:    Level: advanced

308:    Notes:
309:     any subset of the x, y, and w may be the same vector.

311: .seealso: VecPointwiseMult(), VecPointwiseMax(), VecPointwiseMin(), VecPointwiseMaxAbs(), VecMaxPointwiseDivide()
312: @*/
313: PetscErrorCode  VecPointwiseDivide(Vec w,Vec x,Vec y)
314: {

326:   VecCheckSameSize(w,1,x,2);
327:   VecCheckSameSize(w,1,y,3);
328:   (*w->ops->pointwisedivide)(w,x,y);
329:   PetscObjectStateIncrease((PetscObject)w);
330:   return(0);
331: }


334: /*@
335:    VecDuplicate - Creates a new vector of the same type as an existing vector.

337:    Collective on Vec

339:    Input Parameters:
340: .  v - a vector to mimic

342:    Output Parameter:
343: .  newv - location to put new vector

345:    Notes:
346:    VecDuplicate() DOES NOT COPY the vector entries, but rather allocates storage
347:    for the new vector.  Use VecCopy() to copy a vector.

349:    Use VecDestroy() to free the space. Use VecDuplicateVecs() to get several
350:    vectors.

352:    Level: beginner

354: .seealso: VecDestroy(), VecDuplicateVecs(), VecCreate(), VecCopy()
355: @*/
356: PetscErrorCode  VecDuplicate(Vec v,Vec *newv)
357: {

364:   (*v->ops->duplicate)(v,newv);
365:   PetscObjectStateIncrease((PetscObject)*newv);
366:   return(0);
367: }

369: /*@
370:    VecDestroy - Destroys a vector.

372:    Collective on Vec

374:    Input Parameters:
375: .  v  - the vector

377:    Level: beginner

379: .seealso: VecDuplicate(), VecDestroyVecs()
380: @*/
381: PetscErrorCode  VecDestroy(Vec *v)
382: {

386:   if (!*v) return(0);
388:   if (--((PetscObject)(*v))->refct > 0) {*v = 0; return(0);}

390:   PetscObjectSAWsViewOff((PetscObject)*v);
391:   /* destroy the internal part */
392:   if ((*v)->ops->destroy) {
393:     (*(*v)->ops->destroy)(*v);
394:   }
395:   /* destroy the external/common part */
396:   PetscLayoutDestroy(&(*v)->map);
397:   PetscHeaderDestroy(v);
398:   return(0);
399: }

401: /*@C
402:    VecDuplicateVecs - Creates several vectors of the same type as an existing vector.

404:    Collective on Vec

406:    Input Parameters:
407: +  m - the number of vectors to obtain
408: -  v - a vector to mimic

410:    Output Parameter:
411: .  V - location to put pointer to array of vectors

413:    Notes:
414:    Use VecDestroyVecs() to free the space. Use VecDuplicate() to form a single
415:    vector.

417:    Fortran Note:
418:    The Fortran interface is slightly different from that given below, it
419:    requires one to pass in V a Vec (integer) array of size at least m.
420:    See the Fortran chapter of the users manual and petsc/src/vec/vec/examples for details.

422:    Level: intermediate

424: .seealso:  VecDestroyVecs(), VecDuplicate(), VecCreate(), VecDuplicateVecsF90()
425: @*/
426: PetscErrorCode  VecDuplicateVecs(Vec v,PetscInt m,Vec *V[])
427: {

434:   (*v->ops->duplicatevecs)(v,m,V);
435:   return(0);
436: }

438: /*@C
439:    VecDestroyVecs - Frees a block of vectors obtained with VecDuplicateVecs().

441:    Collective on Vec

443:    Input Parameters:
444: +  vv - pointer to pointer to array of vector pointers, if NULL no vectors are destroyed
445: -  m - the number of vectors previously obtained, if zero no vectors are destroyed

447:    Fortran Note:
448:    The Fortran interface is slightly different from that given below.
449:    See the Fortran chapter of the users manual

451:    Level: intermediate

453: .seealso: VecDuplicateVecs(), VecDestroyVecsf90()
454: @*/
455: PetscErrorCode  VecDestroyVecs(PetscInt m,Vec *vv[])
456: {

461:   if (m < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of vectors %D",m);
462:   if (!m || !*vv) {*vv  = NULL; return(0);}
465:   (*(**vv)->ops->destroyvecs)(m,*vv);
466:   *vv  = NULL;
467:   return(0);
468: }

470: /*@C
471:    VecViewFromOptions - View from Options

473:    Collective on Vec

475:    Input Parameters:
476: +  A - the vector
477: .  obj - Optional object
478: -  name - command line option

480:    Level: intermediate
481: .seealso:  Vec, VecView, PetscObjectViewFromOptions(), VecCreate()
482: @*/
483: PetscErrorCode  VecViewFromOptions(Vec A,PetscObject obj,const char name[])
484: {

489:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
490:   return(0);
491: }

493: /*@C
494:    VecView - Views a vector object.

496:    Collective on Vec

498:    Input Parameters:
499: +  vec - the vector
500: -  viewer - an optional visualization context

502:    Notes:
503:    The available visualization contexts include
504: +     PETSC_VIEWER_STDOUT_SELF - for sequential vectors
505: .     PETSC_VIEWER_STDOUT_WORLD - for parallel vectors created on PETSC_COMM_WORLD
506: -     PETSC_VIEWER_STDOUT_(comm) - for parallel vectors created on MPI communicator comm

508:    You can change the format the vector is printed using the
509:    option PetscViewerPushFormat().

511:    The user can open alternative viewers with
512: +    PetscViewerASCIIOpen() - Outputs vector to a specified file
513: .    PetscViewerBinaryOpen() - Outputs vector in binary to a
514:          specified file; corresponding input uses VecLoad()
515: .    PetscViewerDrawOpen() - Outputs vector to an X window display
516: .    PetscViewerSocketOpen() - Outputs vector to Socket viewer
517: -    PetscViewerHDF5Open() - Outputs vector to HDF5 file viewer 

519:    The user can call PetscViewerPushFormat() to specify the output
520:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
521:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
522: +    PETSC_VIEWER_DEFAULT - default, prints vector contents
523: .    PETSC_VIEWER_ASCII_MATLAB - prints vector contents in MATLAB format
524: .    PETSC_VIEWER_ASCII_INDEX - prints vector contents, including indices of vector elements
525: -    PETSC_VIEWER_ASCII_COMMON - prints vector contents, using a
526:          format common among all vector types

528:    Notes:
529:     You can pass any number of vector objects, or other PETSc objects to the same viewer.

531:    Notes for binary viewer: 
532:      If you pass multiple vectors to a binary viewer you can read them back in in the same order
533:      with VecLoad().

535:      If the blocksize of the vector is greater than one then you must provide a unique prefix to
536:      the vector with PetscObjectSetOptionsPrefix((PetscObject)vec,"uniqueprefix"); BEFORE calling VecView() on the
537:      vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize
538:      information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
539:      filename. If you copy the binary file, make sure you copy the associated .info file with it.
540:      
541:      See the manual page for VecLoad() on the exact format the binary viewer stores
542:      the values in the file.


545:    Notes for HDF5 Viewer: 
546:      The name of the Vec (given with PetscObjectSetName() is the name that is used
547:      for the object in the HDF5 file. If you wish to store the same Vec into multiple
548:      datasets in the same file (typically with different values), you must change its
549:      name each time before calling the VecView(). To load the same vector,
550:      the name of the Vec object passed to VecLoad() must be the same.
551:  
552:      If the block size of the vector is greater than 1 then it is used as the first dimension in the HDF5 array.
553:      If the function PetscViewerHDF5SetBaseDimension2()is called then even if the block size is one it will
554:      be used as the first dimension in the HDF5 array (that is the HDF5 array will always be two dimensional)
555:      See also PetscViewerHDF5SetTimestep() which adds an additional complication to reading and writing Vecs
556:      with the HDF5 viewer.
557:      
558:    Level: beginner


561: .seealso: PetscViewerASCIIOpen(), PetscViewerDrawOpen(), PetscDrawLGCreate(),
562:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), VecLoad(), PetscViewerCreate(),
563:           PetscRealView(), PetscScalarView(), PetscIntView(), PetscViewerHDF5SetTimestep()
564: @*/
565: PetscErrorCode  VecView(Vec vec,PetscViewer viewer)
566: {
567:   PetscErrorCode    ierr;
568:   PetscBool         iascii;
569:   PetscViewerFormat format;
570:   PetscMPIInt       size;

575:   if (!viewer) {
576:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec),&viewer);
577:   }
579:   PetscViewerGetFormat(viewer,&format);
580:   MPI_Comm_size(PetscObjectComm((PetscObject)vec),&size);
581:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);

583:   if (vec->stash.n || vec->bstash.n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call VecAssemblyBegin/End() before viewing this vector");

585:   PetscLogEventBegin(VEC_View,vec,viewer,0,0);
586:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
587:   if (iascii) {
588:     PetscInt rows,bs;

590:     PetscObjectPrintClassNamePrefixType((PetscObject)vec,viewer);
591:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
592:       PetscViewerASCIIPushTab(viewer);
593:       VecGetSize(vec,&rows);
594:       VecGetBlockSize(vec,&bs);
595:       if (bs != 1) {
596:         PetscViewerASCIIPrintf(viewer,"length=%D, bs=%D\n",rows,bs);
597:       } else {
598:         PetscViewerASCIIPrintf(viewer,"length=%D\n",rows);
599:       }
600:       PetscViewerASCIIPopTab(viewer);
601:     }
602:   }
603:   VecLockReadPush(vec);
604:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && vec->ops->viewnative) {
605:     (*vec->ops->viewnative)(vec,viewer);
606:   } else {
607:     (*vec->ops->view)(vec,viewer);
608:   }
609:   VecLockReadPop(vec);
610:   PetscLogEventEnd(VEC_View,vec,viewer,0,0);
611:   return(0);
612: }

614: #if defined(PETSC_USE_DEBUG)
615: #include <../src/sys/totalview/tv_data_display.h>
616: PETSC_UNUSED static int TV_display_type(const struct _p_Vec *v)
617: {
618:   const PetscScalar *values;
619:   char              type[32];
620:   PetscErrorCode    ierr;


623:   TV_add_row("Local rows", "int", &v->map->n);
624:   TV_add_row("Global rows", "int", &v->map->N);
625:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)v)->type_name);
626:   VecGetArrayRead((Vec)v,&values);
627:   PetscSNPrintf(type,32,"double[%d]",v->map->n);
628:   TV_add_row("values",type, values);
629:   VecRestoreArrayRead((Vec)v,&values);
630:   return TV_format_OK;
631: }
632: #endif

634: /*@
635:    VecGetSize - Returns the global number of elements of the vector.

637:    Not Collective

639:    Input Parameter:
640: .  x - the vector

642:    Output Parameters:
643: .  size - the global length of the vector

645:    Level: beginner

647: .seealso: VecGetLocalSize()
648: @*/
649: PetscErrorCode  VecGetSize(Vec x,PetscInt *size)
650: {

657:   (*x->ops->getsize)(x,size);
658:   return(0);
659: }

661: /*@
662:    VecGetLocalSize - Returns the number of elements of the vector stored
663:    in local memory. This routine may be implementation dependent, so use
664:    with care.

666:    Not Collective

668:    Input Parameter:
669: .  x - the vector

671:    Output Parameter:
672: .  size - the length of the local piece of the vector

674:    Level: beginner

676: .seealso: VecGetSize()
677: @*/
678: PetscErrorCode  VecGetLocalSize(Vec x,PetscInt *size)
679: {

686:   (*x->ops->getlocalsize)(x,size);
687:   return(0);
688: }

690: /*@C
691:    VecGetOwnershipRange - Returns the range of indices owned by
692:    this processor, assuming that the vectors are laid out with the
693:    first n1 elements on the first processor, next n2 elements on the
694:    second, etc.  For certain parallel layouts this range may not be
695:    well defined.

697:    Not Collective

699:    Input Parameter:
700: .  x - the vector

702:    Output Parameters:
703: +  low - the first local element, pass in NULL if not interested
704: -  high - one more than the last local element, pass in NULL if not interested

706:    Note:
707:    The high argument is one more than the last element stored locally.

709:    Fortran: PETSC_NULL_INTEGER should be used instead of NULL

711:    Level: beginner


714: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRanges(), VecGetOwnershipRanges()
715: @*/
716: PetscErrorCode  VecGetOwnershipRange(Vec x,PetscInt *low,PetscInt *high)
717: {
723:   if (low)  *low  = x->map->rstart;
724:   if (high) *high = x->map->rend;
725:   return(0);
726: }

728: /*@C
729:    VecGetOwnershipRanges - Returns the range of indices owned by EACH processor,
730:    assuming that the vectors are laid out with the
731:    first n1 elements on the first processor, next n2 elements on the
732:    second, etc.  For certain parallel layouts this range may not be
733:    well defined.

735:    Not Collective

737:    Input Parameter:
738: .  x - the vector

740:    Output Parameters:
741: .  range - array of length size+1 with the start and end+1 for each process

743:    Note:
744:    The high argument is one more than the last element stored locally.

746:    Fortran: You must PASS in an array of length size+1

748:    Level: beginner


751: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRanges(), VecGetOwnershipRange()
752: @*/
753: PetscErrorCode  VecGetOwnershipRanges(Vec x,const PetscInt *ranges[])
754: {

760:   PetscLayoutGetRanges(x->map,ranges);
761:   return(0);
762: }

764: /*@
765:    VecSetOption - Sets an option for controling a vector's behavior.

767:    Collective on Vec

769:    Input Parameter:
770: +  x - the vector
771: .  op - the option
772: -  flag - turn the option on or off

774:    Supported Options:
775: +     VEC_IGNORE_OFF_PROC_ENTRIES, which causes VecSetValues() to ignore
776:           entries destined to be stored on a separate processor. This can be used
777:           to eliminate the global reduction in the VecAssemblyXXXX() if you know
778:           that you have only used VecSetValues() to set local elements
779: .     VEC_IGNORE_NEGATIVE_INDICES, which means you can pass negative indices
780:           in ix in calls to VecSetValues() or VecGetValues(). These rows are simply
781:           ignored.
782: -     VEC_SUBSET_OFF_PROC_ENTRIES, which causes VecAssemblyBegin() to assume that the off-process
783:           entries will always be a subset (possibly equal) of the off-process entries set on the
784:           first assembly which had a true VEC_SUBSET_OFF_PROC_ENTRIES and the vector has not
785:           changed this flag afterwards. If this assembly is not such first assembly, then this
786:           assembly can reuse the communication pattern setup in that first assembly, thus avoiding
787:           a global reduction. Subsequent assemblies setting off-process values should use the same
788:           InsertMode as the first assembly.

790:    Developer Note:
791:    The InsertMode restriction could be removed by packing the stash messages out of place.

793:    Level: intermediate

795: @*/
796: PetscErrorCode  VecSetOption(Vec x,VecOption op,PetscBool flag)
797: {

803:   if (x->ops->setoption) {
804:     (*x->ops->setoption)(x,op,flag);
805:   }
806:   return(0);
807: }

809: /* Default routines for obtaining and releasing; */
810: /* may be used by any implementation */
811: PetscErrorCode VecDuplicateVecs_Default(Vec w,PetscInt m,Vec *V[])
812: {
814:   PetscInt       i;

819:   if (m <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"m must be > 0: m = %D",m);
820:   PetscMalloc1(m,V);
821:   for (i=0; i<m; i++) {VecDuplicate(w,*V+i);}
822:   return(0);
823: }

825: PetscErrorCode VecDestroyVecs_Default(PetscInt m,Vec v[])
826: {
828:   PetscInt       i;

832:   for (i=0; i<m; i++) {VecDestroy(&v[i]);}
833:   PetscFree(v);
834:   return(0);
835: }

837: /*@
838:    VecResetArray - Resets a vector to use its default memory. Call this
839:    after the use of VecPlaceArray().

841:    Not Collective

843:    Input Parameters:
844: .  vec - the vector

846:    Level: developer

848: .seealso: VecGetArray(), VecRestoreArray(), VecReplaceArray(), VecPlaceArray()

850: @*/
851: PetscErrorCode  VecResetArray(Vec vec)
852: {

858:   if (vec->ops->resetarray) {
859:     (*vec->ops->resetarray)(vec);
860:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot reset array in this type of vector");
861:   PetscObjectStateIncrease((PetscObject)vec);
862:   return(0);
863: }

865: /*@C
866:   VecLoad - Loads a vector that has been stored in binary or HDF5 format
867:   with VecView().

869:   Collective on PetscViewer

871:   Input Parameters:
872: + newvec - the newly loaded vector, this needs to have been created with VecCreate() or
873:            some related function before a call to VecLoad().
874: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen() or
875:            HDF5 file viewer, obtained from PetscViewerHDF5Open()

877:    Level: intermediate

879:   Notes:
880:   Defaults to the standard Seq or MPI Vec, if you want some other type of Vec call VecSetFromOptions()
881:   before calling this.

883:   The input file must contain the full global vector, as
884:   written by the routine VecView().

886:   If the type or size of newvec is not set before a call to VecLoad, PETSc
887:   sets the type and the local and global sizes. If type and/or
888:   sizes are already set, then the same are used.

890:   If using the binary viewer and the blocksize of the vector is greater than one then you must provide a unique prefix to
891:   the vector with PetscObjectSetOptionsPrefix((PetscObject)vec,"uniqueprefix"); BEFORE calling VecView() on the
892:   vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize
893:   information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
894:   filename. If you copy the binary file, make sure you copy the associated .info file with it.

896:   If using HDF5, you must assign the Vec the same name as was used in the Vec
897:   that was stored in the file using PetscObjectSetName(). Otherwise you will
898:   get the error message: "Cannot H5DOpen2() with Vec name NAMEOFOBJECT".

900:   If the HDF5 file contains a two dimensional array the first dimension is treated as the block size
901:   in loading the vector. Hence, for example, using Matlab notation h5create('vector.dat','/Test_Vec',[27 1]);
902:   will load a vector of size 27 and block size 27 thus resulting in all 27 entries being on the first process of
903:   vectors communicator and the rest of the processes having zero entries

905:   Notes for advanced users when using the binary viewer:
906:   Most users should not need to know the details of the binary storage
907:   format, since VecLoad() and VecView() completely hide these details.
908:   But for anyone who's interested, the standard binary vector storage
909:   format is
910: .vb
911:      PetscInt    VEC_FILE_CLASSID
912:      PetscInt    number of rows
913:      PetscScalar *values of all entries
914: .ve

916:    In addition, PETSc automatically uses byte swapping to work on all machines; the files
917:    are written ALWAYS using big-endian ordering. On small-endian machines the numbers
918:    are converted to the small-endian format when they are read in from the file.
919:    See PetscBinaryRead() and PetscBinaryWrite() to see how this may be done.

921: .seealso: PetscViewerBinaryOpen(), VecView(), MatLoad(), VecLoad()
922: @*/
923: PetscErrorCode  VecLoad(Vec newvec, PetscViewer viewer)
924: {
925:   PetscErrorCode    ierr;
926:   PetscBool         isbinary,ishdf5,isadios,isadios2;
927:   PetscViewerFormat format;

932:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
933:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,&ishdf5);
934:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERADIOS,&isadios);
935:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERADIOS,&isadios2);
936:   if (!isbinary && !ishdf5 && !isadios && !isadios2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

938:   PetscLogEventBegin(VEC_Load,viewer,0,0,0);
939:   if (!((PetscObject)newvec)->type_name && !newvec->ops->create) {
940:     VecSetType(newvec, VECSTANDARD);
941:   }
942:   PetscViewerGetFormat(viewer,&format);
943:   if (format == PETSC_VIEWER_NATIVE && newvec->ops->loadnative) {
944:     (*newvec->ops->loadnative)(newvec,viewer);
945:   } else {
946:     (*newvec->ops->load)(newvec,viewer);
947:   }
948:   PetscLogEventEnd(VEC_Load,viewer,0,0,0);
949:   return(0);
950: }


953: /*@
954:    VecReciprocal - Replaces each component of a vector by its reciprocal.

956:    Logically Collective on Vec

958:    Input Parameter:
959: .  vec - the vector

961:    Output Parameter:
962: .  vec - the vector reciprocal

964:    Level: intermediate

966: .seealso: VecLog(), VecExp(), VecSqrtAbs()

968: @*/
969: PetscErrorCode  VecReciprocal(Vec vec)
970: {

976:   if (vec->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");
977:   if (!vec->ops->reciprocal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Vector does not support reciprocal operation");
978:   (*vec->ops->reciprocal)(vec);
979:   PetscObjectStateIncrease((PetscObject)vec);
980:   return(0);
981: }

983: /*@C
984:     VecSetOperation - Allows user to set a vector operation.

986:    Logically Collective on Vec

988:     Input Parameters:
989: +   vec - the vector
990: .   op - the name of the operation
991: -   f - the function that provides the operation.

993:    Level: advanced

995:     Usage:
996: $      PetscErrorCode userview(Vec,PetscViewer);
997: $      VecCreateMPI(comm,m,M,&x);
998: $      VecSetOperation(x,VECOP_VIEW,(void(*)(void))userview);

1000:     Notes:
1001:     See the file include/petscvec.h for a complete list of matrix
1002:     operations, which all have the form VECOP_<OPERATION>, where
1003:     <OPERATION> is the name (in all capital letters) of the
1004:     user interface routine (e.g., VecView() -> VECOP_VIEW).

1006:     This function is not currently available from Fortran.

1008: .seealso: VecCreate(), MatShellSetOperation()
1009: @*/
1010: PetscErrorCode VecSetOperation(Vec vec,VecOperation op, void (*f)(void))
1011: {
1014:   if (op == VECOP_VIEW && !vec->ops->viewnative) {
1015:     vec->ops->viewnative = vec->ops->view;
1016:   } else if (op == VECOP_LOAD && !vec->ops->loadnative) {
1017:     vec->ops->loadnative = vec->ops->load;
1018:   }
1019:   (((void(**)(void))vec->ops)[(int)op]) = f;
1020:   return(0);
1021: }


1024: /*@
1025:    VecStashSetInitialSize - sets the sizes of the vec-stash, that is
1026:    used during the assembly process to store values that belong to
1027:    other processors.

1029:    Not Collective, different processes can have different size stashes

1031:    Input Parameters:
1032: +  vec   - the vector
1033: .  size  - the initial size of the stash.
1034: -  bsize - the initial size of the block-stash(if used).

1036:    Options Database Keys:
1037: +   -vecstash_initial_size <size> or <size0,size1,...sizep-1>
1038: -   -vecstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>

1040:    Level: intermediate

1042:    Notes:
1043:      The block-stash is used for values set with VecSetValuesBlocked() while
1044:      the stash is used for values set with VecSetValues()

1046:      Run with the option -info and look for output of the form
1047:      VecAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
1048:      to determine the appropriate value, MM, to use for size and
1049:      VecAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
1050:      to determine the value, BMM to use for bsize


1053: .seealso: VecSetBlockSize(), VecSetValues(), VecSetValuesBlocked(), VecStashView()

1055: @*/
1056: PetscErrorCode  VecStashSetInitialSize(Vec vec,PetscInt size,PetscInt bsize)
1057: {

1062:   VecStashSetInitialSize_Private(&vec->stash,size);
1063:   VecStashSetInitialSize_Private(&vec->bstash,bsize);
1064:   return(0);
1065: }

1067: /*@
1068:    VecConjugate - Conjugates a vector.

1070:    Logically Collective on Vec

1072:    Input Parameters:
1073: .  x - the vector

1075:    Level: intermediate

1077: @*/
1078: PetscErrorCode  VecConjugate(Vec x)
1079: {
1080: #if defined(PETSC_USE_COMPLEX)

1086:   if (x->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");
1087:   (*x->ops->conjugate)(x);
1088:   /* we need to copy norms here */
1089:   PetscObjectStateIncrease((PetscObject)x);
1090:   return(0);
1091: #else
1092:   return(0);
1093: #endif
1094: }

1096: /*@
1097:    VecPointwiseMult - Computes the componentwise multiplication w = x*y.

1099:    Logically Collective on Vec

1101:    Input Parameters:
1102: .  x, y  - the vectors

1104:    Output Parameter:
1105: .  w - the result

1107:    Level: advanced

1109:    Notes:
1110:     any subset of the x, y, and w may be the same vector.

1112: .seealso: VecPointwiseDivide(), VecPointwiseMax(), VecPointwiseMin(), VecPointwiseMaxAbs(), VecMaxPointwiseDivide()
1113: @*/
1114: PetscErrorCode  VecPointwiseMult(Vec w, Vec x,Vec y)
1115: {

1127:   VecCheckSameSize(w,1,x,2);
1128:   VecCheckSameSize(w,2,y,3);
1129:   PetscLogEventBegin(VEC_PointwiseMult,x,y,w,0);
1130:   (*w->ops->pointwisemult)(w,x,y);
1131:   PetscLogEventEnd(VEC_PointwiseMult,x,y,w,0);
1132:   PetscObjectStateIncrease((PetscObject)w);
1133:   return(0);
1134: }

1136: /*@
1137:    VecSetRandom - Sets all components of a vector to random numbers.

1139:    Logically Collective on Vec

1141:    Input Parameters:
1142: +  x  - the vector
1143: -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
1144:           it will create one internally.

1146:    Output Parameter:
1147: .  x  - the vector

1149:    Example of Usage:
1150: .vb
1151:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
1152:      VecSetRandom(x,rctx);
1153:      PetscRandomDestroy(rctx);
1154: .ve

1156:    Level: intermediate


1159: .seealso: VecSet(), VecSetValues(), PetscRandomCreate(), PetscRandomDestroy()
1160: @*/
1161: PetscErrorCode  VecSetRandom(Vec x,PetscRandom rctx)
1162: {
1164:   PetscRandom    randObj = NULL;

1170:   if (x->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");

1172:   if (!rctx) {
1173:     MPI_Comm comm;
1174:     PetscObjectGetComm((PetscObject)x,&comm);
1175:     PetscRandomCreate(comm,&randObj);
1176:     PetscRandomSetFromOptions(randObj);
1177:     rctx = randObj;
1178:   }

1180:   PetscLogEventBegin(VEC_SetRandom,x,rctx,0,0);
1181:   (*x->ops->setrandom)(x,rctx);
1182:   PetscLogEventEnd(VEC_SetRandom,x,rctx,0,0);

1184:   PetscRandomDestroy(&randObj);
1185:   PetscObjectStateIncrease((PetscObject)x);
1186:   return(0);
1187: }

1189: /*@
1190:   VecZeroEntries - puts a 0.0 in each element of a vector

1192:   Logically Collective on Vec

1194:   Input Parameter:
1195: . vec - The vector

1197:   Level: beginner

1199:   Developer Note: This routine does not need to exist since the exact functionality is obtained with
1200:      VecSet(vec,0);  I guess someone added it to mirror the functionality of MatZeroEntries() but Mat is nothing
1201:      like a Vec (one is an operator and one is an element of a vector space, yeah yeah dual blah blah blah) so
1202:      this routine should not exist.

1204: .seealso: VecCreate(),  VecSetOptionsPrefix(), VecSet(), VecSetValues()
1205: @*/
1206: PetscErrorCode  VecZeroEntries(Vec vec)
1207: {

1211:   VecSet(vec,0);
1212:   return(0);
1213: }

1215: /*
1216:   VecSetTypeFromOptions_Private - Sets the type of vector from user options. Defaults to a PETSc sequential vector on one
1217:   processor and a PETSc MPI vector on more than one processor.

1219:   Collective on Vec

1221:   Input Parameter:
1222: . vec - The vector

1224:   Level: intermediate

1226: .seealso: VecSetFromOptions(), VecSetType()
1227: */
1228: static PetscErrorCode VecSetTypeFromOptions_Private(PetscOptionItems *PetscOptionsObject,Vec vec)
1229: {
1230:   PetscBool      opt;
1231:   VecType        defaultType;
1232:   char           typeName[256];
1233:   PetscMPIInt    size;

1237:   if (((PetscObject)vec)->type_name) defaultType = ((PetscObject)vec)->type_name;
1238:   else {
1239:     MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size);
1240:     if (size > 1) defaultType = VECMPI;
1241:     else defaultType = VECSEQ;
1242:   }

1244:   VecRegisterAll();
1245:   PetscOptionsFList("-vec_type","Vector type","VecSetType",VecList,defaultType,typeName,256,&opt);
1246:   if (opt) {
1247:     VecSetType(vec, typeName);
1248:   } else {
1249:     VecSetType(vec, defaultType);
1250:   }
1251:   return(0);
1252: }

1254: /*@
1255:   VecSetFromOptions - Configures the vector from the options database.

1257:   Collective on Vec

1259:   Input Parameter:
1260: . vec - The vector

1262:   Notes:
1263:     To see all options, run your program with the -help option, or consult the users manual.
1264:           Must be called after VecCreate() but before the vector is used.

1266:   Level: beginner


1269: .seealso: VecCreate(), VecSetOptionsPrefix()
1270: @*/
1271: PetscErrorCode  VecSetFromOptions(Vec vec)
1272: {


1278:   PetscObjectOptionsBegin((PetscObject)vec);
1279:   /* Handle vector type options */
1280:   VecSetTypeFromOptions_Private(PetscOptionsObject,vec);

1282:   /* Handle specific vector options */
1283:   if (vec->ops->setfromoptions) {
1284:     (*vec->ops->setfromoptions)(PetscOptionsObject,vec);
1285:   }

1287:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1288:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)vec);
1289:   PetscOptionsEnd();
1290:   return(0);
1291: }

1293: /*@
1294:   VecSetSizes - Sets the local and global sizes, and checks to determine compatibility

1296:   Collective on Vec

1298:   Input Parameters:
1299: + v - the vector
1300: . n - the local size (or PETSC_DECIDE to have it set)
1301: - N - the global size (or PETSC_DECIDE)

1303:   Notes:
1304:   n and N cannot be both PETSC_DECIDE
1305:   If one processor calls this with N of PETSC_DECIDE then all processors must, otherwise the program will hang.

1307:   Level: intermediate

1309: .seealso: VecGetSize(), PetscSplitOwnership()
1310: @*/
1311: PetscErrorCode  VecSetSizes(Vec v, PetscInt n, PetscInt N)
1312: {

1318:   if (N >= 0 && n > N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Local size %D cannot be larger than global size %D",n,N);
1319:   if ((v->map->n >= 0 || v->map->N >= 0) && (v->map->n != n || v->map->N != N)) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot change/reset vector sizes to %D local %D global after previously setting them to %D local %D global",n,N,v->map->n,v->map->N);
1320:   v->map->n = n;
1321:   v->map->N = N;
1322:   if (v->ops->create) {
1323:     (*v->ops->create)(v);
1324:     v->ops->create = 0;
1325:   }
1326:   return(0);
1327: }

1329: /*@
1330:    VecSetBlockSize - Sets the blocksize for future calls to VecSetValuesBlocked()
1331:    and VecSetValuesBlockedLocal().

1333:    Logically Collective on Vec

1335:    Input Parameter:
1336: +  v - the vector
1337: -  bs - the blocksize

1339:    Notes:
1340:    All vectors obtained by VecDuplicate() inherit the same blocksize.

1342:    Level: advanced

1344: .seealso: VecSetValuesBlocked(), VecSetLocalToGlobalMapping(), VecGetBlockSize()

1346: @*/
1347: PetscErrorCode  VecSetBlockSize(Vec v,PetscInt bs)
1348: {

1353:   if (bs < 0 || bs == v->map->bs) return(0);
1355:   PetscLayoutSetBlockSize(v->map,bs);
1356:   v->bstash.bs = bs; /* use the same blocksize for the vec's block-stash */
1357:   return(0);
1358: }

1360: /*@
1361:    VecGetBlockSize - Gets the blocksize for the vector, i.e. what is used for VecSetValuesBlocked()
1362:    and VecSetValuesBlockedLocal().

1364:    Not Collective

1366:    Input Parameter:
1367: .  v - the vector

1369:    Output Parameter:
1370: .  bs - the blocksize

1372:    Notes:
1373:    All vectors obtained by VecDuplicate() inherit the same blocksize.

1375:    Level: advanced

1377: .seealso: VecSetValuesBlocked(), VecSetLocalToGlobalMapping(), VecSetBlockSize()


1380: @*/
1381: PetscErrorCode  VecGetBlockSize(Vec v,PetscInt *bs)
1382: {

1388:   PetscLayoutGetBlockSize(v->map,bs);
1389:   return(0);
1390: }

1392: /*@C
1393:    VecSetOptionsPrefix - Sets the prefix used for searching for all
1394:    Vec options in the database.

1396:    Logically Collective on Vec

1398:    Input Parameter:
1399: +  v - the Vec context
1400: -  prefix - the prefix to prepend to all option names

1402:    Notes:
1403:    A hyphen (-) must NOT be given at the beginning of the prefix name.
1404:    The first character of all runtime options is AUTOMATICALLY the hyphen.

1406:    Level: advanced

1408: .seealso: VecSetFromOptions()
1409: @*/
1410: PetscErrorCode  VecSetOptionsPrefix(Vec v,const char prefix[])
1411: {

1416:   PetscObjectSetOptionsPrefix((PetscObject)v,prefix);
1417:   return(0);
1418: }

1420: /*@C
1421:    VecAppendOptionsPrefix - Appends to the prefix used for searching for all
1422:    Vec options in the database.

1424:    Logically Collective on Vec

1426:    Input Parameters:
1427: +  v - the Vec context
1428: -  prefix - the prefix to prepend to all option names

1430:    Notes:
1431:    A hyphen (-) must NOT be given at the beginning of the prefix name.
1432:    The first character of all runtime options is AUTOMATICALLY the hyphen.

1434:    Level: advanced

1436: .seealso: VecGetOptionsPrefix()
1437: @*/
1438: PetscErrorCode  VecAppendOptionsPrefix(Vec v,const char prefix[])
1439: {

1444:   PetscObjectAppendOptionsPrefix((PetscObject)v,prefix);
1445:   return(0);
1446: }

1448: /*@C
1449:    VecGetOptionsPrefix - Sets the prefix used for searching for all
1450:    Vec options in the database.

1452:    Not Collective

1454:    Input Parameter:
1455: .  v - the Vec context

1457:    Output Parameter:
1458: .  prefix - pointer to the prefix string used

1460:    Notes:
1461:     On the fortran side, the user should pass in a string 'prefix' of
1462:    sufficient length to hold the prefix.

1464:    Level: advanced

1466: .seealso: VecAppendOptionsPrefix()
1467: @*/
1468: PetscErrorCode  VecGetOptionsPrefix(Vec v,const char *prefix[])
1469: {

1474:   PetscObjectGetOptionsPrefix((PetscObject)v,prefix);
1475:   return(0);
1476: }

1478: /*@
1479:    VecSetUp - Sets up the internal vector data structures for the later use.

1481:    Collective on Vec

1483:    Input Parameters:
1484: .  v - the Vec context

1486:    Notes:
1487:    For basic use of the Vec classes the user need not explicitly call
1488:    VecSetUp(), since these actions will happen automatically.

1490:    Level: advanced

1492: .seealso: VecCreate(), VecDestroy()
1493: @*/
1494: PetscErrorCode  VecSetUp(Vec v)
1495: {
1496:   PetscMPIInt    size;

1501:   if (v->map->n < 0 && v->map->N < 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Sizes not set");
1502:   if (!((PetscObject)v)->type_name) {
1503:     MPI_Comm_size(PetscObjectComm((PetscObject)v), &size);
1504:     if (size == 1) {
1505:       VecSetType(v, VECSEQ);
1506:     } else {
1507:       VecSetType(v, VECMPI);
1508:     }
1509:   }
1510:   return(0);
1511: }

1513: /*
1514:     These currently expose the PetscScalar/PetscReal in updating the
1515:     cached norm. If we push those down into the implementation these
1516:     will become independent of PetscScalar/PetscReal
1517: */

1519: /*@
1520:    VecCopy - Copies a vector. y <- x

1522:    Logically Collective on Vec

1524:    Input Parameter:
1525: .  x - the vector

1527:    Output Parameter:
1528: .  y - the copy

1530:    Notes:
1531:    For default parallel PETSc vectors, both x and y must be distributed in
1532:    the same manner; local copies are done.

1534:    Developer Notes:
1536:    of the vectors to be sequential and one to be parallel so long as both have the same
1537:    local sizes. This is used in some internal functions in PETSc.

1539:    Level: beginner

1541: .seealso: VecDuplicate()
1542: @*/
1543: PetscErrorCode  VecCopy(Vec x,Vec y)
1544: {
1545:   PetscBool      flgs[4];
1546:   PetscReal      norms[4] = {0.0,0.0,0.0,0.0};
1548:   PetscInt       i;

1555:   if (x == y) return(0);
1556:   VecCheckSameLocalSize(x,1,y,2);
1557:   if (x->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");
1558:   VecSetErrorIfLocked(y,2);

1560: #if !defined(PETSC_USE_MIXED_PRECISION)
1561:   for (i=0; i<4; i++) {
1562:     PetscObjectComposedDataGetReal((PetscObject)x,NormIds[i],norms[i],flgs[i]);
1563:   }
1564: #endif

1566:   PetscLogEventBegin(VEC_Copy,x,y,0,0);
1567: #if defined(PETSC_USE_MIXED_PRECISION)
1568:   extern PetscErrorCode VecGetArray(Vec,double**);
1569:   extern PetscErrorCode VecRestoreArray(Vec,double**);
1570:   extern PetscErrorCode VecGetArray(Vec,float**);
1571:   extern PetscErrorCode VecRestoreArray(Vec,float**);
1572:   extern PetscErrorCode VecGetArrayRead(Vec,const double**);
1573:   extern PetscErrorCode VecRestoreArrayRead(Vec,const double**);
1574:   extern PetscErrorCode VecGetArrayRead(Vec,const float**);
1575:   extern PetscErrorCode VecRestoreArrayRead(Vec,const float**);
1576:   if ((((PetscObject)x)->precision == PETSC_PRECISION_SINGLE) && (((PetscObject)y)->precision == PETSC_PRECISION_DOUBLE)) {
1577:     PetscInt    i,n;
1578:     const float *xx;
1579:     double      *yy;
1580:     VecGetArrayRead(x,&xx);
1581:     VecGetArray(y,&yy);
1582:     VecGetLocalSize(x,&n);
1583:     for (i=0; i<n; i++) yy[i] = xx[i];
1584:     VecRestoreArrayRead(x,&xx);
1585:     VecRestoreArray(y,&yy);
1586:   } else if ((((PetscObject)x)->precision == PETSC_PRECISION_DOUBLE) && (((PetscObject)y)->precision == PETSC_PRECISION_SINGLE)) {
1587:     PetscInt     i,n;
1588:     float        *yy;
1589:     const double *xx;
1590:     VecGetArrayRead(x,&xx);
1591:     VecGetArray(y,&yy);
1592:     VecGetLocalSize(x,&n);
1593:     for (i=0; i<n; i++) yy[i] = (float) xx[i];
1594:     VecRestoreArrayRead(x,&xx);
1595:     VecRestoreArray(y,&yy);
1596:   } else {
1597:     (*x->ops->copy)(x,y);
1598:   }
1599: #else
1600:   (*x->ops->copy)(x,y);
1601: #endif

1603:   PetscObjectStateIncrease((PetscObject)y);
1604: #if !defined(PETSC_USE_MIXED_PRECISION)
1605:   for (i=0; i<4; i++) {
1606:     if (flgs[i]) {
1607:       PetscObjectComposedDataSetReal((PetscObject)y,NormIds[i],norms[i]);
1608:     }
1609:   }
1610: #endif

1612:   PetscLogEventEnd(VEC_Copy,x,y,0,0);
1613:   return(0);
1614: }

1616: /*@
1617:    VecSwap - Swaps the vectors x and y.

1619:    Logically Collective on Vec

1621:    Input Parameters:
1622: .  x, y  - the vectors

1624:    Level: advanced

1626: @*/
1627: PetscErrorCode  VecSwap(Vec x,Vec y)
1628: {
1629:   PetscReal      normxs[4]={0.0,0.0,0.0,0.0},normys[4]={0.0,0.0,0.0,0.0};
1630:   PetscBool      flgxs[4],flgys[4];
1632:   PetscInt       i;

1640:   VecCheckSameSize(x,1,y,2);
1641:   if (x->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");
1642:   if (y->stash.insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled vector");

1644:   PetscLogEventBegin(VEC_Swap,x,y,0,0);
1645:   for (i=0; i<4; i++) {
1646:     PetscObjectComposedDataGetReal((PetscObject)x,NormIds[i],normxs[i],flgxs[i]);
1647:     PetscObjectComposedDataGetReal((PetscObject)y,NormIds[i],normys[i],flgys[i]);
1648:   }
1649:   (*x->ops->swap)(x,y);
1650:   PetscObjectStateIncrease((PetscObject)x);
1651:   PetscObjectStateIncrease((PetscObject)y);
1652:   for (i=0; i<4; i++) {
1653:     if (flgxs[i]) {
1654:       PetscObjectComposedDataSetReal((PetscObject)y,NormIds[i],normxs[i]);
1655:     }
1656:     if (flgys[i]) {
1657:       PetscObjectComposedDataSetReal((PetscObject)x,NormIds[i],normys[i]);
1658:     }
1659:   }
1660:   PetscLogEventEnd(VEC_Swap,x,y,0,0);
1661:   return(0);
1662: }

1664: /*
1665:   VecStashViewFromOptions - Processes command line options to determine if/how an VecStash object is to be viewed.

1667:   Collective on VecStash

1669:   Input Parameters:
1670: + obj   - the VecStash object
1671: . bobj - optional other object that provides the prefix
1672: - optionname - option to activate viewing

1674:   Level: intermediate

1676:   Developer Note: This cannot use PetscObjectViewFromOptions() because it takes a Vec as an argument but does not use VecView

1678: */
1679: PetscErrorCode VecStashViewFromOptions(Vec obj,PetscObject bobj,const char optionname[])
1680: {
1681:   PetscErrorCode    ierr;
1682:   PetscViewer       viewer;
1683:   PetscBool         flg;
1684:   PetscViewerFormat format;
1685:   char              *prefix;

1688:   prefix = bobj ? bobj->prefix : ((PetscObject)obj)->prefix;
1689:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)obj),((PetscObject)obj)->options,prefix,optionname,&viewer,&format,&flg);
1690:   if (flg) {
1691:     PetscViewerPushFormat(viewer,format);
1692:     VecStashView(obj,viewer);
1693:     PetscViewerPopFormat(viewer);
1694:     PetscViewerDestroy(&viewer);
1695:   }
1696:   return(0);
1697: }

1699: /*@
1700:    VecStashView - Prints the entries in the vector stash and block stash.

1702:    Collective on Vec

1704:    Input Parameters:
1705: +  v - the vector
1706: -  viewer - the viewer

1708:    Level: advanced


1711: .seealso: VecSetBlockSize(), VecSetValues(), VecSetValuesBlocked()

1713: @*/
1714: PetscErrorCode  VecStashView(Vec v,PetscViewer viewer)
1715: {
1717:   PetscMPIInt    rank;
1718:   PetscInt       i,j;
1719:   PetscBool      match;
1720:   VecStash       *s;
1721:   PetscScalar    val;


1728:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&match);
1729:   if (!match) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Stash viewer only works with ASCII viewer not %s\n",((PetscObject)v)->type_name);
1730:   PetscViewerASCIIUseTabs(viewer,PETSC_FALSE);
1731:   MPI_Comm_rank(PetscObjectComm((PetscObject)v),&rank);
1732:   s    = &v->bstash;

1734:   /* print block stash */
1735:   PetscViewerASCIIPushSynchronized(viewer);
1736:   PetscViewerASCIISynchronizedPrintf(viewer,"[%d]Vector Block stash size %D block size %D\n",rank,s->n,s->bs);
1737:   for (i=0; i<s->n; i++) {
1738:     PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Element %D ",rank,s->idx[i]);
1739:     for (j=0; j<s->bs; j++) {
1740:       val = s->array[i*s->bs+j];
1741: #if defined(PETSC_USE_COMPLEX)
1742:       PetscViewerASCIISynchronizedPrintf(viewer,"(%18.16e %18.16e) ",PetscRealPart(val),PetscImaginaryPart(val));
1743: #else
1744:       PetscViewerASCIISynchronizedPrintf(viewer,"%18.16e ",val);
1745: #endif
1746:     }
1747:     PetscViewerASCIISynchronizedPrintf(viewer,"\n");
1748:   }
1749:   PetscViewerFlush(viewer);

1751:   s = &v->stash;

1753:   /* print basic stash */
1754:   PetscViewerASCIISynchronizedPrintf(viewer,"[%d]Vector stash size %D\n",rank,s->n);
1755:   for (i=0; i<s->n; i++) {
1756:     val = s->array[i];
1757: #if defined(PETSC_USE_COMPLEX)
1758:     PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Element %D (%18.16e %18.16e) ",rank,s->idx[i],PetscRealPart(val),PetscImaginaryPart(val));
1759: #else
1760:     PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Element %D %18.16e\n",rank,s->idx[i],val);
1761: #endif
1762:   }
1763:   PetscViewerFlush(viewer);
1764:   PetscViewerASCIIPopSynchronized(viewer);
1765:   PetscViewerASCIIUseTabs(viewer,PETSC_TRUE);
1766:   return(0);
1767: }

1769: PetscErrorCode PetscOptionsGetVec(PetscOptions options,const char prefix[],const char key[],Vec v,PetscBool *set)
1770: {
1771:   PetscInt       i,N,rstart,rend;
1773:   PetscScalar    *xx;
1774:   PetscReal      *xreal;
1775:   PetscBool      iset;

1778:   VecGetOwnershipRange(v,&rstart,&rend);
1779:   VecGetSize(v,&N);
1780:   PetscCalloc1(N,&xreal);
1781:   PetscOptionsGetRealArray(options,prefix,key,xreal,&N,&iset);
1782:   if (iset) {
1783:     VecGetArray(v,&xx);
1784:     for (i=rstart; i<rend; i++) xx[i-rstart] = xreal[i];
1785:     VecRestoreArray(v,&xx);
1786:   }
1787:   PetscFree(xreal);
1788:   if (set) *set = iset;
1789:   return(0);
1790: }

1792: /*@
1793:    VecGetLayout - get PetscLayout describing vector layout

1795:    Not Collective

1797:    Input Arguments:
1798: .  x - the vector

1800:    Output Arguments:
1801: .  map - the layout

1803:    Level: developer

1805: .seealso: VecGetSizes(), VecGetOwnershipRange(), VecGetOwnershipRanges()
1806: @*/
1807: PetscErrorCode VecGetLayout(Vec x,PetscLayout *map)
1808: {

1812:   *map = x->map;
1813:   return(0);
1814: }

1816: /*@
1817:    VecSetLayout - set PetscLayout describing vector layout

1819:    Not Collective

1821:    Input Arguments:
1822: +  x - the vector
1823: -  map - the layout

1825:    Notes:
1826:    It is normally only valid to replace the layout with a layout known to be equivalent.

1828:    Level: developer

1830: .seealso: VecGetLayout(), VecGetSizes(), VecGetOwnershipRange(), VecGetOwnershipRanges()
1831: @*/
1832: PetscErrorCode VecSetLayout(Vec x,PetscLayout map)
1833: {

1838:   PetscLayoutReference(map,&x->map);
1839:   return(0);
1840: }

1842: PetscErrorCode VecSetInf(Vec xin)
1843: {
1844:   PetscInt       i,n = xin->map->n;
1845:   PetscScalar    *xx;
1846:   PetscScalar    zero=0.0,one=1.0,inf=one/zero;

1850:   VecGetArray(xin,&xx);
1851:   for (i=0; i<n; i++) xx[i] = inf;
1852:   VecRestoreArray(xin,&xx);
1853:   return(0);
1854: }

1856: /*@
1857:      VecPinToCPU - marks a vector to temporarily stay on the CPU and perform computations on the CPU

1859:    Input Parameters:
1860: +   v - the vector
1861: -   flg - pin to the CPU if value of PETSC_TRUE

1863:    Level: intermediate
1864: @*/
1865: PetscErrorCode VecPinToCPU(Vec v,PetscBool flg)
1866: {
1867: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)

1871:   if (v->pinnedtocpu == flg) return(0);
1872:   v->pinnedtocpu = flg;
1873:   if (v->ops->pintocpu) {
1874:     (*v->ops->pintocpu)(v,flg);
1875:   }
1876:   return(0);
1877: #else
1878:   return 0;
1879: #endif
1880: }