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_Shift, 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_PointwiseDivide, 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_HIPCopyFromGPU, VEC_HIPCopyToGPU;
20: /*@
21: VecStashGetInfo - Gets how many values are currently in the vector stash, i.e. need
22: to be communicated to other processors during the `VecAssemblyBegin()`/`VecAssemblyEnd()` process
24: Not Collective
26: Input Parameter:
27: . vec - the vector
29: Output Parameters:
30: + nstash - the size of the stash
31: . reallocs - the number of additional mallocs incurred in building the stash
32: . bnstash - the size of the block stash
33: - breallocs - the number of additional mallocs incurred in building the block stash (from `VecSetValuesBlocked()`)
35: Level: advanced
37: .seealso: [](ch_vectors), `Vec`, `VecAssemblyBegin()`, `VecAssemblyEnd()`, `VecStashSetInitialSize()`, `VecStashView()`
38: @*/
39: PetscErrorCode VecStashGetInfo(Vec vec, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
40: {
41: PetscFunctionBegin;
42: PetscCall(VecStashGetInfo_Private(&vec->stash, nstash, reallocs));
43: PetscCall(VecStashGetInfo_Private(&vec->bstash, bnstash, breallocs));
44: PetscFunctionReturn(PETSC_SUCCESS);
45: }
47: /*@
48: VecSetLocalToGlobalMapping - Sets a local numbering to global numbering used
49: by the routine `VecSetValuesLocal()` to allow users to insert vector entries
50: using a local (per-processor) numbering.
52: Logically Collective
54: Input Parameters:
55: + x - vector
56: - mapping - mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
58: Level: intermediate
60: Notes:
61: All vectors obtained with `VecDuplicate()` from this vector inherit the same mapping.
63: Vectors obtained with `DMCreateGlobaVector()` will often have this attribute attached to the vector so this call is not needed
65: .seealso: [](ch_vectors), `Vec`, `VecAssemblyBegin()`, `VecAssemblyEnd()`, `VecSetValues()`, `VecSetValuesLocal()`,
66: `VecGetLocalToGlobalMapping()`, `VecSetValuesBlockedLocal()`
67: @*/
68: PetscErrorCode VecSetLocalToGlobalMapping(Vec x, ISLocalToGlobalMapping mapping)
69: {
70: PetscFunctionBegin;
73: if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, mapping);
74: else PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->map, mapping));
75: PetscFunctionReturn(PETSC_SUCCESS);
76: }
78: /*@
79: VecGetLocalToGlobalMapping - Gets the local-to-global numbering set by `VecSetLocalToGlobalMapping()`
81: Not Collective
83: Input Parameter:
84: . X - the vector
86: Output Parameter:
87: . mapping - the mapping
89: Level: advanced
91: .seealso: [](ch_vectors), `Vec`, `VecSetValuesLocal()`, `VecSetLocalToGlobalMapping()`
92: @*/
93: PetscErrorCode VecGetLocalToGlobalMapping(Vec X, ISLocalToGlobalMapping *mapping)
94: {
95: PetscFunctionBegin;
98: PetscAssertPointer(mapping, 2);
99: if (X->ops->getlocaltoglobalmapping) PetscUseTypeMethod(X, getlocaltoglobalmapping, mapping);
100: else *mapping = X->map->mapping;
101: PetscFunctionReturn(PETSC_SUCCESS);
102: }
104: /*@
105: VecAssemblyBegin - Begins assembling the vector; that is ensuring all the vector's entries are stored on the correct MPI process. This routine should
106: be called after completing all calls to `VecSetValues()`.
108: Collective
110: Input Parameter:
111: . vec - the vector
113: Level: beginner
115: .seealso: [](ch_vectors), `Vec`, `VecAssemblyEnd()`, `VecSetValues()`
116: @*/
117: PetscErrorCode VecAssemblyBegin(Vec vec)
118: {
119: PetscFunctionBegin;
122: PetscCall(VecStashViewFromOptions(vec, NULL, "-vec_view_stash"));
123: PetscCall(PetscLogEventBegin(VEC_AssemblyBegin, vec, 0, 0, 0));
124: PetscTryTypeMethod(vec, assemblybegin);
125: PetscCall(PetscLogEventEnd(VEC_AssemblyBegin, vec, 0, 0, 0));
126: PetscCall(PetscObjectStateIncrease((PetscObject)vec));
127: PetscFunctionReturn(PETSC_SUCCESS);
128: }
130: /*@
131: VecAssemblyEnd - Completes assembling the vector. This routine should be called after `VecAssemblyBegin()`.
133: Collective
135: Input Parameter:
136: . vec - the vector
138: Options Database Keys:
139: + -vec_view - Prints vector in `PETSC_VIEWER_DEFAULT` format
140: . -vec_view ::ascii_matlab - Prints vector in `PETSC_VIEWER_ASCII_MATLAB` format to stdout
141: . -vec_view matlab:filename - Prints vector in MATLAB .mat file to filename (requires PETSc configured with --with-matlab)
142: . -vec_view draw - Activates vector viewing using drawing tools
143: . -display <name> - Sets display name (default is host)
144: . -draw_pause <sec> - Sets number of seconds to pause after display
145: - -vec_view socket - Activates vector viewing using a socket
147: Level: beginner
149: .seealso: [](ch_vectors), `Vec`, `VecAssemblyBegin()`, `VecSetValues()`
150: @*/
151: PetscErrorCode VecAssemblyEnd(Vec vec)
152: {
153: PetscFunctionBegin;
155: PetscCall(PetscLogEventBegin(VEC_AssemblyEnd, vec, 0, 0, 0));
157: PetscTryTypeMethod(vec, assemblyend);
158: PetscCall(PetscLogEventEnd(VEC_AssemblyEnd, vec, 0, 0, 0));
159: PetscCall(VecViewFromOptions(vec, NULL, "-vec_view"));
160: PetscFunctionReturn(PETSC_SUCCESS);
161: }
163: /*@
164: VecSetPreallocationCOO - set preallocation for a vector using a coordinate format of the entries with global indices
166: Collective
168: Input Parameters:
169: + x - vector being preallocated
170: . ncoo - number of entries
171: - coo_i - entry indices
173: Level: beginner
175: Notes:
176: This and `VecSetValuesCOO()` provide an alternative API to using `VecSetValues()` to provide vector values.
178: This API is particularly efficient for use on GPUs.
180: Entries can be repeated, see `VecSetValuesCOO()`. Negative indices are not allowed unless vector option `VEC_IGNORE_NEGATIVE_INDICES` is set,
181: in which case they, along with the corresponding entries in `VecSetValuesCOO()`, are ignored. If vector option `VEC_NO_OFF_PROC_ENTRIES` is set,
182: remote entries are ignored, otherwise, they will be properly added or inserted to the vector.
184: The array coo_i[] may be freed immediately after calling this function.
186: .seealso: [](ch_vectors), `Vec`, `VecSetValuesCOO()`, `VecSetPreallocationCOOLocal()`
187: @*/
188: PetscErrorCode VecSetPreallocationCOO(Vec x, PetscCount ncoo, const PetscInt coo_i[])
189: {
190: PetscFunctionBegin;
193: if (ncoo) PetscAssertPointer(coo_i, 3);
194: PetscCall(PetscLogEventBegin(VEC_SetPreallocateCOO, x, 0, 0, 0));
195: PetscCall(PetscLayoutSetUp(x->map));
196: if (x->ops->setpreallocationcoo) {
197: PetscUseTypeMethod(x, setpreallocationcoo, ncoo, coo_i);
198: } else {
199: IS is_coo_i;
200: /* The default implementation only supports ncoo within limit of PetscInt */
201: PetscCheck(ncoo <= PETSC_INT_MAX, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "ncoo %" PetscCount_FMT " overflowed PetscInt; configure --with-64-bit-indices or request support", ncoo);
202: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, (PetscInt)ncoo, coo_i, PETSC_COPY_VALUES, &is_coo_i));
203: PetscCall(PetscObjectCompose((PetscObject)x, "__PETSc_coo_i", (PetscObject)is_coo_i));
204: PetscCall(ISDestroy(&is_coo_i));
205: }
206: PetscCall(PetscLogEventEnd(VEC_SetPreallocateCOO, x, 0, 0, 0));
207: PetscFunctionReturn(PETSC_SUCCESS);
208: }
210: /*@
211: VecSetPreallocationCOOLocal - set preallocation for vectors using a coordinate format of the entries with local indices
213: Collective
215: Input Parameters:
216: + x - vector being preallocated
217: . ncoo - number of entries
218: - coo_i - row indices (local numbering; may be modified)
220: Level: beginner
222: Notes:
223: This and `VecSetValuesCOO()` provide an alternative API to using `VecSetValuesLocal()` to provide vector values.
225: This API is particularly efficient for use on GPUs.
227: The local indices are translated using the local to global mapping, thus `VecSetLocalToGlobalMapping()` must have been
228: called prior to this function.
230: The indices coo_i may be modified within this function. They might be translated to corresponding global
231: indices, but the caller should not rely on them having any specific value after this function returns. The arrays
232: can be freed or reused immediately after this function returns.
234: Entries can be repeated. Negative indices and remote indices might be allowed. see `VecSetPreallocationCOO()`.
236: .seealso: [](ch_vectors), `Vec`, `VecSetPreallocationCOO()`, `VecSetValuesCOO()`
237: @*/
238: PetscErrorCode VecSetPreallocationCOOLocal(Vec x, PetscCount ncoo, PetscInt coo_i[])
239: {
240: ISLocalToGlobalMapping ltog;
242: PetscFunctionBegin;
245: if (ncoo) PetscAssertPointer(coo_i, 3);
246: PetscCheck(ncoo <= PETSC_INT_MAX, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "ncoo %" PetscCount_FMT " overflowed PetscInt; configure --with-64-bit-indices or request support", ncoo);
247: PetscCall(PetscLayoutSetUp(x->map));
248: PetscCall(VecGetLocalToGlobalMapping(x, <og));
249: if (ltog) PetscCall(ISLocalToGlobalMappingApply(ltog, (PetscInt)ncoo, coo_i, coo_i));
250: PetscCall(VecSetPreallocationCOO(x, ncoo, coo_i));
251: PetscFunctionReturn(PETSC_SUCCESS);
252: }
254: /*@
255: VecSetValuesCOO - set values at once in a vector preallocated using `VecSetPreallocationCOO()`
257: Collective
259: Input Parameters:
260: + x - vector being set
261: . coo_v - the value array
262: - imode - the insert mode
264: Level: beginner
266: Note:
267: This and `VecSetPreallocationCOO() or ``VecSetPreallocationCOOLocal()` provide an alternative API to using `VecSetValues()` to provide vector values.
269: This API is particularly efficient for use on GPUs.
271: The values must follow the order of the indices prescribed with `VecSetPreallocationCOO()` or `VecSetPreallocationCOOLocal()`.
272: When repeated entries are specified in the COO indices the `coo_v` values are first properly summed, regardless of the value of `imode`.
273: The imode flag indicates if `coo_v` must be added to the current values of the vector (`ADD_VALUES`) or overwritten (`INSERT_VALUES`).
274: `VecAssemblyBegin()` and `VecAssemblyEnd()` do not need to be called after this routine. It automatically handles the assembly process.
276: .seealso: [](ch_vectors), `Vec`, `VecSetPreallocationCOO()`, `VecSetPreallocationCOOLocal()`, `VecSetValues()`
277: @*/
278: PetscErrorCode VecSetValuesCOO(Vec x, const PetscScalar coo_v[], InsertMode imode)
279: {
280: PetscFunctionBegin;
284: PetscCall(PetscLogEventBegin(VEC_SetValuesCOO, x, 0, 0, 0));
285: if (x->ops->setvaluescoo) {
286: PetscUseTypeMethod(x, setvaluescoo, coo_v, imode);
287: PetscCall(PetscObjectStateIncrease((PetscObject)x));
288: } else {
289: IS is_coo_i;
290: const PetscInt *coo_i;
291: PetscInt ncoo;
292: PetscMemType mtype;
294: PetscCall(PetscGetMemType(coo_v, &mtype));
295: PetscCheck(mtype == PETSC_MEMTYPE_HOST, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONG, "The basic VecSetValuesCOO() only supports v[] on host");
296: PetscCall(PetscObjectQuery((PetscObject)x, "__PETSc_coo_i", (PetscObject *)&is_coo_i));
297: PetscCheck(is_coo_i, PetscObjectComm((PetscObject)x), PETSC_ERR_COR, "Missing coo_i IS");
298: PetscCall(ISGetLocalSize(is_coo_i, &ncoo));
299: PetscCall(ISGetIndices(is_coo_i, &coo_i));
300: if (imode != ADD_VALUES) PetscCall(VecZeroEntries(x));
301: PetscCall(VecSetValues(x, ncoo, coo_i, coo_v, ADD_VALUES));
302: PetscCall(ISRestoreIndices(is_coo_i, &coo_i));
303: PetscCall(VecAssemblyBegin(x));
304: PetscCall(VecAssemblyEnd(x));
305: }
306: PetscCall(PetscLogEventEnd(VEC_SetValuesCOO, x, 0, 0, 0));
307: PetscFunctionReturn(PETSC_SUCCESS);
308: }
310: static PetscErrorCode VecPointwiseApply_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx, PetscLogEvent event, const char async_name[], PetscErrorCode (*const pointwise_op)(Vec, Vec, Vec))
311: {
312: PetscErrorCode (*async_fn)(Vec, Vec, Vec, PetscDeviceContext) = NULL;
314: PetscFunctionBegin;
321: PetscCheckSameTypeAndComm(x, 2, y, 3);
322: PetscCheckSameTypeAndComm(y, 3, w, 1);
323: VecCheckSameSize(w, 1, x, 2);
324: VecCheckSameSize(w, 1, y, 3);
325: VecCheckAssembled(x);
326: VecCheckAssembled(y);
327: PetscCall(VecSetErrorIfLocked(w, 1));
330: if (dctx) PetscCall(PetscObjectQueryFunction((PetscObject)w, async_name, &async_fn));
331: if (event) PetscCall(PetscLogEventBegin(event, x, y, w, 0));
332: if (async_fn) {
333: PetscCall((*async_fn)(w, x, y, dctx));
334: } else {
335: PetscCall((*pointwise_op)(w, x, y));
336: }
337: if (event) PetscCall(PetscLogEventEnd(event, x, y, w, 0));
338: PetscCall(PetscObjectStateIncrease((PetscObject)w));
339: PetscFunctionReturn(PETSC_SUCCESS);
340: }
342: PetscErrorCode VecPointwiseMaxAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
343: {
344: PetscFunctionBegin;
345: // REVIEW ME: no log event?
346: PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMax), w->ops->pointwisemax));
347: PetscFunctionReturn(PETSC_SUCCESS);
348: }
350: /*@
351: VecPointwiseMax - Computes the component-wise maximum `w[i] = max(x[i], y[i])`.
353: Logically Collective
355: Input Parameters:
356: + x - the first input vector
357: - y - the second input vector
359: Output Parameter:
360: . w - the result
362: Level: advanced
364: Notes:
365: Any subset of the `x`, `y`, and `w` may be the same vector.
367: For complex numbers compares only the real part
369: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
370: @*/
371: PetscErrorCode VecPointwiseMax(Vec w, Vec x, Vec y)
372: {
373: PetscFunctionBegin;
374: PetscCall(VecPointwiseMaxAsync_Private(w, x, y, NULL));
375: PetscFunctionReturn(PETSC_SUCCESS);
376: }
378: PetscErrorCode VecPointwiseMinAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
379: {
380: PetscFunctionBegin;
381: // REVIEW ME: no log event?
382: PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMin), w->ops->pointwisemin));
383: PetscFunctionReturn(PETSC_SUCCESS);
384: }
386: /*@
387: VecPointwiseMin - Computes the component-wise minimum `w[i] = min(x[i], y[i])`.
389: Logically Collective
391: Input Parameters:
392: + x - the first input vector
393: - y - the second input vector
395: Output Parameter:
396: . w - the result
398: Level: advanced
400: Notes:
401: Any subset of the `x`, `y`, and `w` may be the same vector.
403: For complex numbers compares only the real part
405: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
406: @*/
407: PetscErrorCode VecPointwiseMin(Vec w, Vec x, Vec y)
408: {
409: PetscFunctionBegin;
410: PetscCall(VecPointwiseMinAsync_Private(w, x, y, NULL));
411: PetscFunctionReturn(PETSC_SUCCESS);
412: }
414: PetscErrorCode VecPointwiseMaxAbsAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
415: {
416: PetscFunctionBegin;
417: // REVIEW ME: no log event?
418: PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMaxAbs), w->ops->pointwisemaxabs));
419: PetscFunctionReturn(PETSC_SUCCESS);
420: }
422: /*@
423: VecPointwiseMaxAbs - Computes the component-wise maximum of the absolute values `w[i] = max(abs(x[i]), abs(y[i]))`.
425: Logically Collective
427: Input Parameters:
428: + x - the first input vector
429: - y - the second input vector
431: Output Parameter:
432: . w - the result
434: Level: advanced
436: Notes:
437: Any subset of the `x`, `y`, and `w` may be the same vector.
439: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMax()`, `VecMaxPointwiseDivide()`
440: @*/
441: PetscErrorCode VecPointwiseMaxAbs(Vec w, Vec x, Vec y)
442: {
443: PetscFunctionBegin;
444: PetscCall(VecPointwiseMaxAbsAsync_Private(w, x, y, NULL));
445: PetscFunctionReturn(PETSC_SUCCESS);
446: }
448: PetscErrorCode VecPointwiseDivideAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
449: {
450: PetscFunctionBegin;
451: PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseDivide, VecAsyncFnName(PointwiseDivide), w->ops->pointwisedivide));
452: PetscFunctionReturn(PETSC_SUCCESS);
453: }
455: /*@
456: VecPointwiseDivide - Computes the component-wise division `w[i] = x[i] / y[i]`.
458: Logically Collective
460: Input Parameters:
461: + x - the numerator vector
462: - y - the denominator vector
464: Output Parameter:
465: . w - the result
467: Level: advanced
469: Note:
470: Any subset of the `x`, `y`, and `w` may be the same vector.
472: .seealso: [](ch_vectors), `Vec`, `VecPointwiseMult()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
473: @*/
474: PetscErrorCode VecPointwiseDivide(Vec w, Vec x, Vec y)
475: {
476: PetscFunctionBegin;
477: PetscCall(VecPointwiseDivideAsync_Private(w, x, y, NULL));
478: PetscFunctionReturn(PETSC_SUCCESS);
479: }
481: PetscErrorCode VecPointwiseMultAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
482: {
483: PetscFunctionBegin;
485: PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseMult, VecAsyncFnName(PointwiseMult), w->ops->pointwisemult));
486: PetscFunctionReturn(PETSC_SUCCESS);
487: }
489: /*@
490: VecPointwiseMult - Computes the component-wise multiplication `w[i] = x[i] * y[i]`.
492: Logically Collective
494: Input Parameters:
495: + x - the first vector
496: - y - the second vector
498: Output Parameter:
499: . w - the result
501: Level: advanced
503: Note:
504: Any subset of the `x`, `y`, and `w` may be the same vector.
506: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
507: @*/
508: PetscErrorCode VecPointwiseMult(Vec w, Vec x, Vec y)
509: {
510: PetscFunctionBegin;
511: PetscCall(VecPointwiseMultAsync_Private(w, x, y, NULL));
512: PetscFunctionReturn(PETSC_SUCCESS);
513: }
515: /*@
516: VecDuplicate - Creates a new vector of the same type as an existing vector.
518: Collective
520: Input Parameter:
521: . v - a vector to mimic
523: Output Parameter:
524: . newv - location to put new vector
526: Level: beginner
528: Notes:
529: `VecDuplicate()` DOES NOT COPY the vector entries, but rather allocates storage
530: for the new vector. Use `VecCopy()` to copy a vector.
532: Use `VecDestroy()` to free the space. Use `VecDuplicateVecs()` to get several
533: vectors.
535: .seealso: [](ch_vectors), `Vec`, `VecDestroy()`, `VecDuplicateVecs()`, `VecCreate()`, `VecCopy()`
536: @*/
537: PetscErrorCode VecDuplicate(Vec v, Vec *newv)
538: {
539: PetscFunctionBegin;
541: PetscAssertPointer(newv, 2);
543: PetscUseTypeMethod(v, duplicate, newv);
544: #if PetscDefined(HAVE_DEVICE)
545: if (v->boundtocpu && v->bindingpropagates) {
546: PetscCall(VecSetBindingPropagates(*newv, PETSC_TRUE));
547: PetscCall(VecBindToCPU(*newv, PETSC_TRUE));
548: }
549: #endif
550: PetscCall(PetscObjectStateIncrease((PetscObject)*newv));
551: PetscFunctionReturn(PETSC_SUCCESS);
552: }
554: /*@
555: VecDestroy - Destroys a vector.
557: Collective
559: Input Parameter:
560: . v - the vector
562: Level: beginner
564: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDuplicate()`, `VecDestroyVecs()`
565: @*/
566: PetscErrorCode VecDestroy(Vec *v)
567: {
568: PetscFunctionBegin;
569: PetscAssertPointer(v, 1);
570: if (!*v) PetscFunctionReturn(PETSC_SUCCESS);
572: if (--((PetscObject)*v)->refct > 0) {
573: *v = NULL;
574: PetscFunctionReturn(PETSC_SUCCESS);
575: }
577: PetscCall(PetscObjectSAWsViewOff((PetscObject)*v));
578: /* destroy the internal part */
579: PetscTryTypeMethod(*v, destroy);
580: PetscCall(PetscFree((*v)->defaultrandtype));
581: /* destroy the external/common part */
582: PetscCall(PetscLayoutDestroy(&(*v)->map));
583: PetscCall(PetscHeaderDestroy(v));
584: PetscFunctionReturn(PETSC_SUCCESS);
585: }
587: /*@C
588: VecDuplicateVecs - Creates several vectors of the same type as an existing vector.
590: Collective
592: Input Parameters:
593: + m - the number of vectors to obtain
594: - v - a vector to mimic
596: Output Parameter:
597: . V - location to put pointer to array of vectors
599: Level: intermediate
601: Note:
602: Use `VecDestroyVecs()` to free the space. Use `VecDuplicate()` to form a single
603: vector.
605: Fortran Notes:
606: The Fortran interface is slightly different from that given below, it
607: requires one to pass in `V` a `Vec` array of size at least `m`.
608: See the [](ch_fortran) for details.
610: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDestroyVecs()`, `VecDuplicate()`, `VecCreate()`, `VecDuplicateVecsF90()`
611: @*/
612: PetscErrorCode VecDuplicateVecs(Vec v, PetscInt m, Vec *V[])
613: {
614: PetscFunctionBegin;
616: PetscAssertPointer(V, 3);
618: PetscUseTypeMethod(v, duplicatevecs, m, V);
619: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
620: if (v->boundtocpu && v->bindingpropagates) {
621: PetscInt i;
623: for (i = 0; i < m; i++) {
624: /* Since ops->duplicatevecs might itself propagate the value of boundtocpu,
625: * avoid unnecessary overhead by only calling VecBindToCPU() if the vector isn't already bound. */
626: if (!(*V)[i]->boundtocpu) {
627: PetscCall(VecSetBindingPropagates((*V)[i], PETSC_TRUE));
628: PetscCall(VecBindToCPU((*V)[i], PETSC_TRUE));
629: }
630: }
631: }
632: #endif
633: PetscFunctionReturn(PETSC_SUCCESS);
634: }
636: /*@C
637: VecDestroyVecs - Frees a block of vectors obtained with `VecDuplicateVecs()`.
639: Collective
641: Input Parameters:
642: + m - the number of vectors previously obtained, if zero no vectors are destroyed
643: - vv - pointer to pointer to array of vector pointers, if `NULL` no vectors are destroyed
645: Level: intermediate
647: Fortran Notes:
648: The Fortran interface is slightly different from that given below.
649: See the [](ch_fortran) for details.
651: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDuplicateVecs()`, `VecDestroyVecsf90()`
652: @*/
653: PetscErrorCode VecDestroyVecs(PetscInt m, Vec *vv[])
654: {
655: PetscFunctionBegin;
656: PetscAssertPointer(vv, 2);
657: PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of vectors %" PetscInt_FMT, m);
658: if (!m || !*vv) {
659: *vv = NULL;
660: PetscFunctionReturn(PETSC_SUCCESS);
661: }
664: PetscCall((*(**vv)->ops->destroyvecs)(m, *vv));
665: *vv = NULL;
666: PetscFunctionReturn(PETSC_SUCCESS);
667: }
669: /*@
670: VecViewFromOptions - View a vector based on values in the options database
672: Collective
674: Input Parameters:
675: + A - the vector
676: . obj - Optional object that provides the options prefix for this viewing
677: - name - command line option
679: Level: intermediate
681: Note:
682: See `PetscObjectViewFromOptions()` to see the `PetscViewer` and PetscViewerFormat` available
684: .seealso: [](ch_vectors), `Vec`, `VecView`, `PetscObjectViewFromOptions()`, `VecCreate()`
685: @*/
686: PetscErrorCode VecViewFromOptions(Vec A, PetscObject obj, const char name[])
687: {
688: PetscFunctionBegin;
690: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
691: PetscFunctionReturn(PETSC_SUCCESS);
692: }
694: /*@
695: VecView - Views a vector object.
697: Collective
699: Input Parameters:
700: + vec - the vector
701: - viewer - an optional `PetscViewer` visualization context
703: Level: beginner
705: Notes:
706: The available visualization contexts include
707: + `PETSC_VIEWER_STDOUT_SELF` - for sequential vectors
708: . `PETSC_VIEWER_STDOUT_WORLD` - for parallel vectors created on `PETSC_COMM_WORLD`
709: - `PETSC_VIEWER_STDOUT`_(comm) - for parallel vectors created on MPI communicator comm
711: You can change the format the vector is printed using the
712: option `PetscViewerPushFormat()`.
714: The user can open alternative viewers with
715: + `PetscViewerASCIIOpen()` - Outputs vector to a specified file
716: . `PetscViewerBinaryOpen()` - Outputs vector in binary to a
717: specified file; corresponding input uses `VecLoad()`
718: . `PetscViewerDrawOpen()` - Outputs vector to an X window display
719: . `PetscViewerSocketOpen()` - Outputs vector to Socket viewer
720: - `PetscViewerHDF5Open()` - Outputs vector to HDF5 file viewer
722: The user can call `PetscViewerPushFormat()` to specify the output
723: format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
724: `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`). Available formats include
725: + `PETSC_VIEWER_DEFAULT` - default, prints vector contents
726: . `PETSC_VIEWER_ASCII_MATLAB` - prints vector contents in MATLAB format
727: . `PETSC_VIEWER_ASCII_INDEX` - prints vector contents, including indices of vector elements
728: - `PETSC_VIEWER_ASCII_COMMON` - prints vector contents, using a
729: format common among all vector types
731: You can pass any number of vector objects, or other PETSc objects to the same viewer.
733: In the debugger you can do call `VecView`(v,0) to display the vector. (The same holds for any PETSc object viewer).
735: Notes for binary viewer:
736: If you pass multiple vectors to a binary viewer you can read them back in the same order
737: with `VecLoad()`.
739: If the blocksize of the vector is greater than one then you must provide a unique prefix to
740: the vector with `PetscObjectSetOptionsPrefix`((`PetscObject`)vec,"uniqueprefix"); BEFORE calling `VecView()` on the
741: vector to be stored and then set that same unique prefix on the vector that you pass to `VecLoad()`. The blocksize
742: information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
743: filename. If you copy the binary file, make sure you copy the associated .info file with it.
745: See the manual page for `VecLoad()` on the exact format the binary viewer stores
746: the values in the file.
748: Notes for HDF5 Viewer:
749: The name of the `Vec` (given with `PetscObjectSetName()` is the name that is used
750: for the object in the HDF5 file. If you wish to store the same Vec into multiple
751: datasets in the same file (typically with different values), you must change its
752: name each time before calling the `VecView()`. To load the same vector,
753: the name of the Vec object passed to `VecLoad()` must be the same.
755: If the block size of the vector is greater than 1 then it is used as the first dimension in the HDF5 array.
756: If the function `PetscViewerHDF5SetBaseDimension2()`is called then even if the block size is one it will
757: be used as the first dimension in the HDF5 array (that is the HDF5 array will always be two dimensional)
758: See also `PetscViewerHDF5SetTimestep()` which adds an additional complication to reading and writing `Vec`
759: with the HDF5 viewer.
761: .seealso: [](ch_vectors), `Vec`, `VecViewFromOptions()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`,
762: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
763: `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
764: @*/
765: PetscErrorCode VecView(Vec vec, PetscViewer viewer)
766: {
767: PetscBool iascii;
768: PetscViewerFormat format;
769: PetscMPIInt size;
771: PetscFunctionBegin;
774: VecCheckAssembled(vec);
775: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
777: PetscCall(PetscViewerGetFormat(viewer, &format));
778: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
779: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
781: PetscCheck(!vec->stash.n && !vec->bstash.n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call VecAssemblyBegin/End() before viewing this vector");
783: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
784: if (iascii) {
785: PetscInt rows, bs;
787: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)vec, viewer));
788: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
789: PetscCall(PetscViewerASCIIPushTab(viewer));
790: PetscCall(VecGetSize(vec, &rows));
791: PetscCall(VecGetBlockSize(vec, &bs));
792: if (bs != 1) {
793: PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT ", bs=%" PetscInt_FMT "\n", rows, bs));
794: } else {
795: PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT "\n", rows));
796: }
797: PetscCall(PetscViewerASCIIPopTab(viewer));
798: }
799: }
800: PetscCall(VecLockReadPush(vec));
801: PetscCall(PetscLogEventBegin(VEC_View, vec, viewer, 0, 0));
802: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && vec->ops->viewnative) {
803: PetscUseTypeMethod(vec, viewnative, viewer);
804: } else {
805: PetscUseTypeMethod(vec, view, viewer);
806: }
807: PetscCall(VecLockReadPop(vec));
808: PetscCall(PetscLogEventEnd(VEC_View, vec, viewer, 0, 0));
809: PetscFunctionReturn(PETSC_SUCCESS);
810: }
812: #if defined(PETSC_USE_DEBUG)
813: #include <../src/sys/totalview/tv_data_display.h>
814: PETSC_UNUSED static int TV_display_type(const struct _p_Vec *v)
815: {
816: const PetscScalar *values;
817: char type[32];
819: TV_add_row("Local rows", "int", &v->map->n);
820: TV_add_row("Global rows", "int", &v->map->N);
821: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)v)->type_name);
822: PetscCall(VecGetArrayRead((Vec)v, &values));
823: PetscCall(PetscSNPrintf(type, 32, "double[%" PetscInt_FMT "]", v->map->n));
824: TV_add_row("values", type, values);
825: PetscCall(VecRestoreArrayRead((Vec)v, &values));
826: return TV_format_OK;
827: }
828: #endif
830: /*@C
831: VecViewNative - Views a vector object with the original type specific viewer
833: Collective
835: Input Parameters:
836: + vec - the vector
837: - viewer - an optional `PetscViewer` visualization context
839: Level: developer
841: Note:
842: This can be used with, for example, vectors obtained with `DMCreateGlobalVector()` for a `DMDA` to display the vector
843: in the PETSc storage format (each MPI process values follow the previous MPI processes) instead of the "natural" grid
844: ordering.
846: .seealso: [](ch_vectors), `Vec`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`, `VecView()`
847: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
848: `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
849: @*/
850: PetscErrorCode VecViewNative(Vec vec, PetscViewer viewer)
851: {
852: PetscFunctionBegin;
855: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
857: PetscUseTypeMethod(vec, viewnative, viewer);
858: PetscFunctionReturn(PETSC_SUCCESS);
859: }
861: /*@
862: VecGetSize - Returns the global number of elements of the vector.
864: Not Collective
866: Input Parameter:
867: . x - the vector
869: Output Parameter:
870: . size - the global length of the vector
872: Level: beginner
874: .seealso: [](ch_vectors), `Vec`, `VecGetLocalSize()`
875: @*/
876: PetscErrorCode VecGetSize(Vec x, PetscInt *size)
877: {
878: PetscFunctionBegin;
880: PetscAssertPointer(size, 2);
882: PetscUseTypeMethod(x, getsize, size);
883: PetscFunctionReturn(PETSC_SUCCESS);
884: }
886: /*@
887: VecGetLocalSize - Returns the number of elements of the vector stored
888: in local memory (that is on this MPI process)
890: Not Collective
892: Input Parameter:
893: . x - the vector
895: Output Parameter:
896: . size - the length of the local piece of the vector
898: Level: beginner
900: .seealso: [](ch_vectors), `Vec`, `VecGetSize()`
901: @*/
902: PetscErrorCode VecGetLocalSize(Vec x, PetscInt *size)
903: {
904: PetscFunctionBegin;
906: PetscAssertPointer(size, 2);
908: PetscUseTypeMethod(x, getlocalsize, size);
909: PetscFunctionReturn(PETSC_SUCCESS);
910: }
912: /*@
913: VecGetOwnershipRange - Returns the range of indices owned by
914: this process. The vector is laid out with the
915: first `n1` elements on the first processor, next `n2` elements on the
916: second, etc. For certain parallel layouts this range may not be
917: well defined.
919: Not Collective
921: Input Parameter:
922: . x - the vector
924: Output Parameters:
925: + low - the first local element, pass in `NULL` if not interested
926: - high - one more than the last local element, pass in `NULL` if not interested
928: Level: beginner
930: Notes:
931: If the `Vec` was obtained from a `DM` with `DMCreateGlobalVector()`, then the range values are determined by the specific `DM`.
933: If the `Vec` was created directly the range values are determined by the local size passed to `VecSetSizes()` or `VecCreateMPI()`.
934: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
936: The high argument is one more than the last element stored locally.
938: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
939: the local values in the vector.
941: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRanges()`, `PetscSplitOwnership()`,
942: `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
943: @*/
944: PetscErrorCode VecGetOwnershipRange(Vec x, PetscInt *low, PetscInt *high)
945: {
946: PetscFunctionBegin;
949: if (low) PetscAssertPointer(low, 2);
950: if (high) PetscAssertPointer(high, 3);
951: if (low) *low = x->map->rstart;
952: if (high) *high = x->map->rend;
953: PetscFunctionReturn(PETSC_SUCCESS);
954: }
956: /*@C
957: VecGetOwnershipRanges - Returns the range of indices owned by EACH processor,
958: The vector is laid out with the
959: first `n1` elements on the first processor, next `n2` elements on the
960: second, etc. For certain parallel layouts this range may not be
961: well defined.
963: Not Collective
965: Input Parameter:
966: . x - the vector
968: Output Parameter:
969: . ranges - array of length `size` + 1 with the start and end+1 for each process
971: Level: beginner
973: Notes:
974: If the `Vec` was obtained from a `DM` with `DMCreateGlobalVector()`, then the range values are determined by the specific `DM`.
976: If the `Vec` was created directly the range values are determined by the local size passed to `VecSetSizes()` or `VecCreateMPI()`.
977: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
979: The high argument is one more than the last element stored locally.
981: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
982: the local values in the vector.
984: The high argument is one more than the last element stored locally.
986: If `ranges` are used after all vectors that share the ranges has been destroyed, then the program will crash accessing `ranges`.
988: Fortran Notes:
989: You must PASS in an array of length `size` + 1, where `size` is the size of the communicator owning the vector
991: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRange()`, `PetscSplitOwnership()`,
992: `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
993: @*/
994: PetscErrorCode VecGetOwnershipRanges(Vec x, const PetscInt *ranges[])
995: {
996: PetscFunctionBegin;
999: PetscCall(PetscLayoutGetRanges(x->map, ranges));
1000: PetscFunctionReturn(PETSC_SUCCESS);
1001: }
1003: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1004: /*@
1005: VecSetOption - Sets an option for controlling a vector's behavior.
1007: Collective
1009: Input Parameters:
1010: + x - the vector
1011: . op - the option
1012: - flag - turn the option on or off
1014: Supported Options:
1015: + `VEC_IGNORE_OFF_PROC_ENTRIES` - which causes `VecSetValues()` to ignore
1016: entries destined to be stored on a separate processor. This can be used
1017: to eliminate the global reduction in the `VecAssemblyBegin()` if you know
1018: that you have only used `VecSetValues()` to set local elements
1019: . `VEC_IGNORE_NEGATIVE_INDICES` - which means you can pass negative indices
1020: in ix in calls to `VecSetValues()` or `VecGetValues()`. These rows are simply
1021: ignored.
1022: - `VEC_SUBSET_OFF_PROC_ENTRIES` - which causes `VecAssemblyBegin()` to assume that the off-process
1023: entries will always be a subset (possibly equal) of the off-process entries set on the
1024: first assembly which had a true `VEC_SUBSET_OFF_PROC_ENTRIES` and the vector has not
1025: changed this flag afterwards. If this assembly is not such first assembly, then this
1026: assembly can reuse the communication pattern setup in that first assembly, thus avoiding
1027: a global reduction. Subsequent assemblies setting off-process values should use the same
1028: InsertMode as the first assembly.
1030: Level: intermediate
1032: Developer Notes:
1033: The `InsertMode` restriction could be removed by packing the stash messages out of place.
1035: .seealso: [](ch_vectors), `Vec`, `VecSetValues()`
1036: @*/
1037: PetscErrorCode VecSetOption(Vec x, VecOption op, PetscBool flag)
1038: {
1039: PetscFunctionBegin;
1042: PetscTryTypeMethod(x, setoption, op, flag);
1043: PetscFunctionReturn(PETSC_SUCCESS);
1044: }
1046: /* Default routines for obtaining and releasing; */
1047: /* may be used by any implementation */
1048: PetscErrorCode VecDuplicateVecs_Default(Vec w, PetscInt m, Vec *V[])
1049: {
1050: PetscFunctionBegin;
1051: PetscCheck(m > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "m must be > 0: m = %" PetscInt_FMT, m);
1052: PetscCall(PetscMalloc1(m, V));
1053: for (PetscInt i = 0; i < m; i++) PetscCall(VecDuplicate(w, *V + i));
1054: PetscFunctionReturn(PETSC_SUCCESS);
1055: }
1057: PetscErrorCode VecDestroyVecs_Default(PetscInt m, Vec v[])
1058: {
1059: PetscInt i;
1061: PetscFunctionBegin;
1062: PetscAssertPointer(v, 2);
1063: for (i = 0; i < m; i++) PetscCall(VecDestroy(&v[i]));
1064: PetscCall(PetscFree(v));
1065: PetscFunctionReturn(PETSC_SUCCESS);
1066: }
1068: /*@
1069: VecResetArray - Resets a vector to use its default memory. Call this
1070: after the use of `VecPlaceArray()`.
1072: Not Collective
1074: Input Parameter:
1075: . vec - the vector
1077: Level: developer
1079: .seealso: [](ch_vectors), `Vec`, `VecGetArray()`, `VecRestoreArray()`, `VecReplaceArray()`, `VecPlaceArray()`
1080: @*/
1081: PetscErrorCode VecResetArray(Vec vec)
1082: {
1083: PetscFunctionBegin;
1086: PetscUseTypeMethod(vec, resetarray);
1087: PetscCall(PetscObjectStateIncrease((PetscObject)vec));
1088: PetscFunctionReturn(PETSC_SUCCESS);
1089: }
1091: /*@
1092: VecLoad - Loads a vector that has been stored in binary or HDF5 format
1093: with `VecView()`.
1095: Collective
1097: Input Parameters:
1098: + vec - the newly loaded vector, this needs to have been created with `VecCreate()` or
1099: some related function before the call to `VecLoad()`.
1100: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
1101: HDF5 file viewer, obtained from `PetscViewerHDF5Open()`
1103: Level: intermediate
1105: Notes:
1106: Defaults to the standard `VECSEQ` or `VECMPI`, if you want some other type of `Vec` call `VecSetFromOptions()`
1107: before calling this.
1109: The input file must contain the full global vector, as
1110: written by the routine `VecView()`.
1112: If the type or size of `vec` is not set before a call to `VecLoad()`, PETSc
1113: sets the type and the local and global sizes based on the vector it is reading in. If type and/or
1114: sizes are already set, then the same are used.
1116: If using the binary viewer and the blocksize of the vector is greater than one then you must provide a unique prefix to
1117: the vector with `PetscObjectSetOptionsPrefix`((`PetscObject`)vec,"uniqueprefix"); BEFORE calling `VecView()` on the
1118: vector to be stored and then set that same unique prefix on the vector that you pass to VecLoad(). The blocksize
1119: information is stored in an ASCII file with the same name as the binary file plus a ".info" appended to the
1120: filename. If you copy the binary file, make sure you copy the associated .info file with it.
1122: If using HDF5, you must assign the `Vec` the same name as was used in the Vec
1123: that was stored in the file using `PetscObjectSetName(). Otherwise you will
1124: get the error message: "Cannot H5DOpen2() with `Vec` name NAMEOFOBJECT".
1126: If the HDF5 file contains a two dimensional array the first dimension is treated as the block size
1127: in loading the vector. Hence, for example, using MATLAB notation h5create('vector.dat','/Test_Vec',[27 1]);
1128: will load a vector of size 27 and block size 27 thus resulting in all 27 entries being on the first process of
1129: vectors communicator and the rest of the processes having zero entries
1131: Notes for advanced users when using the binary viewer:
1132: Most users should not need to know the details of the binary storage
1133: format, since `VecLoad()` and `VecView()` completely hide these details.
1134: But for anyone who's interested, the standard binary vector storage
1135: format is
1136: .vb
1137: PetscInt VEC_FILE_CLASSID
1138: PetscInt number of rows
1139: PetscScalar *values of all entries
1140: .ve
1142: In addition, PETSc automatically uses byte swapping to work on all machines; the files
1143: are written ALWAYS using big-endian ordering. On small-endian machines the numbers
1144: are converted to the small-endian format when they are read in from the file.
1145: See PetscBinaryRead() and PetscBinaryWrite() to see how this may be done.
1147: .seealso: [](ch_vectors), `Vec`, `PetscViewerBinaryOpen()`, `VecView()`, `MatLoad()`
1148: @*/
1149: PetscErrorCode VecLoad(Vec vec, PetscViewer viewer)
1150: {
1151: PetscBool isbinary, ishdf5, isadios, isexodusii, iscgns;
1152: PetscViewerFormat format;
1154: PetscFunctionBegin;
1157: PetscCheckSameComm(vec, 1, viewer, 2);
1158: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1159: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
1160: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
1161: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERADIOS, &isadios));
1162: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
1163: PetscCheck(isbinary || ishdf5 || isadios || isexodusii || iscgns, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1165: PetscCall(VecSetErrorIfLocked(vec, 1));
1166: if (!((PetscObject)vec)->type_name && !vec->ops->create) PetscCall(VecSetType(vec, VECSTANDARD));
1167: PetscCall(PetscLogEventBegin(VEC_Load, viewer, 0, 0, 0));
1168: PetscCall(PetscViewerGetFormat(viewer, &format));
1169: if (format == PETSC_VIEWER_NATIVE && vec->ops->loadnative) {
1170: PetscUseTypeMethod(vec, loadnative, viewer);
1171: } else {
1172: PetscUseTypeMethod(vec, load, viewer);
1173: }
1174: PetscCall(PetscLogEventEnd(VEC_Load, viewer, 0, 0, 0));
1175: PetscFunctionReturn(PETSC_SUCCESS);
1176: }
1178: /*@
1179: VecReciprocal - Replaces each component of a vector by its reciprocal.
1181: Logically Collective
1183: Input Parameter:
1184: . vec - the vector
1186: Output Parameter:
1187: . vec - the vector reciprocal
1189: Level: intermediate
1191: Note:
1192: Vector entries with value 0.0 are not changed
1194: .seealso: [](ch_vectors), `Vec`, `VecLog()`, `VecExp()`, `VecSqrtAbs()`
1195: @*/
1196: PetscErrorCode VecReciprocal(Vec vec)
1197: {
1198: PetscFunctionBegin;
1199: PetscCall(VecReciprocalAsync_Private(vec, NULL));
1200: PetscFunctionReturn(PETSC_SUCCESS);
1201: }
1203: /*@C
1204: VecSetOperation - Allows the user to override a particular vector operation.
1206: Logically Collective; No Fortran Support
1208: Input Parameters:
1209: + vec - The vector to modify
1210: . op - The name of the operation
1211: - f - The function that provides the operation.
1213: Notes:
1214: `f` may be `NULL` to remove the operation from `vec`. Depending on the operation this may be
1215: allowed, however some always expect a valid function. In these cases an error will be raised
1216: when calling the interface routine in question.
1218: See `VecOperation` for an up-to-date list of override-able operations. The operations listed
1219: there have the form `VECOP_<OPERATION>`, where `<OPERATION>` is the suffix (in all capital
1220: letters) of the public interface routine (e.g., `VecView()` -> `VECOP_VIEW`).
1222: Overriding a particular `Vec`'s operation has no affect on any other `Vec`s past, present,
1223: or future. The user should also note that overriding a method is "destructive"; the previous
1224: method is not retained in any way.
1226: Level: advanced
1228: Example Usage:
1229: .vb
1230: // some new VecView() implementation, must have the same signature as the function it seeks
1231: // to replace
1232: PetscErrorCode UserVecView(Vec x, PetscViewer viewer)
1233: {
1234: PetscFunctionBeginUser;
1235: // ...
1236: PetscFunctionReturn(PETSC_SUCCESS);
1237: }
1239: // Create a VECMPI which has a pre-defined VecView() implementation
1240: VecCreateMPI(comm, n, N, &x);
1241: // Calls the VECMPI implementation for VecView()
1242: VecView(x, viewer);
1244: VecSetOperation(x, VECOP_VIEW, (void (*)(void))UserVecView);
1245: // Now calls UserVecView()
1246: VecView(x, viewer);
1247: .ve
1249: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `MatShellSetOperation()`
1250: @*/
1251: PetscErrorCode VecSetOperation(Vec vec, VecOperation op, void (*f)(void))
1252: {
1253: PetscFunctionBegin;
1255: if (op == VECOP_VIEW && !vec->ops->viewnative) {
1256: vec->ops->viewnative = vec->ops->view;
1257: } else if (op == VECOP_LOAD && !vec->ops->loadnative) {
1258: vec->ops->loadnative = vec->ops->load;
1259: }
1260: ((void (**)(void))vec->ops)[(int)op] = f;
1261: PetscFunctionReturn(PETSC_SUCCESS);
1262: }
1264: /*@
1265: VecStashSetInitialSize - sets the sizes of the vec-stash, that is
1266: used during the assembly process to store values that belong to
1267: other processors.
1269: Not Collective, different processes can have different size stashes
1271: Input Parameters:
1272: + vec - the vector
1273: . size - the initial size of the stash.
1274: - bsize - the initial size of the block-stash(if used).
1276: Options Database Keys:
1277: + -vecstash_initial_size <size> or <size0,size1,...sizep-1> - set initial size
1278: - -vecstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1> - set initial block size
1280: Level: intermediate
1282: Notes:
1283: The block-stash is used for values set with `VecSetValuesBlocked()` while
1284: the stash is used for values set with `VecSetValues()`
1286: Run with the option -info and look for output of the form
1287: VecAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
1288: to determine the appropriate value, MM, to use for size and
1289: VecAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
1290: to determine the value, BMM to use for bsize
1292: PETSc attempts to smartly manage the stash size so there is little likelihood setting a
1293: a specific value here will affect performance
1295: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`, `VecStashView()`
1296: @*/
1297: PetscErrorCode VecStashSetInitialSize(Vec vec, PetscInt size, PetscInt bsize)
1298: {
1299: PetscFunctionBegin;
1301: PetscCall(VecStashSetInitialSize_Private(&vec->stash, size));
1302: PetscCall(VecStashSetInitialSize_Private(&vec->bstash, bsize));
1303: PetscFunctionReturn(PETSC_SUCCESS);
1304: }
1306: /*@
1307: VecSetRandom - Sets all components of a vector to random numbers.
1309: Logically Collective
1311: Input Parameters:
1312: + x - the vector
1313: - rctx - the random number context, formed by `PetscRandomCreate()`, or use `NULL` and it will create one internally.
1315: Output Parameter:
1316: . x - the vector
1318: Example of Usage:
1319: .vb
1320: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
1321: VecSetRandom(x,rctx);
1322: PetscRandomDestroy(&rctx);
1323: .ve
1325: Level: intermediate
1327: .seealso: [](ch_vectors), `Vec`, `VecSet()`, `VecSetValues()`, `PetscRandomCreate()`, `PetscRandomDestroy()`
1328: @*/
1329: PetscErrorCode VecSetRandom(Vec x, PetscRandom rctx)
1330: {
1331: PetscRandom randObj = NULL;
1333: PetscFunctionBegin;
1337: VecCheckAssembled(x);
1338: PetscCall(VecSetErrorIfLocked(x, 1));
1340: if (!rctx) {
1341: PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)x), &randObj));
1342: PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
1343: PetscCall(PetscRandomSetFromOptions(randObj));
1344: rctx = randObj;
1345: }
1347: PetscCall(PetscLogEventBegin(VEC_SetRandom, x, rctx, 0, 0));
1348: PetscUseTypeMethod(x, setrandom, rctx);
1349: PetscCall(PetscLogEventEnd(VEC_SetRandom, x, rctx, 0, 0));
1351: PetscCall(PetscRandomDestroy(&randObj));
1352: PetscCall(PetscObjectStateIncrease((PetscObject)x));
1353: PetscFunctionReturn(PETSC_SUCCESS);
1354: }
1356: /*@
1357: VecZeroEntries - puts a `0.0` in each element of a vector
1359: Logically Collective
1361: Input Parameter:
1362: . vec - The vector
1364: Level: beginner
1366: Note:
1367: If the norm of the vector is known to be zero then this skips the unneeded zeroing process
1369: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`, `VecSet()`, `VecSetValues()`
1370: @*/
1371: PetscErrorCode VecZeroEntries(Vec vec)
1372: {
1373: PetscFunctionBegin;
1374: PetscCall(VecSet(vec, 0));
1375: PetscFunctionReturn(PETSC_SUCCESS);
1376: }
1378: /*
1379: VecSetTypeFromOptions_Private - Sets the type of vector from user options. Defaults to a PETSc sequential vector on one
1380: processor and a PETSc MPI vector on more than one processor.
1382: Collective
1384: Input Parameter:
1385: . vec - The vector
1387: Level: intermediate
1389: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`, `VecSetType()`
1390: */
1391: static PetscErrorCode VecSetTypeFromOptions_Private(Vec vec, PetscOptionItems *PetscOptionsObject)
1392: {
1393: PetscBool opt;
1394: VecType defaultType;
1395: char typeName[256];
1396: PetscMPIInt size;
1398: PetscFunctionBegin;
1399: if (((PetscObject)vec)->type_name) defaultType = ((PetscObject)vec)->type_name;
1400: else {
1401: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
1402: if (size > 1) defaultType = VECMPI;
1403: else defaultType = VECSEQ;
1404: }
1406: PetscCall(VecRegisterAll());
1407: PetscCall(PetscOptionsFList("-vec_type", "Vector type", "VecSetType", VecList, defaultType, typeName, 256, &opt));
1408: if (opt) {
1409: PetscCall(VecSetType(vec, typeName));
1410: } else {
1411: PetscCall(VecSetType(vec, defaultType));
1412: }
1413: PetscFunctionReturn(PETSC_SUCCESS);
1414: }
1416: /*@
1417: VecSetFromOptions - Configures the vector from the options database.
1419: Collective
1421: Input Parameter:
1422: . vec - The vector
1424: Level: beginner
1426: Notes:
1427: To see all options, run your program with the -help option.
1429: Must be called after `VecCreate()` but before the vector is used.
1431: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`
1432: @*/
1433: PetscErrorCode VecSetFromOptions(Vec vec)
1434: {
1435: PetscBool flg;
1436: PetscInt bind_below = 0;
1438: PetscFunctionBegin;
1441: PetscObjectOptionsBegin((PetscObject)vec);
1442: /* Handle vector type options */
1443: PetscCall(VecSetTypeFromOptions_Private(vec, PetscOptionsObject));
1445: /* Handle specific vector options */
1446: PetscTryTypeMethod(vec, setfromoptions, PetscOptionsObject);
1448: /* Bind to CPU if below a user-specified size threshold.
1449: * This perhaps belongs in the options for the GPU Vec types, but VecBindToCPU() does nothing when called on non-GPU types,
1450: * and putting it here makes is more maintainable than duplicating this for all. */
1451: PetscCall(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));
1452: if (flg && vec->map->n < bind_below) PetscCall(VecBindToCPU(vec, PETSC_TRUE));
1454: /* process any options handlers added with PetscObjectAddOptionsHandler() */
1455: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)vec, PetscOptionsObject));
1456: PetscOptionsEnd();
1457: PetscFunctionReturn(PETSC_SUCCESS);
1458: }
1460: /*@
1461: VecSetSizes - Sets the local and global sizes, and checks to determine compatibility of the sizes
1463: Collective
1465: Input Parameters:
1466: + v - the vector
1467: . n - the local size (or `PETSC_DECIDE` to have it set)
1468: - N - the global size (or `PETSC_DETERMINE` to have it set)
1470: Level: intermediate
1472: Notes:
1473: `N` cannot be `PETSC_DETERMINE` if `n` is `PETSC_DECIDE`
1475: If one processor calls this with `N` of `PETSC_DETERMINE` then all processors must, otherwise the program will hang.
1477: If `n` is not `PETSC_DECIDE`, then the value determines the `PetscLayout` of the vector and the ranges returned by
1478: `VecGetOwnershipRange()` and `VecGetOwnershipRanges()`
1480: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecCreateSeq()`, `VecCreateMPI()`, `VecGetSize()`, `PetscSplitOwnership()`, `PetscLayout`,
1481: `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`, `MatSetSizes()`
1482: @*/
1483: PetscErrorCode VecSetSizes(Vec v, PetscInt n, PetscInt N)
1484: {
1485: PetscFunctionBegin;
1487: if (N >= 0) {
1489: PetscCheck(n <= N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Local size %" PetscInt_FMT " cannot be larger than global size %" PetscInt_FMT, n, N);
1490: }
1491: PetscCheck(!(v->map->n >= 0 || v->map->N >= 0) || !(v->map->n != n || v->map->N != N), PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot change/reset vector sizes to %" PetscInt_FMT " local %" PetscInt_FMT " global after previously setting them to %" PetscInt_FMT " local %" PetscInt_FMT " global", n, N,
1492: v->map->n, v->map->N);
1493: v->map->n = n;
1494: v->map->N = N;
1495: PetscTryTypeMethod(v, create);
1496: v->ops->create = NULL;
1497: PetscFunctionReturn(PETSC_SUCCESS);
1498: }
1500: /*@
1501: VecSetBlockSize - Sets the block size for future calls to `VecSetValuesBlocked()`
1502: and `VecSetValuesBlockedLocal()`.
1504: Logically Collective
1506: Input Parameters:
1507: + v - the vector
1508: - bs - the blocksize
1510: Level: advanced
1512: Note:
1513: All vectors obtained by `VecDuplicate()` inherit the same blocksize.
1515: Vectors obtained with `DMCreateGlobalVector()` and `DMCreateLocalVector()` generally already have a blocksize set based on the state of the `DM`
1517: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecGetBlockSize()`
1518: @*/
1519: PetscErrorCode VecSetBlockSize(Vec v, PetscInt bs)
1520: {
1521: PetscFunctionBegin;
1524: PetscCall(PetscLayoutSetBlockSize(v->map, bs));
1525: v->bstash.bs = bs; /* use the same blocksize for the vec's block-stash */
1526: PetscFunctionReturn(PETSC_SUCCESS);
1527: }
1529: /*@
1530: VecGetBlockSize - Gets the blocksize for the vector, i.e. what is used for `VecSetValuesBlocked()`
1531: and `VecSetValuesBlockedLocal()`.
1533: Not Collective
1535: Input Parameter:
1536: . v - the vector
1538: Output Parameter:
1539: . bs - the blocksize
1541: Level: advanced
1543: Note:
1544: All vectors obtained by `VecDuplicate()` inherit the same blocksize.
1546: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecSetBlockSize()`
1547: @*/
1548: PetscErrorCode VecGetBlockSize(Vec v, PetscInt *bs)
1549: {
1550: PetscFunctionBegin;
1552: PetscAssertPointer(bs, 2);
1553: PetscCall(PetscLayoutGetBlockSize(v->map, bs));
1554: PetscFunctionReturn(PETSC_SUCCESS);
1555: }
1557: /*@
1558: VecSetOptionsPrefix - Sets the prefix used for searching for all
1559: `Vec` options in the database.
1561: Logically Collective
1563: Input Parameters:
1564: + v - the `Vec` context
1565: - prefix - the prefix to prepend to all option names
1567: Level: advanced
1569: Note:
1570: A hyphen (-) must NOT be given at the beginning of the prefix name.
1571: The first character of all runtime options is AUTOMATICALLY the hyphen.
1573: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`
1574: @*/
1575: PetscErrorCode VecSetOptionsPrefix(Vec v, const char prefix[])
1576: {
1577: PetscFunctionBegin;
1579: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)v, prefix));
1580: PetscFunctionReturn(PETSC_SUCCESS);
1581: }
1583: /*@
1584: VecAppendOptionsPrefix - Appends to the prefix used for searching for all
1585: `Vec` options in the database.
1587: Logically Collective
1589: Input Parameters:
1590: + v - the `Vec` context
1591: - prefix - the prefix to prepend to all option names
1593: Level: advanced
1595: Note:
1596: A hyphen (-) must NOT be given at the beginning of the prefix name.
1597: The first character of all runtime options is AUTOMATICALLY the hyphen.
1599: .seealso: [](ch_vectors), `Vec`, `VecGetOptionsPrefix()`
1600: @*/
1601: PetscErrorCode VecAppendOptionsPrefix(Vec v, const char prefix[])
1602: {
1603: PetscFunctionBegin;
1605: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)v, prefix));
1606: PetscFunctionReturn(PETSC_SUCCESS);
1607: }
1609: /*@
1610: VecGetOptionsPrefix - Sets the prefix used for searching for all
1611: Vec options in the database.
1613: Not Collective
1615: Input Parameter:
1616: . v - the `Vec` context
1618: Output Parameter:
1619: . prefix - pointer to the prefix string used
1621: Level: advanced
1623: Fortran Notes:
1624: The user must pass in a string `prefix` of
1625: sufficient length to hold the prefix.
1627: .seealso: [](ch_vectors), `Vec`, `VecAppendOptionsPrefix()`
1628: @*/
1629: PetscErrorCode VecGetOptionsPrefix(Vec v, const char *prefix[])
1630: {
1631: PetscFunctionBegin;
1633: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)v, prefix));
1634: PetscFunctionReturn(PETSC_SUCCESS);
1635: }
1637: /*@C
1638: VecGetState - Gets the state of a `Vec`.
1640: Not Collective
1642: Input Parameter:
1643: . v - the `Vec` context
1645: Output Parameter:
1646: . state - the object state
1648: Level: advanced
1650: Note:
1651: Object state is an integer which gets increased every time
1652: the object is changed. By saving and later querying the object state
1653: one can determine whether information about the object is still current.
1655: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `PetscObjectStateGet()`
1656: @*/
1657: PetscErrorCode VecGetState(Vec v, PetscObjectState *state)
1658: {
1659: PetscFunctionBegin;
1661: PetscAssertPointer(state, 2);
1662: PetscCall(PetscObjectStateGet((PetscObject)v, state));
1663: PetscFunctionReturn(PETSC_SUCCESS);
1664: }
1666: /*@
1667: VecSetUp - Sets up the internal vector data structures for the later use.
1669: Collective
1671: Input Parameter:
1672: . v - the `Vec` context
1674: Level: advanced
1676: Notes:
1677: For basic use of the `Vec` classes the user need not explicitly call
1678: `VecSetUp()`, since these actions will happen automatically.
1680: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDestroy()`
1681: @*/
1682: PetscErrorCode VecSetUp(Vec v)
1683: {
1684: PetscMPIInt size;
1686: PetscFunctionBegin;
1688: PetscCheck(v->map->n >= 0 || v->map->N >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Sizes not set");
1689: if (!((PetscObject)v)->type_name) {
1690: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)v), &size));
1691: if (size == 1) {
1692: PetscCall(VecSetType(v, VECSEQ));
1693: } else {
1694: PetscCall(VecSetType(v, VECMPI));
1695: }
1696: }
1697: PetscFunctionReturn(PETSC_SUCCESS);
1698: }
1700: /*
1701: These currently expose the PetscScalar/PetscReal in updating the
1702: cached norm. If we push those down into the implementation these
1703: will become independent of PetscScalar/PetscReal
1704: */
1706: PetscErrorCode VecCopyAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1707: {
1708: PetscBool flgs[4];
1709: PetscReal norms[4] = {0.0, 0.0, 0.0, 0.0};
1711: PetscFunctionBegin;
1716: if (x == y) PetscFunctionReturn(PETSC_SUCCESS);
1717: VecCheckSameLocalSize(x, 1, y, 2);
1718: VecCheckAssembled(x);
1719: PetscCall(VecSetErrorIfLocked(y, 2));
1721: #if !defined(PETSC_USE_MIXED_PRECISION)
1722: for (PetscInt i = 0; i < 4; i++) PetscCall(PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], norms[i], flgs[i]));
1723: #endif
1725: PetscCall(PetscLogEventBegin(VEC_Copy, x, y, 0, 0));
1726: #if defined(PETSC_USE_MIXED_PRECISION)
1727: extern PetscErrorCode VecGetArray(Vec, double **);
1728: extern PetscErrorCode VecRestoreArray(Vec, double **);
1729: extern PetscErrorCode VecGetArray(Vec, float **);
1730: extern PetscErrorCode VecRestoreArray(Vec, float **);
1731: extern PetscErrorCode VecGetArrayRead(Vec, const double **);
1732: extern PetscErrorCode VecRestoreArrayRead(Vec, const double **);
1733: extern PetscErrorCode VecGetArrayRead(Vec, const float **);
1734: extern PetscErrorCode VecRestoreArrayRead(Vec, const float **);
1735: if ((((PetscObject)x)->precision == PETSC_PRECISION_SINGLE) && (((PetscObject)y)->precision == PETSC_PRECISION_DOUBLE)) {
1736: PetscInt i, n;
1737: const float *xx;
1738: double *yy;
1739: PetscCall(VecGetArrayRead(x, &xx));
1740: PetscCall(VecGetArray(y, &yy));
1741: PetscCall(VecGetLocalSize(x, &n));
1742: for (i = 0; i < n; i++) yy[i] = xx[i];
1743: PetscCall(VecRestoreArrayRead(x, &xx));
1744: PetscCall(VecRestoreArray(y, &yy));
1745: } else if ((((PetscObject)x)->precision == PETSC_PRECISION_DOUBLE) && (((PetscObject)y)->precision == PETSC_PRECISION_SINGLE)) {
1746: PetscInt i, n;
1747: float *yy;
1748: const double *xx;
1749: PetscCall(VecGetArrayRead(x, &xx));
1750: PetscCall(VecGetArray(y, &yy));
1751: PetscCall(VecGetLocalSize(x, &n));
1752: for (i = 0; i < n; i++) yy[i] = (float)xx[i];
1753: PetscCall(VecRestoreArrayRead(x, &xx));
1754: PetscCall(VecRestoreArray(y, &yy));
1755: } else PetscUseTypeMethod(x, copy, y);
1756: #else
1757: VecMethodDispatch(x, dctx, VecAsyncFnName(Copy), copy, (Vec, Vec, PetscDeviceContext), y);
1758: #endif
1760: PetscCall(PetscObjectStateIncrease((PetscObject)y));
1761: #if !defined(PETSC_USE_MIXED_PRECISION)
1762: for (PetscInt i = 0; i < 4; i++) {
1763: if (flgs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], norms[i]));
1764: }
1765: #endif
1767: PetscCall(PetscLogEventEnd(VEC_Copy, x, y, 0, 0));
1768: PetscFunctionReturn(PETSC_SUCCESS);
1769: }
1771: /*@
1772: VecCopy - Copies a vector `y = x`
1774: Logically Collective
1776: Input Parameter:
1777: . x - the vector
1779: Output Parameter:
1780: . y - the copy
1782: Level: beginner
1784: Note:
1785: For default parallel PETSc vectors, both `x` and `y` must be distributed in
1786: the same manner; local copies are done.
1788: Developer Notes:
1789: `PetscCheckSameTypeAndComm`(x,1,y,2) is not used on these vectors because we allow one
1790: of the vectors to be sequential and one to be parallel so long as both have the same
1791: local sizes. This is used in some internal functions in PETSc.
1793: .seealso: [](ch_vectors), `Vec`, `VecDuplicate()`
1794: @*/
1795: PetscErrorCode VecCopy(Vec x, Vec y)
1796: {
1797: PetscFunctionBegin;
1798: PetscCall(VecCopyAsync_Private(x, y, NULL));
1799: PetscFunctionReturn(PETSC_SUCCESS);
1800: }
1802: PetscErrorCode VecSwapAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1803: {
1804: PetscReal normxs[4], normys[4];
1805: PetscBool flgxs[4], flgys[4];
1807: PetscFunctionBegin;
1812: PetscCheckSameTypeAndComm(x, 1, y, 2);
1813: VecCheckSameSize(x, 1, y, 2);
1814: VecCheckAssembled(x);
1815: VecCheckAssembled(y);
1816: PetscCall(VecSetErrorIfLocked(x, 1));
1817: PetscCall(VecSetErrorIfLocked(y, 2));
1819: for (PetscInt i = 0; i < 4; i++) {
1820: PetscCall(PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], normxs[i], flgxs[i]));
1821: PetscCall(PetscObjectComposedDataGetReal((PetscObject)y, NormIds[i], normys[i], flgys[i]));
1822: }
1824: PetscCall(PetscLogEventBegin(VEC_Swap, x, y, 0, 0));
1825: VecMethodDispatch(x, dctx, VecAsyncFnName(Swap), swap, (Vec, Vec, PetscDeviceContext), y);
1826: PetscCall(PetscLogEventEnd(VEC_Swap, x, y, 0, 0));
1828: PetscCall(PetscObjectStateIncrease((PetscObject)x));
1829: PetscCall(PetscObjectStateIncrease((PetscObject)y));
1830: for (PetscInt i = 0; i < 4; i++) {
1831: if (flgxs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], normxs[i]));
1832: if (flgys[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)x, NormIds[i], normys[i]));
1833: }
1834: PetscFunctionReturn(PETSC_SUCCESS);
1835: }
1836: /*@
1837: VecSwap - Swaps the values between two vectors, `x` and `y`.
1839: Logically Collective
1841: Input Parameters:
1842: + x - the first vector
1843: - y - the second vector
1845: Level: advanced
1847: .seealso: [](ch_vectors), `Vec`, `VecSet()`
1848: @*/
1849: PetscErrorCode VecSwap(Vec x, Vec y)
1850: {
1851: PetscFunctionBegin;
1852: PetscCall(VecSwapAsync_Private(x, y, NULL));
1853: PetscFunctionReturn(PETSC_SUCCESS);
1854: }
1856: /*@
1857: VecStashViewFromOptions - Processes command line options to determine if/how a `VecStash` object is to be viewed.
1859: Collective
1861: Input Parameters:
1862: + obj - the `Vec` containing a stash
1863: . bobj - optional other object that provides the prefix
1864: - optionname - option to activate viewing
1866: Level: intermediate
1868: Developer Notes:
1869: This cannot use `PetscObjectViewFromOptions()` because it takes a `Vec` as an argument but does not use `VecView()`
1871: .seealso: [](ch_vectors), `Vec`, `VecStashSetInitialSize()`
1872: @*/
1873: PetscErrorCode VecStashViewFromOptions(Vec obj, PetscObject bobj, const char optionname[])
1874: {
1875: PetscViewer viewer;
1876: PetscBool flg;
1877: PetscViewerFormat format;
1878: char *prefix;
1880: PetscFunctionBegin;
1881: prefix = bobj ? bobj->prefix : ((PetscObject)obj)->prefix;
1882: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)obj), ((PetscObject)obj)->options, prefix, optionname, &viewer, &format, &flg));
1883: if (flg) {
1884: PetscCall(PetscViewerPushFormat(viewer, format));
1885: PetscCall(VecStashView(obj, viewer));
1886: PetscCall(PetscViewerPopFormat(viewer));
1887: PetscCall(PetscViewerDestroy(&viewer));
1888: }
1889: PetscFunctionReturn(PETSC_SUCCESS);
1890: }
1892: /*@
1893: VecStashView - Prints the entries in the vector stash and block stash.
1895: Collective
1897: Input Parameters:
1898: + v - the vector
1899: - viewer - the viewer
1901: Level: advanced
1903: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`
1904: @*/
1905: PetscErrorCode VecStashView(Vec v, PetscViewer viewer)
1906: {
1907: PetscMPIInt rank;
1908: PetscInt i, j;
1909: PetscBool match;
1910: VecStash *s;
1911: PetscScalar val;
1913: PetscFunctionBegin;
1916: PetscCheckSameComm(v, 1, viewer, 2);
1918: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &match));
1919: PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_SUP, "Stash viewer only works with ASCII viewer not %s", ((PetscObject)v)->type_name);
1920: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1921: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)v), &rank));
1922: s = &v->bstash;
1924: /* print block stash */
1925: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1926: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector Block stash size %" PetscInt_FMT " block size %" PetscInt_FMT "\n", rank, s->n, s->bs));
1927: for (i = 0; i < s->n; i++) {
1928: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " ", rank, s->idx[i]));
1929: for (j = 0; j < s->bs; j++) {
1930: val = s->array[i * s->bs + j];
1931: #if defined(PETSC_USE_COMPLEX)
1932: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "(%18.16e %18.16e) ", (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
1933: #else
1934: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%18.16e ", (double)val));
1935: #endif
1936: }
1937: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1938: }
1939: PetscCall(PetscViewerFlush(viewer));
1941: s = &v->stash;
1943: /* print basic stash */
1944: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector stash size %" PetscInt_FMT "\n", rank, s->n));
1945: for (i = 0; i < s->n; i++) {
1946: val = s->array[i];
1947: #if defined(PETSC_USE_COMPLEX)
1948: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " (%18.16e %18.16e) ", rank, s->idx[i], (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
1949: #else
1950: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " %18.16e\n", rank, s->idx[i], (double)val));
1951: #endif
1952: }
1953: PetscCall(PetscViewerFlush(viewer));
1954: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1955: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1956: PetscFunctionReturn(PETSC_SUCCESS);
1957: }
1959: PetscErrorCode PetscOptionsGetVec(PetscOptions options, const char prefix[], const char key[], Vec v, PetscBool *set)
1960: {
1961: PetscInt i, N, rstart, rend;
1962: PetscScalar *xx;
1963: PetscReal *xreal;
1964: PetscBool iset;
1966: PetscFunctionBegin;
1967: PetscCall(VecGetOwnershipRange(v, &rstart, &rend));
1968: PetscCall(VecGetSize(v, &N));
1969: PetscCall(PetscCalloc1(N, &xreal));
1970: PetscCall(PetscOptionsGetRealArray(options, prefix, key, xreal, &N, &iset));
1971: if (iset) {
1972: PetscCall(VecGetArray(v, &xx));
1973: for (i = rstart; i < rend; i++) xx[i - rstart] = xreal[i];
1974: PetscCall(VecRestoreArray(v, &xx));
1975: }
1976: PetscCall(PetscFree(xreal));
1977: if (set) *set = iset;
1978: PetscFunctionReturn(PETSC_SUCCESS);
1979: }
1981: /*@
1982: VecGetLayout - get `PetscLayout` describing a vector layout
1984: Not Collective
1986: Input Parameter:
1987: . x - the vector
1989: Output Parameter:
1990: . map - the layout
1992: Level: developer
1994: Note:
1995: The layout determines what vector elements are contained on each MPI process
1997: .seealso: [](ch_vectors), `PetscLayout`, `Vec`, `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
1998: @*/
1999: PetscErrorCode VecGetLayout(Vec x, PetscLayout *map)
2000: {
2001: PetscFunctionBegin;
2003: PetscAssertPointer(map, 2);
2004: *map = x->map;
2005: PetscFunctionReturn(PETSC_SUCCESS);
2006: }
2008: /*@
2009: VecSetLayout - set `PetscLayout` describing vector layout
2011: Not Collective
2013: Input Parameters:
2014: + x - the vector
2015: - map - the layout
2017: Level: developer
2019: Note:
2020: It is normally only valid to replace the layout with a layout known to be equivalent.
2022: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2023: @*/
2024: PetscErrorCode VecSetLayout(Vec x, PetscLayout map)
2025: {
2026: PetscFunctionBegin;
2028: PetscCall(PetscLayoutReference(map, &x->map));
2029: PetscFunctionReturn(PETSC_SUCCESS);
2030: }
2032: /*@
2033: VecFlag - set infinity into the local part of the vector on any subset of MPI processes
2035: Logically Collective
2037: Input Parameters:
2038: + xin - the vector, can be `NULL` but only if on all processes
2039: - flg - indicates if this processes portion of the vector should be set to infinity
2041: Level: developer
2043: Note:
2044: This removes the values from the vector norm cache for all processes by calling `PetscObjectIncrease()`.
2046: This is used for any subset of MPI processes to indicate an failure in a solver, after the next use of `VecNorm()` if
2047: `KSPCheckNorm()` detects an infinity and at least one of the MPI processes has a not converged reason then the `KSP`
2048: object collectively is labeled as not converged.
2050: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2051: @*/
2052: PetscErrorCode VecFlag(Vec xin, PetscInt flg)
2053: {
2054: // use of variables one and zero over just doing 1.0/0.0 is deliberate. MSVC complains that
2055: // we are dividing by zero in the latter case (ostensibly because dividing by 0 is UB, but
2056: // only for *integers* not floats).
2057: const PetscScalar one = 1.0, zero = 0.0;
2058: PetscScalar inf;
2060: PetscFunctionBegin;
2061: if (!xin) PetscFunctionReturn(PETSC_SUCCESS);
2063: PetscCall(PetscObjectStateIncrease((PetscObject)xin));
2064: if (flg) {
2065: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2066: inf = one / zero;
2067: PetscCall(PetscFPTrapPop());
2068: if (xin->ops->set) {
2069: PetscUseTypeMethod(xin, set, inf);
2070: } else {
2071: PetscInt n;
2072: PetscScalar *xx;
2074: PetscCall(VecGetLocalSize(xin, &n));
2075: PetscCall(VecGetArrayWrite(xin, &xx));
2076: for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2077: PetscCall(VecRestoreArrayWrite(xin, &xx));
2078: }
2079: }
2080: PetscFunctionReturn(PETSC_SUCCESS);
2081: }
2083: /*@
2084: VecSetInf - set infinity into the local part of the vector
2086: Not Collective
2088: Input Parameters:
2089: . xin - the vector
2091: Level: developer
2093: Note:
2094: Deprecated, see `VecFlag()`
2095: This is used for any subset of MPI processes to indicate an failure in a solver, after the next use of `VecNorm()` if
2096: `KSPCheckNorm()` detects an infinity and at least one of the MPI processes has a not converged reason then the `KSP`
2097: object collectively is labeled as not converged.
2099: This cannot be called if `xin` has a cached norm available
2101: .seealso: [](ch_vectors), `VecFlag()`, `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSizes()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2102: @*/
2103: PetscErrorCode VecSetInf(Vec xin)
2104: {
2105: // use of variables one and zero over just doing 1.0/0.0 is deliberate. MSVC complains that
2106: // we are dividing by zero in the latter case (ostensibly because dividing by 0 is UB, but
2107: // only for *integers* not floats).
2108: const PetscScalar one = 1.0, zero = 0.0;
2109: PetscScalar inf;
2110: PetscBool flg;
2112: PetscFunctionBegin;
2113: PetscCall(VecNormAvailable(xin, NORM_2, &flg, NULL));
2114: PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot call VecSetInf() if the vector has a cached norm");
2115: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2116: inf = one / zero;
2117: PetscCall(PetscFPTrapPop());
2118: if (xin->ops->set) {
2119: PetscUseTypeMethod(xin, set, inf);
2120: } else {
2121: PetscInt n;
2122: PetscScalar *xx;
2124: PetscCall(VecGetLocalSize(xin, &n));
2125: PetscCall(VecGetArrayWrite(xin, &xx));
2126: for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2127: PetscCall(VecRestoreArrayWrite(xin, &xx));
2128: }
2129: PetscFunctionReturn(PETSC_SUCCESS);
2130: }
2132: /*@
2133: VecBindToCPU - marks a vector to temporarily stay on the CPU and perform computations on the CPU
2135: Logically collective
2137: Input Parameters:
2138: + v - the vector
2139: - flg - bind to the CPU if value of `PETSC_TRUE`
2141: Level: intermediate
2143: .seealso: [](ch_vectors), `Vec`, `VecBoundToCPU()`
2144: @*/
2145: PetscErrorCode VecBindToCPU(Vec v, PetscBool flg)
2146: {
2147: PetscFunctionBegin;
2150: #if defined(PETSC_HAVE_DEVICE)
2151: if (v->boundtocpu == flg) PetscFunctionReturn(PETSC_SUCCESS);
2152: v->boundtocpu = flg;
2153: PetscTryTypeMethod(v, bindtocpu, flg);
2154: #endif
2155: PetscFunctionReturn(PETSC_SUCCESS);
2156: }
2158: /*@
2159: VecBoundToCPU - query if a vector is bound to the CPU
2161: Not collective
2163: Input Parameter:
2164: . v - the vector
2166: Output Parameter:
2167: . flg - the logical flag
2169: Level: intermediate
2171: .seealso: [](ch_vectors), `Vec`, `VecBindToCPU()`
2172: @*/
2173: PetscErrorCode VecBoundToCPU(Vec v, PetscBool *flg)
2174: {
2175: PetscFunctionBegin;
2177: PetscAssertPointer(flg, 2);
2178: #if defined(PETSC_HAVE_DEVICE)
2179: *flg = v->boundtocpu;
2180: #else
2181: *flg = PETSC_TRUE;
2182: #endif
2183: PetscFunctionReturn(PETSC_SUCCESS);
2184: }
2186: /*@
2187: VecSetBindingPropagates - Sets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects
2189: Input Parameters:
2190: + v - the vector
2191: - flg - flag indicating whether the boundtocpu flag should be propagated
2193: Level: developer
2195: Notes:
2196: 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.
2197: The created vectors will also have their bindingpropagates flag set to true.
2199: Developer Notes:
2200: If a `DMDA` has the `-dm_bind_below option` set to true, then vectors created by `DMCreateGlobalVector()` will have `VecSetBindingPropagates()` called on them to
2201: set their bindingpropagates flag to true.
2203: .seealso: [](ch_vectors), `Vec`, `MatSetBindingPropagates()`, `VecGetBindingPropagates()`
2204: @*/
2205: PetscErrorCode VecSetBindingPropagates(Vec v, PetscBool flg)
2206: {
2207: PetscFunctionBegin;
2209: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2210: v->bindingpropagates = flg;
2211: #endif
2212: PetscFunctionReturn(PETSC_SUCCESS);
2213: }
2215: /*@
2216: VecGetBindingPropagates - Gets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects
2218: Input Parameter:
2219: . v - the vector
2221: Output Parameter:
2222: . flg - flag indicating whether the boundtocpu flag will be propagated
2224: Level: developer
2226: .seealso: [](ch_vectors), `Vec`, `VecSetBindingPropagates()`
2227: @*/
2228: PetscErrorCode VecGetBindingPropagates(Vec v, PetscBool *flg)
2229: {
2230: PetscFunctionBegin;
2232: PetscAssertPointer(flg, 2);
2233: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2234: *flg = v->bindingpropagates;
2235: #else
2236: *flg = PETSC_FALSE;
2237: #endif
2238: PetscFunctionReturn(PETSC_SUCCESS);
2239: }
2241: /*@C
2242: VecSetPinnedMemoryMin - Set the minimum data size for which pinned memory will be used for host (CPU) allocations.
2244: Logically Collective
2246: Input Parameters:
2247: + v - the vector
2248: - mbytes - minimum data size in bytes
2250: Options Database Key:
2251: . -vec_pinned_memory_min <size> - minimum size (in bytes) for an allocation to use pinned memory on host.
2253: Level: developer
2255: Note:
2256: Specifying -1 ensures that pinned memory will never be used.
2258: .seealso: [](ch_vectors), `Vec`, `VecGetPinnedMemoryMin()`
2259: @*/
2260: PetscErrorCode VecSetPinnedMemoryMin(Vec v, size_t mbytes)
2261: {
2262: PetscFunctionBegin;
2264: #if PetscDefined(HAVE_DEVICE)
2265: v->minimum_bytes_pinned_memory = mbytes;
2266: #endif
2267: PetscFunctionReturn(PETSC_SUCCESS);
2268: }
2270: /*@C
2271: VecGetPinnedMemoryMin - Get the minimum data size for which pinned memory will be used for host (CPU) allocations.
2273: Logically Collective
2275: Input Parameter:
2276: . v - the vector
2278: Output Parameter:
2279: . mbytes - minimum data size in bytes
2281: Level: developer
2283: .seealso: [](ch_vectors), `Vec`, `VecSetPinnedMemoryMin()`
2284: @*/
2285: PetscErrorCode VecGetPinnedMemoryMin(Vec v, size_t *mbytes)
2286: {
2287: PetscFunctionBegin;
2289: PetscAssertPointer(mbytes, 2);
2290: #if PetscDefined(HAVE_DEVICE)
2291: *mbytes = v->minimum_bytes_pinned_memory;
2292: #endif
2293: PetscFunctionReturn(PETSC_SUCCESS);
2294: }
2296: /*@
2297: VecGetOffloadMask - Get the offload mask of a `Vec`
2299: Not Collective
2301: Input Parameter:
2302: . v - the vector
2304: Output Parameter:
2305: . mask - corresponding `PetscOffloadMask` enum value.
2307: Level: intermediate
2309: .seealso: [](ch_vectors), `Vec`, `VecCreateSeqCUDA()`, `VecCreateSeqViennaCL()`, `VecGetArray()`, `VecGetType()`
2310: @*/
2311: PetscErrorCode VecGetOffloadMask(Vec v, PetscOffloadMask *mask)
2312: {
2313: PetscFunctionBegin;
2315: PetscAssertPointer(mask, 2);
2316: *mask = v->offloadmask;
2317: PetscFunctionReturn(PETSC_SUCCESS);
2318: }
2320: #if !defined(PETSC_HAVE_VIENNACL)
2321: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLContext(Vec v, PETSC_UINTPTR_T *ctx)
2322: {
2323: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_context");
2324: }
2326: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLQueue(Vec v, PETSC_UINTPTR_T *queue)
2327: {
2328: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_command_queue");
2329: }
2331: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMem(Vec v, PETSC_UINTPTR_T *queue)
2332: {
2333: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2334: }
2336: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemRead(Vec v, PETSC_UINTPTR_T *queue)
2337: {
2338: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2339: }
2341: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemWrite(Vec v, PETSC_UINTPTR_T *queue)
2342: {
2343: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2344: }
2346: PETSC_EXTERN PetscErrorCode VecViennaCLRestoreCLMemWrite(Vec v)
2347: {
2348: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to restore a Vec's cl_mem");
2349: }
2350: #endif
2352: static PetscErrorCode VecErrorWeightedNorms_Basic(Vec U, Vec Y, Vec E, NormType wnormtype, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol, PetscReal ignore_max, PetscReal *norm, PetscInt *norm_loc, PetscReal *norma, PetscInt *norma_loc, PetscReal *normr, PetscInt *normr_loc)
2353: {
2354: const PetscScalar *u, *y;
2355: const PetscScalar *atola = NULL, *rtola = NULL, *erra = NULL;
2356: PetscInt n, n_loc = 0, na_loc = 0, nr_loc = 0;
2357: PetscReal nrm = 0, nrma = 0, nrmr = 0, err_loc[6];
2359: PetscFunctionBegin;
2360: #define SkipSmallValue(a, b, tol) \
2361: if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue
2363: PetscCall(VecGetLocalSize(U, &n));
2364: PetscCall(VecGetArrayRead(U, &u));
2365: PetscCall(VecGetArrayRead(Y, &y));
2366: if (E) PetscCall(VecGetArrayRead(E, &erra));
2367: if (vatol) PetscCall(VecGetArrayRead(vatol, &atola));
2368: if (vrtol) PetscCall(VecGetArrayRead(vrtol, &rtola));
2369: for (PetscInt i = 0; i < n; i++) {
2370: PetscReal err, tol, tola, tolr;
2372: SkipSmallValue(y[i], u[i], ignore_max);
2373: atol = atola ? PetscRealPart(atola[i]) : atol;
2374: rtol = rtola ? PetscRealPart(rtola[i]) : rtol;
2375: err = erra ? PetscAbsScalar(erra[i]) : PetscAbsScalar(y[i] - u[i]);
2376: tola = atol;
2377: tolr = rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
2378: tol = tola + tolr;
2379: if (tola > 0.) {
2380: if (wnormtype == NORM_INFINITY) nrma = PetscMax(nrma, err / tola);
2381: else nrma += PetscSqr(err / tola);
2382: na_loc++;
2383: }
2384: if (tolr > 0.) {
2385: if (wnormtype == NORM_INFINITY) nrmr = PetscMax(nrmr, err / tolr);
2386: else nrmr += PetscSqr(err / tolr);
2387: nr_loc++;
2388: }
2389: if (tol > 0.) {
2390: if (wnormtype == NORM_INFINITY) nrm = PetscMax(nrm, err / tol);
2391: else nrm += PetscSqr(err / tol);
2392: n_loc++;
2393: }
2394: }
2395: if (E) PetscCall(VecRestoreArrayRead(E, &erra));
2396: if (vatol) PetscCall(VecRestoreArrayRead(vatol, &atola));
2397: if (vrtol) PetscCall(VecRestoreArrayRead(vrtol, &rtola));
2398: PetscCall(VecRestoreArrayRead(U, &u));
2399: PetscCall(VecRestoreArrayRead(Y, &y));
2400: #undef SkipSmallValue
2402: err_loc[0] = nrm;
2403: err_loc[1] = nrma;
2404: err_loc[2] = nrmr;
2405: err_loc[3] = (PetscReal)n_loc;
2406: err_loc[4] = (PetscReal)na_loc;
2407: err_loc[5] = (PetscReal)nr_loc;
2408: if (wnormtype == NORM_2) {
2409: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2410: } else {
2411: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)U)));
2412: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc + 3, 3, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2413: }
2414: if (wnormtype == NORM_2) {
2415: *norm = PetscSqrtReal(err_loc[0]);
2416: *norma = PetscSqrtReal(err_loc[1]);
2417: *normr = PetscSqrtReal(err_loc[2]);
2418: } else {
2419: *norm = err_loc[0];
2420: *norma = err_loc[1];
2421: *normr = err_loc[2];
2422: }
2423: *norm_loc = (PetscInt)err_loc[3];
2424: *norma_loc = (PetscInt)err_loc[4];
2425: *normr_loc = (PetscInt)err_loc[5];
2426: PetscFunctionReturn(PETSC_SUCCESS);
2427: }
2429: /*@
2430: VecErrorWeightedNorms - compute a weighted norm of the difference between two vectors
2432: Collective
2434: Input Parameters:
2435: + U - first vector to be compared
2436: . Y - second vector to be compared
2437: . E - optional third vector representing the error (if not provided, the error is ||U-Y||)
2438: . wnormtype - norm type
2439: . atol - scalar for absolute tolerance
2440: . vatol - vector representing per-entry absolute tolerances (can be ``NULL``)
2441: . rtol - scalar for relative tolerance
2442: . vrtol - vector representing per-entry relative tolerances (can be ``NULL``)
2443: - ignore_max - ignore values smaller then this value in absolute terms.
2445: Output Parameters:
2446: + norm - weighted norm
2447: . norm_loc - number of vector locations used for the weighted norm
2448: . norma - weighted norm based on the absolute tolerance
2449: . norma_loc - number of vector locations used for the absolute weighted norm
2450: . normr - weighted norm based on the relative tolerance
2451: - normr_loc - number of vector locations used for the relative weighted norm
2453: Level: developer
2455: Notes:
2456: This is primarily used for computing weighted local truncation errors in ``TS``.
2458: .seealso: [](ch_vectors), `Vec`, `NormType`, `TSErrorWeightedNorm()`, `TSErrorWeightedENorm()`
2459: @*/
2460: PetscErrorCode VecErrorWeightedNorms(Vec U, Vec Y, Vec E, NormType wnormtype, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol, PetscReal ignore_max, PetscReal *norm, PetscInt *norm_loc, PetscReal *norma, PetscInt *norma_loc, PetscReal *normr, PetscInt *normr_loc)
2461: {
2462: PetscFunctionBegin;
2467: if (E) {
2470: }
2473: if (vatol) {
2476: }
2478: if (vrtol) {
2481: }
2483: PetscAssertPointer(norm, 10);
2484: PetscAssertPointer(norm_loc, 11);
2485: PetscAssertPointer(norma, 12);
2486: PetscAssertPointer(norma_loc, 13);
2487: PetscAssertPointer(normr, 14);
2488: PetscAssertPointer(normr_loc, 15);
2489: PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)U), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
2491: /* There are potentially 5 vectors involved, some of them may happen to be of different type or bound to cpu.
2492: Here we check that they all implement the same operation and call it if so.
2493: Otherwise, we call the _Basic implementation that always works (provided VecGetArrayRead is implemented). */
2494: PetscBool sameop = (PetscBool)(U->ops->errorwnorm && U->ops->errorwnorm == Y->ops->errorwnorm);
2495: if (sameop && E) sameop = (PetscBool)(U->ops->errorwnorm == E->ops->errorwnorm);
2496: if (sameop && vatol) sameop = (PetscBool)(U->ops->errorwnorm == vatol->ops->errorwnorm);
2497: if (sameop && vrtol) sameop = (PetscBool)(U->ops->errorwnorm == vrtol->ops->errorwnorm);
2498: if (sameop) PetscUseTypeMethod(U, errorwnorm, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc);
2499: else PetscCall(VecErrorWeightedNorms_Basic(U, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc));
2500: PetscFunctionReturn(PETSC_SUCCESS);
2501: }