Actual source code: vector.c
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>
6: #include <petsc/private/deviceimpl.h>
8: /* Logging support */
9: PetscClassId VEC_CLASSID;
10: PetscLogEvent VEC_View, VEC_Max, VEC_Min, VEC_Dot, VEC_MDot, VEC_TDot;
11: PetscLogEvent VEC_Norm, VEC_Normalize, VEC_Scale, VEC_Copy, VEC_Set, VEC_AXPY, VEC_AYPX, VEC_WAXPY;
12: PetscLogEvent VEC_MTDot, VEC_MAXPY, VEC_Swap, VEC_AssemblyBegin, VEC_ScatterBegin, VEC_ScatterEnd;
13: PetscLogEvent VEC_AssemblyEnd, VEC_PointwiseMult, VEC_SetValues, VEC_Load, VEC_SetPreallocateCOO, VEC_SetValuesCOO;
14: PetscLogEvent VEC_SetRandom, VEC_ReduceArithmetic, VEC_ReduceCommunication, VEC_ReduceBegin, VEC_ReduceEnd, VEC_Ops;
15: PetscLogEvent VEC_DotNorm2, VEC_AXPBYPCZ;
16: PetscLogEvent VEC_ViennaCLCopyFromGPU, VEC_ViennaCLCopyToGPU;
17: PetscLogEvent VEC_CUDACopyFromGPU, VEC_CUDACopyToGPU;
18: PetscLogEvent VEC_CUDACopyFromGPUSome, VEC_CUDACopyToGPUSome;
19: PetscLogEvent VEC_HIPCopyFromGPU, VEC_HIPCopyToGPU;
20: PetscLogEvent VEC_HIPCopyFromGPUSome, VEC_HIPCopyToGPUSome;
22: /*@
23: VecStashGetInfo - Gets how many values are currently in the vector stash, i.e. need
24: to be communicated to other processors during the VecAssemblyBegin/End() process
26: Not collective
28: Input Parameter:
29: . vec - the vector
31: Output Parameters:
32: + nstash - the size of the stash
33: . reallocs - the number of additional mallocs incurred.
34: . bnstash - the size of the block stash
35: - breallocs - the number of additional mallocs incurred.in the block stash
37: Level: advanced
39: .seealso: `VecAssemblyBegin()`, `VecAssemblyEnd()`, `Vec`, `VecStashSetInitialSize()`, `VecStashView()`
41: @*/
42: PetscErrorCode VecStashGetInfo(Vec vec, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
43: {
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: {
72: if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, mapping);
73: else PetscLayoutSetISLocalToGlobalMapping(x->map, mapping);
74: return 0;
75: }
77: /*@
78: VecGetLocalToGlobalMapping - Gets the local-to-global numbering set by VecSetLocalToGlobalMapping()
80: Not Collective
82: Input Parameter:
83: . X - the vector
85: Output Parameter:
86: . mapping - the mapping
88: Level: advanced
90: .seealso: `VecSetValuesLocal()`
91: @*/
92: PetscErrorCode VecGetLocalToGlobalMapping(Vec X, ISLocalToGlobalMapping *mapping)
93: {
97: *mapping = X->map->mapping;
98: return 0;
99: }
101: /*@
102: VecAssemblyBegin - Begins assembling the vector. This routine should
103: be called after completing all calls to VecSetValues().
105: Collective on Vec
107: Input Parameter:
108: . vec - the vector
110: Level: beginner
112: .seealso: `VecAssemblyEnd()`, `VecSetValues()`
113: @*/
114: PetscErrorCode VecAssemblyBegin(Vec vec)
115: {
118: VecStashViewFromOptions(vec, NULL, "-vec_view_stash");
119: PetscLogEventBegin(VEC_AssemblyBegin, vec, 0, 0, 0);
120: PetscTryTypeMethod(vec, assemblybegin);
121: PetscLogEventEnd(VEC_AssemblyBegin, vec, 0, 0, 0);
122: PetscObjectStateIncrease((PetscObject)vec);
123: return 0;
124: }
126: /*@
127: VecAssemblyEnd - Completes assembling the vector. This routine should
128: be called after VecAssemblyBegin().
130: Collective on Vec
132: Input Parameter:
133: . vec - the vector
135: Options Database Keys:
136: + -vec_view - Prints vector in ASCII format
137: . -vec_view ::ascii_matlab - Prints vector in ASCII MATLAB format to stdout
138: . -vec_view matlab:filename - Prints vector in MATLAB format to filename (requires PETSc configured with --with-matlab)
139: . -vec_view draw - Activates vector viewing using drawing tools
140: . -display <name> - Sets display name (default is host)
141: . -draw_pause <sec> - Sets number of seconds to pause after display
142: - -vec_view socket - Activates vector viewing using a socket
144: Level: beginner
146: .seealso: `VecAssemblyBegin()`, `VecSetValues()`
147: @*/
148: PetscErrorCode VecAssemblyEnd(Vec vec)
149: {
151: PetscLogEventBegin(VEC_AssemblyEnd, vec, 0, 0, 0);
153: PetscTryTypeMethod(vec, assemblyend);
154: PetscLogEventEnd(VEC_AssemblyEnd, vec, 0, 0, 0);
155: VecViewFromOptions(vec, NULL, "-vec_view");
156: return 0;
157: }
159: /*@
160: VecSetPreallocationCOO - set preallocation for a vector using a coordinate format of the entries with global indices
162: Collective on Vec
164: Input Parameters:
165: + x - vector being preallocated
166: . ncoo - number of entries
167: - coo_i - entry indices
169: Level: beginner
171: Notes:
172: Entries can be repeated, see VecSetValuesCOO(). Negative indices are not allowed unless vector option VEC_IGNORE_NEGATIVE_INDICES is set,
173: in which case they, along with the corresponding entries in VecSetValuesCOO(), are ignored. If vector option VEC_NO_OFF_PROC_ENTRIES is set,
174: remote entries are ignored, otherwise, they will be properly added or inserted to the vector.
176: The array coo_i[] may be freed immediately after calling this function.
178: .seealso: VecSetValuesCOO(), VecSetPreallocationCOOLocal()
179: @*/
180: PetscErrorCode VecSetPreallocationCOO(Vec x, PetscCount ncoo, const PetscInt coo_i[])
181: {
185: PetscLogEventBegin(VEC_SetPreallocateCOO, x, 0, 0, 0);
186: PetscLayoutSetUp(x->map);
187: if (x->ops->setpreallocationcoo) {
188: PetscUseTypeMethod(x, setpreallocationcoo, ncoo, coo_i);
189: } else {
190: IS is_coo_i;
191: /* The default implementation only supports ncoo within limit of PetscInt */
193: ISCreateGeneral(PETSC_COMM_SELF, ncoo, coo_i, PETSC_COPY_VALUES, &is_coo_i);
194: PetscObjectCompose((PetscObject)x, "__PETSc_coo_i", (PetscObject)is_coo_i);
195: ISDestroy(&is_coo_i);
196: }
197: PetscLogEventEnd(VEC_SetPreallocateCOO, x, 0, 0, 0);
198: return 0;
199: }
201: /*@
202: VecSetPreallocationCOOLocal - set preallocation for vectors using a coordinate format of the entries with local indices
204: Collective on Mat
206: Input Parameters:
207: + x - vector being preallocated
208: . ncoo - number of entries
209: - coo_i - row indices (local numbering; may be modified)
211: Level: beginner
213: Notes:
214: The local indices are translated using the local to global mapping, thus VecSetLocalToGlobalMapping() must have been
215: called prior to this function.
217: The indices coo_i may be modified within this function. They might be translated to corresponding global
218: indices, but the caller should not rely on them having any specific value after this function returns. The arrays
219: can be freed or reused immediately after this function returns.
221: Entries can be repeated. Negative indices and remote indices might be allowed. see VecSetPreallocationCOO().
223: .seealso: VecSetPreallocationCOO(), VecSetValuesCOO()
224: @*/
225: PetscErrorCode VecSetPreallocationCOOLocal(Vec x, PetscCount ncoo, PetscInt coo_i[])
226: {
227: ISLocalToGlobalMapping ltog;
233: PetscLayoutSetUp(x->map);
234: VecGetLocalToGlobalMapping(x, <og);
235: if (ltog) ISLocalToGlobalMappingApply(ltog, ncoo, coo_i, coo_i);
236: VecSetPreallocationCOO(x, ncoo, coo_i);
237: return 0;
238: }
240: /*@
241: VecSetValuesCOO - set values at once in a vector preallocated using VecSetPreallocationCOO()
243: Collective on Vec
245: Input Parameters:
246: + x - vector being set
247: . coo_v - the value array
248: - imode - the insert mode
250: Level: beginner
252: Notes: The values must follow the order of the indices prescribed with VecSetPreallocationCOO() or VecSetPreallocationCOOLocal().
253: When repeated entries are specified in the COO indices the coo_v values are first properly summed, regardless of the value of imode.
254: The imode flag indicates if coo_v must be added to the current values of the vector (ADD_VALUES) or overwritten (INSERT_VALUES).
255: VecAssemblyBegin() and VecAssemblyEnd() do not need to be called after this routine. It automatically handles the assembly process.
257: .seealso: VecSetPreallocationCOO(), VecSetPreallocationCOOLocal(), VecSetValues()
258: @*/
259: PetscErrorCode VecSetValuesCOO(Vec x, const PetscScalar coo_v[], InsertMode imode)
260: {
264: PetscLogEventBegin(VEC_SetValuesCOO, x, 0, 0, 0);
265: if (x->ops->setvaluescoo) {
266: PetscUseTypeMethod(x, setvaluescoo, coo_v, imode);
267: PetscObjectStateIncrease((PetscObject)x);
268: } else {
269: IS is_coo_i;
270: const PetscInt *coo_i;
271: PetscInt ncoo;
272: PetscMemType mtype;
274: PetscGetMemType(coo_v, &mtype);
276: PetscObjectQuery((PetscObject)x, "__PETSc_coo_i", (PetscObject *)&is_coo_i);
278: ISGetLocalSize(is_coo_i, &ncoo);
279: ISGetIndices(is_coo_i, &coo_i);
280: if (imode != ADD_VALUES) VecZeroEntries(x);
281: VecSetValues(x, ncoo, coo_i, coo_v, ADD_VALUES);
282: ISRestoreIndices(is_coo_i, &coo_i);
283: VecAssemblyBegin(x);
284: VecAssemblyEnd(x);
285: }
286: PetscLogEventEnd(VEC_SetValuesCOO, x, 0, 0, 0);
287: return 0;
288: }
290: static PetscErrorCode VecPointwiseApply_Private(Vec w, Vec x, Vec y, PetscLogEvent event, PetscErrorCode (*const pointwise_op)(Vec, Vec, Vec))
291: {
300: VecCheckSameSize(w, 1, x, 2);
301: VecCheckSameSize(w, 1, y, 3);
302: VecSetErrorIfLocked(w, 1);
305: if (event) PetscLogEventBegin(event, x, y, w, 0);
306: (*pointwise_op)(w, x, y);
307: if (event) PetscLogEventEnd(event, x, y, w, 0);
308: PetscObjectStateIncrease((PetscObject)w);
309: return 0;
310: }
312: /*@
313: VecPointwiseMax - Computes the componentwise maximum w_i = max(x_i, y_i).
315: Logically Collective on Vec
317: Input Parameters:
318: . x, y - the vectors
320: Output Parameter:
321: . w - the result
323: Level: advanced
325: Notes:
326: any subset of the x, y, and w may be the same vector.
327: For complex numbers compares only the real part
329: .seealso: `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
330: @*/
331: PetscErrorCode VecPointwiseMax(Vec w, Vec x, Vec y)
332: {
334: // REVIEW ME: no log event?
335: VecPointwiseApply_Private(w, x, y, 0, w->ops->pointwisemax);
336: return 0;
337: }
339: /*@
340: VecPointwiseMin - Computes the componentwise minimum w_i = min(x_i, y_i).
342: Logically Collective on Vec
344: Input Parameters:
345: . x, y - the vectors
347: Output Parameter:
348: . w - the result
350: Level: advanced
352: Notes:
353: any subset of the x, y, and w may be the same vector.
354: For complex numbers compares only the real part
356: .seealso: `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
357: @*/
358: PetscErrorCode VecPointwiseMin(Vec w, Vec x, Vec y)
359: {
361: // REVIEW ME: no log event?
362: VecPointwiseApply_Private(w, x, y, 0, w->ops->pointwisemin);
363: return 0;
364: }
366: /*@
367: VecPointwiseMaxAbs - Computes the componentwise maximum of the absolute values w_i = max(abs(x_i), abs(y_i)).
369: Logically Collective on Vec
371: Input Parameters:
372: . x, y - the vectors
374: Output Parameter:
375: . w - the result
377: Level: advanced
379: Notes:
380: any subset of the x, y, and w may be the same vector.
382: .seealso: `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMax()`, `VecMaxPointwiseDivide()`
383: @*/
384: PetscErrorCode VecPointwiseMaxAbs(Vec w, Vec x, Vec y)
385: {
387: // REVIEW ME: no log event?
388: VecPointwiseApply_Private(w, x, y, 0, w->ops->pointwisemaxabs);
389: return 0;
390: }
392: /*@
393: VecPointwiseDivide - Computes the componentwise division w = x/y.
395: Logically Collective on Vec
397: Input Parameters:
398: . x, y - the vectors
400: Output Parameter:
401: . w - the result
403: Level: advanced
405: Notes:
406: any subset of the x, y, and w may be the same vector.
408: .seealso: `VecPointwiseMult()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
409: @*/
410: PetscErrorCode VecPointwiseDivide(Vec w, Vec x, Vec y)
411: {
413: // REVIEW ME: no log event?
414: VecPointwiseApply_Private(w, x, y, 0, w->ops->pointwisedivide);
415: return 0;
416: }
418: /*@
419: VecPointwiseMult - Computes the componentwise multiplication w = x*y.
421: Logically Collective on Vec
423: Input Parameters:
424: . x, y - the vectors
426: Output Parameter:
427: . w - the result
429: Level: advanced
431: Notes:
432: any subset of the x, y, and w may be the same vector.
434: .seealso: `VecPointwiseDivide()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
435: @*/
436: PetscErrorCode VecPointwiseMult(Vec w, Vec x, Vec y)
437: {
439: VecPointwiseApply_Private(w, x, y, VEC_PointwiseMult, w->ops->pointwisemult);
440: return 0;
441: }
443: /*@
444: VecDuplicate - Creates a new vector of the same type as an existing vector.
446: Collective on Vec
448: Input Parameters:
449: . v - a vector to mimic
451: Output Parameter:
452: . newv - location to put new vector
454: Notes:
455: VecDuplicate() DOES NOT COPY the vector entries, but rather allocates storage
456: for the new vector. Use VecCopy() to copy a vector.
458: Use VecDestroy() to free the space. Use VecDuplicateVecs() to get several
459: vectors.
461: Level: beginner
463: .seealso: `VecDestroy()`, `VecDuplicateVecs()`, `VecCreate()`, `VecCopy()`
464: @*/
465: PetscErrorCode VecDuplicate(Vec v, Vec *newv)
466: {
470: PetscUseTypeMethod(v, duplicate, newv);
471: #if PetscDefined(HAVE_DEVICE)
472: if (v->boundtocpu && v->bindingpropagates) {
473: VecSetBindingPropagates(*newv, PETSC_TRUE);
474: VecBindToCPU(*newv, PETSC_TRUE);
475: }
476: #endif
477: PetscObjectStateIncrease((PetscObject)(*newv));
478: return 0;
479: }
481: /*@C
482: VecDestroy - Destroys a vector.
484: Collective on Vec
486: Input Parameters:
487: . v - the vector
489: Level: beginner
491: .seealso: `VecDuplicate()`, `VecDestroyVecs()`
492: @*/
493: PetscErrorCode VecDestroy(Vec *v)
494: {
496: if (!*v) return 0;
498: if (--((PetscObject)(*v))->refct > 0) {
499: *v = NULL;
500: return 0;
501: }
503: PetscObjectSAWsViewOff((PetscObject)*v);
504: /* destroy the internal part */
505: PetscTryTypeMethod(*v, destroy);
506: PetscFree((*v)->defaultrandtype);
507: /* destroy the external/common part */
508: PetscLayoutDestroy(&(*v)->map);
509: PetscHeaderDestroy(v);
510: return 0;
511: }
513: /*@C
514: VecDuplicateVecs - Creates several vectors of the same type as an existing vector.
516: Collective on Vec
518: Input Parameters:
519: + m - the number of vectors to obtain
520: - v - a vector to mimic
522: Output Parameter:
523: . V - location to put pointer to array of vectors
525: Notes:
526: Use VecDestroyVecs() to free the space. Use VecDuplicate() to form a single
527: vector.
529: Fortran Note:
530: The Fortran interface is slightly different from that given below, it
531: requires one to pass in V a Vec (integer) array of size at least m.
532: See the Fortran chapter of the users manual and petsc/src/vec/vec/examples for details.
534: Level: intermediate
536: .seealso: `VecDestroyVecs()`, `VecDuplicate()`, `VecCreate()`, `VecDuplicateVecsF90()`
537: @*/
538: PetscErrorCode VecDuplicateVecs(Vec v, PetscInt m, Vec *V[])
539: {
543: PetscUseTypeMethod(v, duplicatevecs, m, V);
544: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
545: if (v->boundtocpu && v->bindingpropagates) {
546: PetscInt i;
548: for (i = 0; i < m; i++) {
549: /* Since ops->duplicatevecs might itself propagate the value of boundtocpu,
550: * avoid unnecessary overhead by only calling VecBindToCPU() if the vector isn't already bound. */
551: if (!(*V)[i]->boundtocpu) {
552: VecSetBindingPropagates((*V)[i], PETSC_TRUE);
553: VecBindToCPU((*V)[i], PETSC_TRUE);
554: }
555: }
556: }
557: #endif
558: return 0;
559: }
561: /*@C
562: VecDestroyVecs - Frees a block of vectors obtained with VecDuplicateVecs().
564: Collective on Vec
566: Input Parameters:
567: + vv - pointer to pointer to array of vector pointers, if NULL no vectors are destroyed
568: - m - the number of vectors previously obtained, if zero no vectors are destroyed
570: Fortran Note:
571: The Fortran interface is slightly different from that given below.
572: See the Fortran chapter of the users manual
574: Level: intermediate
576: .seealso: `VecDuplicateVecs()`, `VecDestroyVecsf90()`
577: @*/
578: PetscErrorCode VecDestroyVecs(PetscInt m, Vec *vv[])
579: {
582: if (!m || !*vv) {
583: *vv = NULL;
584: return 0;
585: }
588: (*(**vv)->ops->destroyvecs)(m, *vv);
589: *vv = NULL;
590: return 0;
591: }
593: /*@C
594: VecViewFromOptions - View from Options
596: Collective on Vec
598: Input Parameters:
599: + A - the vector
600: . obj - Optional object
601: - name - command line option
603: Level: intermediate
604: .seealso: `Vec`, `VecView`, `PetscObjectViewFromOptions()`, `VecCreate()`
605: @*/
606: PetscErrorCode VecViewFromOptions(Vec A, PetscObject obj, const char name[])
607: {
609: PetscObjectViewFromOptions((PetscObject)A, obj, name);
610: return 0;
611: }
613: /*@C
614: VecView - Views a vector object.
616: Collective on Vec
618: Input Parameters:
619: + vec - the vector
620: - viewer - an optional visualization context
622: Notes:
623: The available visualization contexts include
624: + PETSC_VIEWER_STDOUT_SELF - for sequential vectors
625: . PETSC_VIEWER_STDOUT_WORLD - for parallel vectors created on PETSC_COMM_WORLD
626: - PETSC_VIEWER_STDOUT_(comm) - for parallel vectors created on MPI communicator comm
628: You can change the format the vector is printed using the
629: option PetscViewerPushFormat().
631: The user can open alternative viewers with
632: + PetscViewerASCIIOpen() - Outputs vector to a specified file
633: . PetscViewerBinaryOpen() - Outputs vector in binary to a
634: specified file; corresponding input uses VecLoad()
635: . PetscViewerDrawOpen() - Outputs vector to an X window display
636: . PetscViewerSocketOpen() - Outputs vector to Socket viewer
637: - PetscViewerHDF5Open() - Outputs vector to HDF5 file viewer
639: The user can call PetscViewerPushFormat() to specify the output
640: format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
641: PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen). Available formats include
642: + PETSC_VIEWER_DEFAULT - default, prints vector contents
643: . PETSC_VIEWER_ASCII_MATLAB - prints vector contents in MATLAB format
644: . PETSC_VIEWER_ASCII_INDEX - prints vector contents, including indices of vector elements
645: - PETSC_VIEWER_ASCII_COMMON - prints vector contents, using a
646: format common among all vector types
648: Notes:
649: You can pass any number of vector objects, or other PETSc objects to the same viewer.
651: In the debugger you can do "call VecView(v,0)" to display the vector. (The same holds for any PETSc object viewer).
653: Notes for binary viewer:
654: If you pass multiple vectors to a binary viewer you can read them back in in the same order
655: with VecLoad().
657: If the blocksize of the vector is greater than one then you must provide a unique prefix to
658: the vector with PetscObjectSetOptionsPrefix((PetscObject)vec,"uniqueprefix"); BEFORE calling VecView() on the
659: vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize
660: information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
661: filename. If you copy the binary file, make sure you copy the associated .info file with it.
663: See the manual page for VecLoad() on the exact format the binary viewer stores
664: the values in the file.
666: Notes for HDF5 Viewer:
667: The name of the Vec (given with PetscObjectSetName() is the name that is used
668: for the object in the HDF5 file. If you wish to store the same Vec into multiple
669: datasets in the same file (typically with different values), you must change its
670: name each time before calling the VecView(). To load the same vector,
671: the name of the Vec object passed to VecLoad() must be the same.
673: If the block size of the vector is greater than 1 then it is used as the first dimension in the HDF5 array.
674: If the function PetscViewerHDF5SetBaseDimension2()is called then even if the block size is one it will
675: be used as the first dimension in the HDF5 array (that is the HDF5 array will always be two dimensional)
676: See also PetscViewerHDF5SetTimestep() which adds an additional complication to reading and writing Vecs
677: with the HDF5 viewer.
679: Level: beginner
681: .seealso: `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`,
682: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
683: `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
684: @*/
685: PetscErrorCode VecView(Vec vec, PetscViewer viewer)
686: {
687: PetscBool iascii;
688: PetscViewerFormat format;
689: PetscMPIInt size;
693: if (!viewer) PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer);
695: PetscViewerGetFormat(viewer, &format);
696: MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size);
697: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return 0;
701: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii);
702: if (iascii) {
703: PetscInt rows, bs;
705: PetscObjectPrintClassNamePrefixType((PetscObject)vec, viewer);
706: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
707: PetscViewerASCIIPushTab(viewer);
708: VecGetSize(vec, &rows);
709: VecGetBlockSize(vec, &bs);
710: if (bs != 1) {
711: PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT ", bs=%" PetscInt_FMT "\n", rows, bs);
712: } else {
713: PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT "\n", rows);
714: }
715: PetscViewerASCIIPopTab(viewer);
716: }
717: }
718: VecLockReadPush(vec);
719: PetscLogEventBegin(VEC_View, vec, viewer, 0, 0);
720: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && vec->ops->viewnative) {
721: PetscUseTypeMethod(vec, viewnative, viewer);
722: } else {
723: PetscUseTypeMethod(vec, view, viewer);
724: }
725: VecLockReadPop(vec);
726: PetscLogEventEnd(VEC_View, vec, viewer, 0, 0);
727: return 0;
728: }
730: #if defined(PETSC_USE_DEBUG)
731: #include <../src/sys/totalview/tv_data_display.h>
732: PETSC_UNUSED static int TV_display_type(const struct _p_Vec *v)
733: {
734: const PetscScalar *values;
735: char type[32];
737: TV_add_row("Local rows", "int", &v->map->n);
738: TV_add_row("Global rows", "int", &v->map->N);
739: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)v)->type_name);
740: VecGetArrayRead((Vec)v, &values);
741: PetscSNPrintf(type, 32, "double[%" PetscInt_FMT "]", v->map->n);
742: TV_add_row("values", type, values);
743: VecRestoreArrayRead((Vec)v, &values);
744: return TV_format_OK;
745: }
746: #endif
748: /*@C
749: VecViewNative - Views a vector object with the original type specific viewer
751: Collective on Vec
753: Input Parameters:
754: + vec - the vector
755: - viewer - an optional visualization context
757: Level: developer
759: .seealso: `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`, `VecView()`
760: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
761: `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
762: @*/
763: PetscErrorCode VecViewNative(Vec vec, PetscViewer viewer)
764: {
767: if (!viewer) PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer);
769: PetscUseTypeMethod(vec, viewnative, viewer);
770: return 0;
771: }
773: /*@
774: VecGetSize - Returns the global number of elements of the vector.
776: Not Collective
778: Input Parameter:
779: . x - the vector
781: Output Parameters:
782: . size - the global length of the vector
784: Level: beginner
786: .seealso: `VecGetLocalSize()`
787: @*/
788: PetscErrorCode VecGetSize(Vec x, PetscInt *size)
789: {
793: PetscUseTypeMethod(x, getsize, size);
794: return 0;
795: }
797: /*@
798: VecGetLocalSize - Returns the number of elements of the vector stored
799: in local memory.
801: Not Collective
803: Input Parameter:
804: . x - the vector
806: Output Parameter:
807: . size - the length of the local piece of the vector
809: Level: beginner
811: .seealso: `VecGetSize()`
812: @*/
813: PetscErrorCode VecGetLocalSize(Vec x, PetscInt *size)
814: {
818: PetscUseTypeMethod(x, getlocalsize, size);
819: return 0;
820: }
822: /*@C
823: VecGetOwnershipRange - Returns the range of indices owned by
824: this processor, assuming that the vectors are laid out with the
825: first n1 elements on the first processor, next n2 elements on the
826: second, etc. For certain parallel layouts this range may not be
827: well defined.
829: Not Collective
831: Input Parameter:
832: . x - the vector
834: Output Parameters:
835: + low - the first local element, pass in NULL if not interested
836: - high - one more than the last local element, pass in NULL if not interested
838: Note:
839: The high argument is one more than the last element stored locally.
841: Fortran: PETSC_NULL_INTEGER should be used instead of NULL
843: Level: beginner
845: .seealso: `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRanges()`
846: @*/
847: PetscErrorCode VecGetOwnershipRange(Vec x, PetscInt *low, PetscInt *high)
848: {
853: if (low) *low = x->map->rstart;
854: if (high) *high = x->map->rend;
855: return 0;
856: }
858: /*@C
859: VecGetOwnershipRanges - Returns the range of indices owned by EACH processor,
860: assuming that the vectors are laid out with the
861: first n1 elements on the first processor, next n2 elements on the
862: second, etc. For certain parallel layouts this range may not be
863: well defined.
865: Not Collective
867: Input Parameter:
868: . x - the vector
870: Output Parameters:
871: . range - array of length size+1 with the start and end+1 for each process
873: Note:
874: The high argument is one more than the last element stored locally.
876: Fortran: You must PASS in an array of length size+1
878: If the ranges are used after all vectors that share the ranges has been destroyed then the program will crash accessing ranges[].
880: Level: beginner
882: .seealso: `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRange()`
883: @*/
884: PetscErrorCode VecGetOwnershipRanges(Vec x, const PetscInt *ranges[])
885: {
888: PetscLayoutGetRanges(x->map, ranges);
889: return 0;
890: }
892: /*@
893: VecSetOption - Sets an option for controling a vector's behavior.
895: Collective on Vec
897: Input Parameters:
898: + x - the vector
899: . op - the option
900: - flag - turn the option on or off
902: Supported Options:
903: + VEC_IGNORE_OFF_PROC_ENTRIES, which causes VecSetValues() to ignore
904: entries destined to be stored on a separate processor. This can be used
905: to eliminate the global reduction in the VecAssemblyXXXX() if you know
906: that you have only used VecSetValues() to set local elements
907: . VEC_IGNORE_NEGATIVE_INDICES, which means you can pass negative indices
908: in ix in calls to VecSetValues() or VecGetValues(). These rows are simply
909: ignored.
910: - VEC_SUBSET_OFF_PROC_ENTRIES, which causes VecAssemblyBegin() to assume that the off-process
911: entries will always be a subset (possibly equal) of the off-process entries set on the
912: first assembly which had a true VEC_SUBSET_OFF_PROC_ENTRIES and the vector has not
913: changed this flag afterwards. If this assembly is not such first assembly, then this
914: assembly can reuse the communication pattern setup in that first assembly, thus avoiding
915: a global reduction. Subsequent assemblies setting off-process values should use the same
916: InsertMode as the first assembly.
918: Developer Note:
919: The InsertMode restriction could be removed by packing the stash messages out of place.
921: Level: intermediate
923: @*/
924: PetscErrorCode VecSetOption(Vec x, VecOption op, PetscBool flag)
925: {
928: PetscTryTypeMethod(x, setoption, op, flag);
929: return 0;
930: }
932: /* Default routines for obtaining and releasing; */
933: /* may be used by any implementation */
934: PetscErrorCode VecDuplicateVecs_Default(Vec w, PetscInt m, Vec *V[])
935: {
939: PetscMalloc1(m, V);
940: for (PetscInt i = 0; i < m; i++) VecDuplicate(w, *V + i);
941: return 0;
942: }
944: PetscErrorCode VecDestroyVecs_Default(PetscInt m, Vec v[])
945: {
946: PetscInt i;
949: for (i = 0; i < m; i++) VecDestroy(&v[i]);
950: PetscFree(v);
951: return 0;
952: }
954: /*@
955: VecResetArray - Resets a vector to use its default memory. Call this
956: after the use of VecPlaceArray().
958: Not Collective
960: Input Parameters:
961: . vec - the vector
963: Level: developer
965: .seealso: `VecGetArray()`, `VecRestoreArray()`, `VecReplaceArray()`, `VecPlaceArray()`
967: @*/
968: PetscErrorCode VecResetArray(Vec vec)
969: {
972: PetscUseTypeMethod(vec, resetarray);
973: PetscObjectStateIncrease((PetscObject)vec);
974: return 0;
975: }
977: /*@C
978: VecLoad - Loads a vector that has been stored in binary or HDF5 format
979: with VecView().
981: Collective on PetscViewer
983: Input Parameters:
984: + vec - the newly loaded vector, this needs to have been created with VecCreate() or
985: some related function before a call to VecLoad().
986: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen() or
987: HDF5 file viewer, obtained from PetscViewerHDF5Open()
989: Level: intermediate
991: Notes:
992: Defaults to the standard Seq or MPI Vec, if you want some other type of Vec call VecSetFromOptions()
993: before calling this.
995: The input file must contain the full global vector, as
996: written by the routine VecView().
998: If the type or size of vec is not set before a call to VecLoad, PETSc
999: sets the type and the local and global sizes. If type and/or
1000: sizes are already set, then the same are used.
1002: If using the binary viewer and the blocksize of the vector is greater than one then you must provide a unique prefix to
1003: the vector with PetscObjectSetOptionsPrefix((PetscObject)vec,"uniqueprefix"); BEFORE calling VecView() on the
1004: vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize
1005: information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
1006: filename. If you copy the binary file, make sure you copy the associated .info file with it.
1008: If using HDF5, you must assign the Vec the same name as was used in the Vec
1009: that was stored in the file using PetscObjectSetName(). Otherwise you will
1010: get the error message: "Cannot H5DOpen2() with Vec name NAMEOFOBJECT".
1012: If the HDF5 file contains a two dimensional array the first dimension is treated as the block size
1013: in loading the vector. Hence, for example, using Matlab notation h5create('vector.dat','/Test_Vec',[27 1]);
1014: will load a vector of size 27 and block size 27 thus resulting in all 27 entries being on the first process of
1015: vectors communicator and the rest of the processes having zero entries
1017: Notes for advanced users when using the binary viewer:
1018: Most users should not need to know the details of the binary storage
1019: format, since VecLoad() and VecView() completely hide these details.
1020: But for anyone who's interested, the standard binary vector storage
1021: format is
1022: .vb
1023: PetscInt VEC_FILE_CLASSID
1024: PetscInt number of rows
1025: PetscScalar *values of all entries
1026: .ve
1028: In addition, PETSc automatically uses byte swapping to work on all machines; the files
1029: are written ALWAYS using big-endian ordering. On small-endian machines the numbers
1030: are converted to the small-endian format when they are read in from the file.
1031: See PetscBinaryRead() and PetscBinaryWrite() to see how this may be done.
1033: .seealso: `PetscViewerBinaryOpen()`, `VecView()`, `MatLoad()`, `VecLoad()`
1034: @*/
1035: PetscErrorCode VecLoad(Vec vec, PetscViewer viewer)
1036: {
1037: PetscBool isbinary, ishdf5, isadios, isexodusii;
1038: PetscViewerFormat format;
1043: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary);
1044: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5);
1045: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERADIOS, &isadios);
1046: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii);
1049: VecSetErrorIfLocked(vec, 1);
1050: if (!((PetscObject)vec)->type_name && !vec->ops->create) VecSetType(vec, VECSTANDARD);
1051: PetscLogEventBegin(VEC_Load, viewer, 0, 0, 0);
1052: PetscViewerGetFormat(viewer, &format);
1053: if (format == PETSC_VIEWER_NATIVE && vec->ops->loadnative) {
1054: PetscUseTypeMethod(vec, loadnative, viewer);
1055: } else {
1056: PetscUseTypeMethod(vec, load, viewer);
1057: }
1058: PetscLogEventEnd(VEC_Load, viewer, 0, 0, 0);
1059: return 0;
1060: }
1062: /*@
1063: VecReciprocal - Replaces each component of a vector by its reciprocal.
1065: Logically Collective on Vec
1067: Input Parameter:
1068: . vec - the vector
1070: Output Parameter:
1071: . vec - the vector reciprocal
1073: Level: intermediate
1075: .seealso: `VecLog()`, `VecExp()`, `VecSqrtAbs()`
1077: @*/
1078: PetscErrorCode VecReciprocal(Vec vec)
1079: {
1083: VecSetErrorIfLocked(vec, 1);
1084: PetscUseTypeMethod(vec, reciprocal);
1085: PetscObjectStateIncrease((PetscObject)vec);
1086: return 0;
1087: }
1089: /*@C
1090: VecSetOperation - Allows user to set a vector operation.
1092: Logically Collective on Vec
1094: Input Parameters:
1095: + vec - the vector
1096: . op - the name of the operation
1097: - f - the function that provides the operation.
1099: Level: advanced
1101: Usage:
1102: $ PetscErrorCode userview(Vec,PetscViewer);
1103: $ VecCreateMPI(comm,m,M,&x);
1104: $ VecSetOperation(x,VECOP_VIEW,(void(*)(void))userview);
1106: Notes:
1107: See the file include/petscvec.h for a complete list of matrix
1108: operations, which all have the form VECOP_<OPERATION>, where
1109: <OPERATION> is the name (in all capital letters) of the
1110: user interface routine (e.g., VecView() -> VECOP_VIEW).
1112: This function is not currently available from Fortran.
1114: .seealso: `VecCreate()`, `MatShellSetOperation()`
1115: @*/
1116: PetscErrorCode VecSetOperation(Vec vec, VecOperation op, void (*f)(void))
1117: {
1119: if (op == VECOP_VIEW && !vec->ops->viewnative) {
1120: vec->ops->viewnative = vec->ops->view;
1121: } else if (op == VECOP_LOAD && !vec->ops->loadnative) {
1122: vec->ops->loadnative = vec->ops->load;
1123: }
1124: (((void (**)(void))vec->ops)[(int)op]) = f;
1125: return 0;
1126: }
1128: /*@
1129: VecStashSetInitialSize - sets the sizes of the vec-stash, that is
1130: used during the assembly process to store values that belong to
1131: other processors.
1133: Not Collective, different processes can have different size stashes
1135: Input Parameters:
1136: + vec - the vector
1137: . size - the initial size of the stash.
1138: - bsize - the initial size of the block-stash(if used).
1140: Options Database Keys:
1141: + -vecstash_initial_size <size> or <size0,size1,...sizep-1>
1142: - -vecstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>
1144: Level: intermediate
1146: Notes:
1147: The block-stash is used for values set with VecSetValuesBlocked() while
1148: the stash is used for values set with VecSetValues()
1150: Run with the option -info and look for output of the form
1151: VecAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
1152: to determine the appropriate value, MM, to use for size and
1153: VecAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
1154: to determine the value, BMM to use for bsize
1156: .seealso: `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`, `VecStashView()`
1158: @*/
1159: PetscErrorCode VecStashSetInitialSize(Vec vec, PetscInt size, PetscInt bsize)
1160: {
1162: VecStashSetInitialSize_Private(&vec->stash, size);
1163: VecStashSetInitialSize_Private(&vec->bstash, bsize);
1164: return 0;
1165: }
1167: /*@
1168: VecConjugate - Conjugates a vector.
1170: Logically Collective on Vec
1172: Input Parameters:
1173: . x - the vector
1175: Level: intermediate
1177: @*/
1178: PetscErrorCode VecConjugate(Vec x)
1179: {
1183: VecSetErrorIfLocked(x, 1);
1184: if (PetscDefined(USE_COMPLEX)) {
1185: PetscUseTypeMethod(x, conjugate);
1186: /* we need to copy norms here */
1187: PetscObjectStateIncrease((PetscObject)x);
1188: }
1189: return 0;
1190: }
1192: /*@
1193: VecSetRandom - Sets all components of a vector to random numbers.
1195: Logically Collective on Vec
1197: Input Parameters:
1198: + x - the vector
1199: - rctx - the random number context, formed by PetscRandomCreate(), or NULL and
1200: it will create one internally.
1202: Output Parameter:
1203: . x - the vector
1205: Example of Usage:
1206: .vb
1207: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
1208: VecSetRandom(x,rctx);
1209: PetscRandomDestroy(&rctx);
1210: .ve
1212: Level: intermediate
1214: .seealso: `VecSet()`, `VecSetValues()`, `PetscRandomCreate()`, `PetscRandomDestroy()`
1215: @*/
1216: PetscErrorCode VecSetRandom(Vec x, PetscRandom rctx)
1217: {
1218: PetscRandom randObj = NULL;
1224: VecSetErrorIfLocked(x, 1);
1226: if (!rctx) {
1227: PetscRandomCreate(PetscObjectComm((PetscObject)x), &randObj);
1228: PetscRandomSetType(randObj, x->defaultrandtype);
1229: PetscRandomSetFromOptions(randObj);
1230: rctx = randObj;
1231: }
1233: PetscLogEventBegin(VEC_SetRandom, x, rctx, 0, 0);
1234: PetscUseTypeMethod(x, setrandom, rctx);
1235: PetscLogEventEnd(VEC_SetRandom, x, rctx, 0, 0);
1237: PetscRandomDestroy(&randObj);
1238: PetscObjectStateIncrease((PetscObject)x);
1239: return 0;
1240: }
1242: /*@
1243: VecZeroEntries - puts a 0.0 in each element of a vector
1245: Logically Collective on Vec
1247: Input Parameter:
1248: . vec - The vector
1250: Level: beginner
1252: .seealso: `VecCreate()`, `VecSetOptionsPrefix()`, `VecSet()`, `VecSetValues()`
1253: @*/
1254: PetscErrorCode VecZeroEntries(Vec vec)
1255: {
1256: VecSet(vec, 0);
1257: return 0;
1258: }
1260: /*
1261: VecSetTypeFromOptions_Private - Sets the type of vector from user options. Defaults to a PETSc sequential vector on one
1262: processor and a PETSc MPI vector on more than one processor.
1264: Collective on Vec
1266: Input Parameter:
1267: . vec - The vector
1269: Level: intermediate
1271: .seealso: `VecSetFromOptions()`, `VecSetType()`
1272: */
1273: static PetscErrorCode VecSetTypeFromOptions_Private(Vec vec, PetscOptionItems *PetscOptionsObject)
1274: {
1275: PetscBool opt;
1276: VecType defaultType;
1277: char typeName[256];
1278: PetscMPIInt size;
1280: if (((PetscObject)vec)->type_name) defaultType = ((PetscObject)vec)->type_name;
1281: else {
1282: MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size);
1283: if (size > 1) defaultType = VECMPI;
1284: else defaultType = VECSEQ;
1285: }
1287: VecRegisterAll();
1288: PetscOptionsFList("-vec_type", "Vector type", "VecSetType", VecList, defaultType, typeName, 256, &opt);
1289: if (opt) {
1290: VecSetType(vec, typeName);
1291: } else {
1292: VecSetType(vec, defaultType);
1293: }
1294: return 0;
1295: }
1297: /*@
1298: VecSetFromOptions - Configures the vector from the options database.
1300: Collective on Vec
1302: Input Parameter:
1303: . vec - The vector
1305: Notes:
1306: To see all options, run your program with the -help option, or consult the users manual.
1307: Must be called after VecCreate() but before the vector is used.
1309: Level: beginner
1311: .seealso: `VecCreate()`, `VecSetOptionsPrefix()`
1312: @*/
1313: PetscErrorCode VecSetFromOptions(Vec vec)
1314: {
1315: PetscBool flg;
1316: PetscInt bind_below = 0;
1320: PetscObjectOptionsBegin((PetscObject)vec);
1321: /* Handle vector type options */
1322: VecSetTypeFromOptions_Private(vec, PetscOptionsObject);
1324: /* Handle specific vector options */
1325: PetscTryTypeMethod(vec, setfromoptions, PetscOptionsObject);
1327: /* Bind to CPU if below a user-specified size threshold.
1328: * This perhaps belongs in the options for the GPU Vec types, but VecBindToCPU() does nothing when called on non-GPU types,
1329: * and putting it here makes is more maintainable than duplicating this for all. */
1330: PetscOptionsInt("-vec_bind_below", "Set the size threshold (in local entries) below which the Vec is bound to the CPU", "VecBindToCPU", bind_below, &bind_below, &flg);
1331: if (flg && vec->map->n < bind_below) VecBindToCPU(vec, PETSC_TRUE);
1333: /* process any options handlers added with PetscObjectAddOptionsHandler() */
1334: PetscObjectProcessOptionsHandlers((PetscObject)vec, PetscOptionsObject);
1335: PetscOptionsEnd();
1336: return 0;
1337: }
1339: /*@
1340: VecSetSizes - Sets the local and global sizes, and checks to determine compatibility
1342: Collective on Vec
1344: Input Parameters:
1345: + v - the vector
1346: . n - the local size (or PETSC_DECIDE to have it set)
1347: - N - the global size (or PETSC_DECIDE)
1349: Notes:
1350: n and N cannot be both PETSC_DECIDE
1351: If one processor calls this with N of PETSC_DECIDE then all processors must, otherwise the program will hang.
1353: Level: intermediate
1355: .seealso: `VecGetSize()`, `PetscSplitOwnership()`
1356: @*/
1357: PetscErrorCode VecSetSizes(Vec v, PetscInt n, PetscInt N)
1358: {
1360: if (N >= 0) {
1363: }
1365: v->map->n, v->map->N);
1366: v->map->n = n;
1367: v->map->N = N;
1368: PetscTryTypeMethod(v, create);
1369: v->ops->create = NULL;
1370: return 0;
1371: }
1373: /*@
1374: VecSetBlockSize - Sets the blocksize for future calls to VecSetValuesBlocked()
1375: and VecSetValuesBlockedLocal().
1377: Logically Collective on Vec
1379: Input Parameters:
1380: + v - the vector
1381: - bs - the blocksize
1383: Notes:
1384: All vectors obtained by VecDuplicate() inherit the same blocksize.
1386: Level: advanced
1388: .seealso: `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecGetBlockSize()`
1390: @*/
1391: PetscErrorCode VecSetBlockSize(Vec v, PetscInt bs)
1392: {
1395: PetscLayoutSetBlockSize(v->map, bs);
1396: v->bstash.bs = bs; /* use the same blocksize for the vec's block-stash */
1397: return 0;
1398: }
1400: /*@
1401: VecGetBlockSize - Gets the blocksize for the vector, i.e. what is used for VecSetValuesBlocked()
1402: and VecSetValuesBlockedLocal().
1404: Not Collective
1406: Input Parameter:
1407: . v - the vector
1409: Output Parameter:
1410: . bs - the blocksize
1412: Notes:
1413: All vectors obtained by VecDuplicate() inherit the same blocksize.
1415: Level: advanced
1417: .seealso: `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecSetBlockSize()`
1419: @*/
1420: PetscErrorCode VecGetBlockSize(Vec v, PetscInt *bs)
1421: {
1424: PetscLayoutGetBlockSize(v->map, bs);
1425: return 0;
1426: }
1428: /*@C
1429: VecSetOptionsPrefix - Sets the prefix used for searching for all
1430: Vec options in the database.
1432: Logically Collective on Vec
1434: Input Parameters:
1435: + v - the Vec context
1436: - prefix - the prefix to prepend to all option names
1438: Notes:
1439: A hyphen (-) must NOT be given at the beginning of the prefix name.
1440: The first character of all runtime options is AUTOMATICALLY the hyphen.
1442: Level: advanced
1444: .seealso: `VecSetFromOptions()`
1445: @*/
1446: PetscErrorCode VecSetOptionsPrefix(Vec v, const char prefix[])
1447: {
1449: PetscObjectSetOptionsPrefix((PetscObject)v, prefix);
1450: return 0;
1451: }
1453: /*@C
1454: VecAppendOptionsPrefix - Appends to the prefix used for searching for all
1455: Vec options in the database.
1457: Logically Collective on Vec
1459: Input Parameters:
1460: + v - the Vec context
1461: - prefix - the prefix to prepend to all option names
1463: Notes:
1464: A hyphen (-) must NOT be given at the beginning of the prefix name.
1465: The first character of all runtime options is AUTOMATICALLY the hyphen.
1467: Level: advanced
1469: .seealso: `VecGetOptionsPrefix()`
1470: @*/
1471: PetscErrorCode VecAppendOptionsPrefix(Vec v, const char prefix[])
1472: {
1474: PetscObjectAppendOptionsPrefix((PetscObject)v, prefix);
1475: return 0;
1476: }
1478: /*@C
1479: VecGetOptionsPrefix - Sets the prefix used for searching for all
1480: Vec options in the database.
1482: Not Collective
1484: Input Parameter:
1485: . v - the Vec context
1487: Output Parameter:
1488: . prefix - pointer to the prefix string used
1490: Notes:
1491: On the fortran side, the user should pass in a string 'prefix' of
1492: sufficient length to hold the prefix.
1494: Level: advanced
1496: .seealso: `VecAppendOptionsPrefix()`
1497: @*/
1498: PetscErrorCode VecGetOptionsPrefix(Vec v, const char *prefix[])
1499: {
1501: PetscObjectGetOptionsPrefix((PetscObject)v, prefix);
1502: return 0;
1503: }
1505: /*@
1506: VecSetUp - Sets up the internal vector data structures for the later use.
1508: Collective on Vec
1510: Input Parameters:
1511: . v - the Vec context
1513: Notes:
1514: For basic use of the Vec classes the user need not explicitly call
1515: VecSetUp(), since these actions will happen automatically.
1517: Level: advanced
1519: .seealso: `VecCreate()`, `VecDestroy()`
1520: @*/
1521: PetscErrorCode VecSetUp(Vec v)
1522: {
1523: PetscMPIInt size;
1527: if (!((PetscObject)v)->type_name) {
1528: MPI_Comm_size(PetscObjectComm((PetscObject)v), &size);
1529: if (size == 1) {
1530: VecSetType(v, VECSEQ);
1531: } else {
1532: VecSetType(v, VECMPI);
1533: }
1534: }
1535: return 0;
1536: }
1538: /*
1539: These currently expose the PetscScalar/PetscReal in updating the
1540: cached norm. If we push those down into the implementation these
1541: will become independent of PetscScalar/PetscReal
1542: */
1544: /*@
1545: VecCopy - Copies a vector. y <- x
1547: Logically Collective on Vec
1549: Input Parameter:
1550: . x - the vector
1552: Output Parameter:
1553: . y - the copy
1555: Notes:
1556: For default parallel PETSc vectors, both x and y must be distributed in
1557: the same manner; local copies are done.
1559: Developer Notes:
1561: of the vectors to be sequential and one to be parallel so long as both have the same
1562: local sizes. This is used in some internal functions in PETSc.
1564: Level: beginner
1566: .seealso: `VecDuplicate()`
1567: @*/
1568: PetscErrorCode VecCopy(Vec x, Vec y)
1569: {
1570: PetscBool flgs[4];
1571: PetscReal norms[4] = {0.0, 0.0, 0.0, 0.0};
1577: if (x == y) return 0;
1578: VecCheckSameLocalSize(x, 1, y, 2);
1580: VecSetErrorIfLocked(y, 2);
1582: #if !defined(PETSC_USE_MIXED_PRECISION)
1583: for (PetscInt i = 0; i < 4; i++) PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], norms[i], flgs[i]);
1584: #endif
1586: PetscLogEventBegin(VEC_Copy, x, y, 0, 0);
1587: #if defined(PETSC_USE_MIXED_PRECISION)
1588: extern PetscErrorCode VecGetArray(Vec, double **);
1589: extern PetscErrorCode VecRestoreArray(Vec, double **);
1590: extern PetscErrorCode VecGetArray(Vec, float **);
1591: extern PetscErrorCode VecRestoreArray(Vec, float **);
1592: extern PetscErrorCode VecGetArrayRead(Vec, const double **);
1593: extern PetscErrorCode VecRestoreArrayRead(Vec, const double **);
1594: extern PetscErrorCode VecGetArrayRead(Vec, const float **);
1595: extern PetscErrorCode VecRestoreArrayRead(Vec, const float **);
1596: if ((((PetscObject)x)->precision == PETSC_PRECISION_SINGLE) && (((PetscObject)y)->precision == PETSC_PRECISION_DOUBLE)) {
1597: PetscInt i, n;
1598: const float *xx;
1599: double *yy;
1600: VecGetArrayRead(x, &xx);
1601: VecGetArray(y, &yy);
1602: VecGetLocalSize(x, &n);
1603: for (i = 0; i < n; i++) yy[i] = xx[i];
1604: VecRestoreArrayRead(x, &xx);
1605: VecRestoreArray(y, &yy);
1606: } else if ((((PetscObject)x)->precision == PETSC_PRECISION_DOUBLE) && (((PetscObject)y)->precision == PETSC_PRECISION_SINGLE)) {
1607: PetscInt i, n;
1608: float *yy;
1609: const double *xx;
1610: VecGetArrayRead(x, &xx);
1611: VecGetArray(y, &yy);
1612: VecGetLocalSize(x, &n);
1613: for (i = 0; i < n; i++) yy[i] = (float)xx[i];
1614: VecRestoreArrayRead(x, &xx);
1615: VecRestoreArray(y, &yy);
1616: } else PetscUseTypeMethod(x, copy, y);
1617: #else
1618: PetscUseTypeMethod(x, copy, y);
1619: #endif
1621: PetscObjectStateIncrease((PetscObject)y);
1622: #if !defined(PETSC_USE_MIXED_PRECISION)
1623: for (PetscInt i = 0; i < 4; i++) {
1624: if (flgs[i]) PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], norms[i]);
1625: }
1626: #endif
1628: PetscLogEventEnd(VEC_Copy, x, y, 0, 0);
1629: return 0;
1630: }
1632: /*@
1633: VecSwap - Swaps the vectors x and y.
1635: Logically Collective on Vec
1637: Input Parameters:
1638: . x, y - the vectors
1640: Level: advanced
1642: @*/
1643: PetscErrorCode VecSwap(Vec x, Vec y)
1644: {
1645: PetscReal normxs[4], normys[4];
1646: PetscBool flgxs[4], flgys[4];
1653: VecCheckSameSize(x, 1, y, 2);
1656: VecSetErrorIfLocked(x, 1);
1657: VecSetErrorIfLocked(y, 2);
1659: for (PetscInt i = 0; i < 4; i++) {
1660: PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], normxs[i], flgxs[i]);
1661: PetscObjectComposedDataGetReal((PetscObject)y, NormIds[i], normys[i], flgys[i]);
1662: }
1664: PetscLogEventBegin(VEC_Swap, x, y, 0, 0);
1665: PetscUseTypeMethod(x, swap, y);
1666: PetscLogEventEnd(VEC_Swap, x, y, 0, 0);
1668: PetscObjectStateIncrease((PetscObject)x);
1669: PetscObjectStateIncrease((PetscObject)y);
1670: for (PetscInt i = 0; i < 4; i++) {
1671: if (flgxs[i]) PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], normxs[i]);
1672: if (flgys[i]) PetscObjectComposedDataSetReal((PetscObject)x, NormIds[i], normys[i]);
1673: }
1674: return 0;
1675: }
1677: /*
1678: VecStashViewFromOptions - Processes command line options to determine if/how an VecStash object is to be viewed.
1680: Collective on VecStash
1682: Input Parameters:
1683: + obj - the VecStash object
1684: . bobj - optional other object that provides the prefix
1685: - optionname - option to activate viewing
1687: Level: intermediate
1689: Developer Note: This cannot use PetscObjectViewFromOptions() because it takes a Vec as an argument but does not use VecView
1691: */
1692: PetscErrorCode VecStashViewFromOptions(Vec obj, PetscObject bobj, const char optionname[])
1693: {
1694: PetscViewer viewer;
1695: PetscBool flg;
1696: PetscViewerFormat format;
1697: char *prefix;
1699: prefix = bobj ? bobj->prefix : ((PetscObject)obj)->prefix;
1700: PetscOptionsGetViewer(PetscObjectComm((PetscObject)obj), ((PetscObject)obj)->options, prefix, optionname, &viewer, &format, &flg);
1701: if (flg) {
1702: PetscViewerPushFormat(viewer, format);
1703: VecStashView(obj, viewer);
1704: PetscViewerPopFormat(viewer);
1705: PetscViewerDestroy(&viewer);
1706: }
1707: return 0;
1708: }
1710: /*@
1711: VecStashView - Prints the entries in the vector stash and block stash.
1713: Collective on Vec
1715: Input Parameters:
1716: + v - the vector
1717: - viewer - the viewer
1719: Level: advanced
1721: .seealso: `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`
1723: @*/
1724: PetscErrorCode VecStashView(Vec v, PetscViewer viewer)
1725: {
1726: PetscMPIInt rank;
1727: PetscInt i, j;
1728: PetscBool match;
1729: VecStash *s;
1730: PetscScalar val;
1736: PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &match);
1738: PetscViewerASCIIUseTabs(viewer, PETSC_FALSE);
1739: MPI_Comm_rank(PetscObjectComm((PetscObject)v), &rank);
1740: s = &v->bstash;
1742: /* print block stash */
1743: PetscViewerASCIIPushSynchronized(viewer);
1744: PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector Block stash size %" PetscInt_FMT " block size %" PetscInt_FMT "\n", rank, s->n, s->bs);
1745: for (i = 0; i < s->n; i++) {
1746: PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " ", rank, s->idx[i]);
1747: for (j = 0; j < s->bs; j++) {
1748: val = s->array[i * s->bs + j];
1749: #if defined(PETSC_USE_COMPLEX)
1750: PetscViewerASCIISynchronizedPrintf(viewer, "(%18.16e %18.16e) ", (double)PetscRealPart(val), (double)PetscImaginaryPart(val));
1751: #else
1752: PetscViewerASCIISynchronizedPrintf(viewer, "%18.16e ", (double)val);
1753: #endif
1754: }
1755: PetscViewerASCIISynchronizedPrintf(viewer, "\n");
1756: }
1757: PetscViewerFlush(viewer);
1759: s = &v->stash;
1761: /* print basic stash */
1762: PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector stash size %" PetscInt_FMT "\n", rank, s->n);
1763: for (i = 0; i < s->n; i++) {
1764: val = s->array[i];
1765: #if defined(PETSC_USE_COMPLEX)
1766: PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " (%18.16e %18.16e) ", rank, s->idx[i], (double)PetscRealPart(val), (double)PetscImaginaryPart(val));
1767: #else
1768: PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " %18.16e\n", rank, s->idx[i], (double)val);
1769: #endif
1770: }
1771: PetscViewerFlush(viewer);
1772: PetscViewerASCIIPopSynchronized(viewer);
1773: PetscViewerASCIIUseTabs(viewer, PETSC_TRUE);
1774: return 0;
1775: }
1777: PetscErrorCode PetscOptionsGetVec(PetscOptions options, const char prefix[], const char key[], Vec v, PetscBool *set)
1778: {
1779: PetscInt i, N, rstart, rend;
1780: PetscScalar *xx;
1781: PetscReal *xreal;
1782: PetscBool iset;
1784: VecGetOwnershipRange(v, &rstart, &rend);
1785: VecGetSize(v, &N);
1786: PetscCalloc1(N, &xreal);
1787: PetscOptionsGetRealArray(options, prefix, key, xreal, &N, &iset);
1788: if (iset) {
1789: VecGetArray(v, &xx);
1790: for (i = rstart; i < rend; i++) xx[i - rstart] = xreal[i];
1791: VecRestoreArray(v, &xx);
1792: }
1793: PetscFree(xreal);
1794: if (set) *set = iset;
1795: return 0;
1796: }
1798: /*@
1799: VecGetLayout - get PetscLayout describing vector layout
1801: Not Collective
1803: Input Parameter:
1804: . x - the vector
1806: Output Parameter:
1807: . map - the layout
1809: Level: developer
1811: .seealso: `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
1812: @*/
1813: PetscErrorCode VecGetLayout(Vec x, PetscLayout *map)
1814: {
1817: *map = x->map;
1818: return 0;
1819: }
1821: /*@
1822: VecSetLayout - set PetscLayout describing vector layout
1824: Not Collective
1826: Input Parameters:
1827: + x - the vector
1828: - map - the layout
1830: Notes:
1831: It is normally only valid to replace the layout with a layout known to be equivalent.
1833: Level: developer
1835: .seealso: `VecGetLayout()`, `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
1836: @*/
1837: PetscErrorCode VecSetLayout(Vec x, PetscLayout map)
1838: {
1840: PetscLayoutReference(map, &x->map);
1841: return 0;
1842: }
1844: PetscErrorCode VecSetInf(Vec xin)
1845: {
1846: PetscInt i, n = xin->map->n;
1847: PetscScalar *xx;
1848: PetscScalar zero = 0.0, one = 1.0, inf = one / zero;
1850: if (xin->ops->set) PetscUseTypeMethod(xin, set, inf);
1851: else {
1852: VecGetArrayWrite(xin, &xx);
1853: for (i = 0; i < n; i++) xx[i] = inf;
1854: VecRestoreArrayWrite(xin, &xx);
1855: }
1856: return 0;
1857: }
1859: /*@
1860: VecBindToCPU - marks a vector to temporarily stay on the CPU and perform computations on the CPU
1862: Logically collective on Vec
1864: Input Parameters:
1865: + v - the vector
1866: - flg - bind to the CPU if value of PETSC_TRUE
1868: Level: intermediate
1869: @*/
1870: PetscErrorCode VecBindToCPU(Vec v, PetscBool flg)
1871: {
1874: #if defined(PETSC_HAVE_DEVICE)
1875: if (v->boundtocpu == flg) return 0;
1876: v->boundtocpu = flg;
1877: PetscTryTypeMethod(v, bindtocpu, flg);
1878: #endif
1879: return 0;
1880: }
1882: /*@
1883: VecBoundToCPU - query if a vector is bound to the CPU
1885: Not collective
1887: Input Parameter:
1888: . v - the vector
1890: Output Parameter:
1891: . flg - the logical flag
1893: Level: intermediate
1895: .seealso: `VecBindToCPU()`
1896: @*/
1897: PetscErrorCode VecBoundToCPU(Vec v, PetscBool *flg)
1898: {
1901: #if defined(PETSC_HAVE_DEVICE)
1902: *flg = v->boundtocpu;
1903: #else
1904: *flg = PETSC_TRUE;
1905: #endif
1906: return 0;
1907: }
1909: /*@
1910: VecSetBindingPropagates - Sets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects
1912: Input Parameters:
1913: + v - the vector
1914: - flg - flag indicating whether the boundtocpu flag should be propagated
1916: Level: developer
1918: Notes:
1919: If the value of flg is set to true, then VecDuplicate() and VecDuplicateVecs() will bind created vectors to GPU if the input vector is bound to the CPU.
1920: The created vectors will also have their bindingpropagates flag set to true.
1922: Developer Notes:
1923: If a DMDA has the -dm_bind_below option set to true, then vectors created by DMCreateGlobalVector() will have VecSetBindingPropagates() called on them to
1924: set their bindingpropagates flag to true.
1926: .seealso: `MatSetBindingPropagates()`, `VecGetBindingPropagates()`
1927: @*/
1928: PetscErrorCode VecSetBindingPropagates(Vec v, PetscBool flg)
1929: {
1931: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1932: v->bindingpropagates = flg;
1933: #endif
1934: return 0;
1935: }
1937: /*@
1938: VecGetBindingPropagates - Gets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects
1940: Input Parameter:
1941: . v - the vector
1943: Output Parameter:
1944: . flg - flag indicating whether the boundtocpu flag will be propagated
1946: Level: developer
1948: .seealso: `VecSetBindingPropagates()`
1949: @*/
1950: PetscErrorCode VecGetBindingPropagates(Vec v, PetscBool *flg)
1951: {
1954: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1955: *flg = v->bindingpropagates;
1956: #else
1957: *flg = PETSC_FALSE;
1958: #endif
1959: return 0;
1960: }
1962: /*@C
1963: VecSetPinnedMemoryMin - Set the minimum data size for which pinned memory will be used for host (CPU) allocations.
1965: Logically Collective on Vec
1967: Input Parameters:
1968: + v - the vector
1969: - mbytes - minimum data size in bytes
1971: Options Database Keys:
1973: . -vec_pinned_memory_min <size> - minimum size (in bytes) for an allocation to use pinned memory on host.
1974: Note that this takes a PetscScalar, to accommodate large values;
1975: specifying -1 ensures that pinned memory will never be used.
1977: Level: developer
1979: .seealso: `VecGetPinnedMemoryMin()`
1980: @*/
1981: PetscErrorCode VecSetPinnedMemoryMin(Vec v, size_t mbytes)
1982: {
1984: #if PetscDefined(HAVE_DEVICE)
1985: v->minimum_bytes_pinned_memory = mbytes;
1986: #endif
1987: return 0;
1988: }
1990: /*@C
1991: VecGetPinnedMemoryMin - Get the minimum data size for which pinned memory will be used for host (CPU) allocations.
1993: Logically Collective on Vec
1995: Input Parameters:
1996: . v - the vector
1998: Output Parameters:
1999: . mbytes - minimum data size in bytes
2001: Level: developer
2003: .seealso: `VecSetPinnedMemoryMin()`
2004: @*/
2005: PetscErrorCode VecGetPinnedMemoryMin(Vec v, size_t *mbytes)
2006: {
2009: #if PetscDefined(HAVE_DEVICE)
2010: *mbytes = v->minimum_bytes_pinned_memory;
2011: #endif
2012: return 0;
2013: }
2015: /*@
2016: VecGetOffloadMask - Get the offload mask of a Vec.
2018: Not Collective
2020: Input Parameters:
2021: . v - the vector
2023: Output Parameters:
2024: . mask - corresponding PetscOffloadMask enum value.
2026: Level: intermediate
2028: .seealso: `VecCreateSeqCUDA()`, `VecCreateSeqViennaCL()`, `VecGetArray()`, `VecGetType()`
2029: @*/
2030: PetscErrorCode VecGetOffloadMask(Vec v, PetscOffloadMask *mask)
2031: {
2034: *mask = v->offloadmask;
2035: return 0;
2036: }
2038: #if !defined(PETSC_HAVE_VIENNACL)
2039: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLContext(Vec v, PETSC_UINTPTR_T *ctx)
2040: {
2041: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_context");
2042: }
2044: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLQueue(Vec v, PETSC_UINTPTR_T *queue)
2045: {
2046: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_command_queue");
2047: }
2049: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMem(Vec v, PETSC_UINTPTR_T *queue)
2050: {
2051: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2052: }
2054: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemRead(Vec v, PETSC_UINTPTR_T *queue)
2055: {
2056: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2057: }
2059: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemWrite(Vec v, PETSC_UINTPTR_T *queue)
2060: {
2061: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2062: }
2064: PETSC_EXTERN PetscErrorCode VecViennaCLRestoreCLMemWrite(Vec v)
2065: {
2066: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to restore a Vec's cl_mem");
2067: }
2068: #endif