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:     PetscInt ncoo_i;
200:     IS       is_coo_i;

202:     PetscCall(PetscIntCast(ncoo, &ncoo_i));
203:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncoo_i, coo_i, PETSC_COPY_VALUES, &is_coo_i));
204:     PetscCall(PetscObjectCompose((PetscObject)x, "__PETSc_coo_i", (PetscObject)is_coo_i));
205:     PetscCall(ISDestroy(&is_coo_i));
206:   }
207:   PetscCall(PetscLogEventEnd(VEC_SetPreallocateCOO, x, 0, 0, 0));
208:   PetscFunctionReturn(PETSC_SUCCESS);
209: }

211: /*@
212:   VecSetPreallocationCOOLocal - set preallocation for vectors using a coordinate format of the entries with local indices

214:   Collective

216:   Input Parameters:
217: + x     - vector being preallocated
218: . ncoo  - number of entries
219: - coo_i - row indices (local numbering; may be modified)

221:   Level: beginner

223:   Notes:
224:   This and `VecSetValuesCOO()` provide an alternative API to using `VecSetValuesLocal()` to provide vector values.

226:   This API is particularly efficient for use on GPUs.

228:   The local indices are translated using the local to global mapping, thus `VecSetLocalToGlobalMapping()` must have been
229:   called prior to this function.

231:   The indices coo_i may be modified within this function. They might be translated to corresponding global
232:   indices, but the caller should not rely on them having any specific value after this function returns. The arrays
233:   can be freed or reused immediately after this function returns.

235:   Entries can be repeated. Negative indices and remote indices might be allowed. see `VecSetPreallocationCOO()`.

237: .seealso: [](ch_vectors), `Vec`, `VecSetPreallocationCOO()`, `VecSetValuesCOO()`
238: @*/
239: PetscErrorCode VecSetPreallocationCOOLocal(Vec x, PetscCount ncoo, PetscInt coo_i[])
240: {
241:   PetscInt               ncoo_i;
242:   ISLocalToGlobalMapping ltog;

244:   PetscFunctionBegin;
247:   if (ncoo) PetscAssertPointer(coo_i, 3);
248:   PetscCall(PetscIntCast(ncoo, &ncoo_i));
249:   PetscCall(PetscLayoutSetUp(x->map));
250:   PetscCall(VecGetLocalToGlobalMapping(x, &ltog));
251:   if (ltog) PetscCall(ISLocalToGlobalMappingApply(ltog, ncoo_i, coo_i, coo_i));
252:   PetscCall(VecSetPreallocationCOO(x, ncoo, coo_i));
253:   PetscFunctionReturn(PETSC_SUCCESS);
254: }

256: /*@
257:   VecSetValuesCOO - set values at once in a vector preallocated using `VecSetPreallocationCOO()`

259:   Collective

261:   Input Parameters:
262: + x     - vector being set
263: . coo_v - the value array
264: - imode - the insert mode

266:   Level: beginner

268:   Note:
269:   This and `VecSetPreallocationCOO() or ``VecSetPreallocationCOOLocal()` provide an alternative API to using `VecSetValues()` to provide vector values.

271:   This API is particularly efficient for use on GPUs.

273:   The values must follow the order of the indices prescribed with `VecSetPreallocationCOO()` or `VecSetPreallocationCOOLocal()`.
274:   When repeated entries are specified in the COO indices the `coo_v` values are first properly summed, regardless of the value of `imode`.
275:   The imode flag indicates if `coo_v` must be added to the current values of the vector (`ADD_VALUES`) or overwritten (`INSERT_VALUES`).
276:   `VecAssemblyBegin()` and `VecAssemblyEnd()` do not need to be called after this routine. It automatically handles the assembly process.

278: .seealso: [](ch_vectors), `Vec`, `VecSetPreallocationCOO()`, `VecSetPreallocationCOOLocal()`, `VecSetValues()`
279: @*/
280: PetscErrorCode VecSetValuesCOO(Vec x, const PetscScalar coo_v[], InsertMode imode)
281: {
282:   PetscFunctionBegin;
286:   PetscCall(PetscLogEventBegin(VEC_SetValuesCOO, x, 0, 0, 0));
287:   if (x->ops->setvaluescoo) {
288:     PetscUseTypeMethod(x, setvaluescoo, coo_v, imode);
289:     PetscCall(PetscObjectStateIncrease((PetscObject)x));
290:   } else {
291:     IS              is_coo_i;
292:     const PetscInt *coo_i;
293:     PetscInt        ncoo;
294:     PetscMemType    mtype;

296:     PetscCall(PetscGetMemType(coo_v, &mtype));
297:     PetscCheck(mtype == PETSC_MEMTYPE_HOST, PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONG, "The basic VecSetValuesCOO() only supports v[] on host");
298:     PetscCall(PetscObjectQuery((PetscObject)x, "__PETSc_coo_i", (PetscObject *)&is_coo_i));
299:     PetscCheck(is_coo_i, PetscObjectComm((PetscObject)x), PETSC_ERR_COR, "Missing coo_i IS");
300:     PetscCall(ISGetLocalSize(is_coo_i, &ncoo));
301:     PetscCall(ISGetIndices(is_coo_i, &coo_i));
302:     if (imode != ADD_VALUES) PetscCall(VecZeroEntries(x));
303:     PetscCall(VecSetValues(x, ncoo, coo_i, coo_v, ADD_VALUES));
304:     PetscCall(ISRestoreIndices(is_coo_i, &coo_i));
305:     PetscCall(VecAssemblyBegin(x));
306:     PetscCall(VecAssemblyEnd(x));
307:   }
308:   PetscCall(PetscLogEventEnd(VEC_SetValuesCOO, x, 0, 0, 0));
309:   PetscFunctionReturn(PETSC_SUCCESS);
310: }

312: 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))
313: {
314:   PetscErrorCode (*async_fn)(Vec, Vec, Vec, PetscDeviceContext) = NULL;

316:   PetscFunctionBegin;
323:   PetscCheckSameTypeAndComm(x, 2, y, 3);
324:   PetscCheckSameTypeAndComm(y, 3, w, 1);
325:   VecCheckSameSize(w, 1, x, 2);
326:   VecCheckSameSize(w, 1, y, 3);
327:   VecCheckAssembled(x);
328:   VecCheckAssembled(y);
329:   PetscCall(VecSetErrorIfLocked(w, 1));

332:   if (dctx) PetscCall(PetscObjectQueryFunction((PetscObject)w, async_name, &async_fn));
333:   if (event) PetscCall(PetscLogEventBegin(event, x, y, w, 0));
334:   if (async_fn) {
335:     PetscCall((*async_fn)(w, x, y, dctx));
336:   } else {
337:     PetscCall((*pointwise_op)(w, x, y));
338:   }
339:   if (event) PetscCall(PetscLogEventEnd(event, x, y, w, 0));
340:   PetscCall(PetscObjectStateIncrease((PetscObject)w));
341:   PetscFunctionReturn(PETSC_SUCCESS);
342: }

344: PetscErrorCode VecPointwiseMaxAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
345: {
346:   PetscFunctionBegin;
347:   // REVIEW ME: no log event?
348:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMax), w->ops->pointwisemax));
349:   PetscFunctionReturn(PETSC_SUCCESS);
350: }

352: /*@
353:   VecPointwiseMax - Computes the component-wise maximum `w[i] = max(x[i], y[i])`.

355:   Logically Collective

357:   Input Parameters:
358: + x - the first input vector
359: - y - the second input vector

361:   Output Parameter:
362: . w - the result

364:   Level: advanced

366:   Notes:
367:   Any subset of the `x`, `y`, and `w` may be the same vector.

369:   For complex numbers compares only the real part

371: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
372: @*/
373: PetscErrorCode VecPointwiseMax(Vec w, Vec x, Vec y)
374: {
375:   PetscFunctionBegin;
376:   PetscCall(VecPointwiseMaxAsync_Private(w, x, y, NULL));
377:   PetscFunctionReturn(PETSC_SUCCESS);
378: }

380: PetscErrorCode VecPointwiseMinAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
381: {
382:   PetscFunctionBegin;
383:   // REVIEW ME: no log event?
384:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMin), w->ops->pointwisemin));
385:   PetscFunctionReturn(PETSC_SUCCESS);
386: }

388: /*@
389:   VecPointwiseMin - Computes the component-wise minimum `w[i] = min(x[i], y[i])`.

391:   Logically Collective

393:   Input Parameters:
394: + x - the first input vector
395: - y - the second input vector

397:   Output Parameter:
398: . w - the result

400:   Level: advanced

402:   Notes:
403:   Any subset of the `x`, `y`, and `w` may be the same vector.

405:   For complex numbers compares only the real part

407: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
408: @*/
409: PetscErrorCode VecPointwiseMin(Vec w, Vec x, Vec y)
410: {
411:   PetscFunctionBegin;
412:   PetscCall(VecPointwiseMinAsync_Private(w, x, y, NULL));
413:   PetscFunctionReturn(PETSC_SUCCESS);
414: }

416: PetscErrorCode VecPointwiseMaxAbsAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
417: {
418:   PetscFunctionBegin;
419:   // REVIEW ME: no log event?
420:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMaxAbs), w->ops->pointwisemaxabs));
421:   PetscFunctionReturn(PETSC_SUCCESS);
422: }

424: /*@
425:   VecPointwiseMaxAbs - Computes the component-wise maximum of the absolute values `w[i] = max(abs(x[i]), abs(y[i]))`.

427:   Logically Collective

429:   Input Parameters:
430: + x - the first input vector
431: - y - the second input vector

433:   Output Parameter:
434: . w - the result

436:   Level: advanced

438:   Notes:
439:   Any subset of the `x`, `y`, and `w` may be the same vector.

441: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMax()`, `VecMaxPointwiseDivide()`
442: @*/
443: PetscErrorCode VecPointwiseMaxAbs(Vec w, Vec x, Vec y)
444: {
445:   PetscFunctionBegin;
446:   PetscCall(VecPointwiseMaxAbsAsync_Private(w, x, y, NULL));
447:   PetscFunctionReturn(PETSC_SUCCESS);
448: }

450: PetscErrorCode VecPointwiseDivideAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
451: {
452:   PetscFunctionBegin;
453:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseDivide, VecAsyncFnName(PointwiseDivide), w->ops->pointwisedivide));
454:   PetscFunctionReturn(PETSC_SUCCESS);
455: }

457: /*@
458:   VecPointwiseDivide - Computes the component-wise division `w[i] = x[i] / y[i]`.

460:   Logically Collective

462:   Input Parameters:
463: + x - the numerator vector
464: - y - the denominator vector

466:   Output Parameter:
467: . w - the result

469:   Level: advanced

471:   Note:
472:   Any subset of the `x`, `y`, and `w` may be the same vector.

474: .seealso: [](ch_vectors), `Vec`, `VecPointwiseMult()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
475: @*/
476: PetscErrorCode VecPointwiseDivide(Vec w, Vec x, Vec y)
477: {
478:   PetscFunctionBegin;
479:   PetscCall(VecPointwiseDivideAsync_Private(w, x, y, NULL));
480:   PetscFunctionReturn(PETSC_SUCCESS);
481: }

483: PetscErrorCode VecPointwiseMultAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
484: {
485:   PetscFunctionBegin;
487:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseMult, VecAsyncFnName(PointwiseMult), w->ops->pointwisemult));
488:   PetscFunctionReturn(PETSC_SUCCESS);
489: }

491: /*@
492:   VecPointwiseMult - Computes the component-wise multiplication `w[i] = x[i] * y[i]`.

494:   Logically Collective

496:   Input Parameters:
497: + x - the first vector
498: - y - the second vector

500:   Output Parameter:
501: . w - the result

503:   Level: advanced

505:   Note:
506:   Any subset of the `x`, `y`, and `w` may be the same vector.

508: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
509: @*/
510: PetscErrorCode VecPointwiseMult(Vec w, Vec x, Vec y)
511: {
512:   PetscFunctionBegin;
513:   PetscCall(VecPointwiseMultAsync_Private(w, x, y, NULL));
514:   PetscFunctionReturn(PETSC_SUCCESS);
515: }

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

520:   Collective

522:   Input Parameter:
523: . v - a vector to mimic

525:   Output Parameter:
526: . newv - location to put new vector

528:   Level: beginner

530:   Notes:
531:   `VecDuplicate()` DOES NOT COPY the vector entries, but rather allocates storage
532:   for the new vector.  Use `VecCopy()` to copy a vector.

534:   Use `VecDestroy()` to free the space. Use `VecDuplicateVecs()` to get several
535:   vectors.

537: .seealso: [](ch_vectors), `Vec`, `VecDestroy()`, `VecDuplicateVecs()`, `VecCreate()`, `VecCopy()`
538: @*/
539: PetscErrorCode VecDuplicate(Vec v, Vec *newv)
540: {
541:   PetscFunctionBegin;
543:   PetscAssertPointer(newv, 2);
545:   PetscUseTypeMethod(v, duplicate, newv);
546: #if PetscDefined(HAVE_DEVICE)
547:   if (v->boundtocpu && v->bindingpropagates) {
548:     PetscCall(VecSetBindingPropagates(*newv, PETSC_TRUE));
549:     PetscCall(VecBindToCPU(*newv, PETSC_TRUE));
550:   }
551: #endif
552:   PetscCall(PetscObjectStateIncrease((PetscObject)*newv));
553:   PetscFunctionReturn(PETSC_SUCCESS);
554: }

556: /*@
557:   VecDestroy - Destroys a vector.

559:   Collective

561:   Input Parameter:
562: . v - the vector

564:   Level: beginner

566: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDuplicate()`, `VecDestroyVecs()`
567: @*/
568: PetscErrorCode VecDestroy(Vec *v)
569: {
570:   PetscFunctionBegin;
571:   PetscAssertPointer(v, 1);
572:   if (!*v) PetscFunctionReturn(PETSC_SUCCESS);
574:   if (--((PetscObject)*v)->refct > 0) {
575:     *v = NULL;
576:     PetscFunctionReturn(PETSC_SUCCESS);
577:   }

579:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*v));
580:   /* destroy the internal part */
581:   PetscTryTypeMethod(*v, destroy);
582:   PetscCall(PetscFree((*v)->defaultrandtype));
583:   /* destroy the external/common part */
584:   PetscCall(PetscLayoutDestroy(&(*v)->map));
585:   PetscCall(PetscHeaderDestroy(v));
586:   PetscFunctionReturn(PETSC_SUCCESS);
587: }

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

592:   Collective

594:   Input Parameters:
595: + m - the number of vectors to obtain
596: - v - a vector to mimic

598:   Output Parameter:
599: . V - location to put pointer to array of vectors

601:   Level: intermediate

603:   Note:
604:   Use `VecDestroyVecs()` to free the space. Use `VecDuplicate()` to form a single
605:   vector.

607:   Fortran Note:
608: .vb
609:   Vec, pointer :: V(:)
610: .ve

612: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDestroyVecs()`, `VecDuplicate()`, `VecCreate()`
613: @*/
614: PetscErrorCode VecDuplicateVecs(Vec v, PetscInt m, Vec *V[])
615: {
616:   PetscFunctionBegin;
618:   PetscAssertPointer(V, 3);
620:   PetscUseTypeMethod(v, duplicatevecs, m, V);
621: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
622:   if (v->boundtocpu && v->bindingpropagates) {
623:     PetscInt i;

625:     for (i = 0; i < m; i++) {
626:       /* Since ops->duplicatevecs might itself propagate the value of boundtocpu,
627:        * avoid unnecessary overhead by only calling VecBindToCPU() if the vector isn't already bound. */
628:       if (!(*V)[i]->boundtocpu) {
629:         PetscCall(VecSetBindingPropagates((*V)[i], PETSC_TRUE));
630:         PetscCall(VecBindToCPU((*V)[i], PETSC_TRUE));
631:       }
632:     }
633:   }
634: #endif
635:   PetscFunctionReturn(PETSC_SUCCESS);
636: }

638: /*@C
639:   VecDestroyVecs - Frees a block of vectors obtained with `VecDuplicateVecs()`.

641:   Collective

643:   Input Parameters:
644: + m  - the number of vectors previously obtained, if zero no vectors are destroyed
645: - vv - pointer to pointer to array of vector pointers, if `NULL` no vectors are destroyed

647:   Level: intermediate

649: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDuplicateVecs()`, `VecDestroyVecsf90()`
650: @*/
651: PetscErrorCode VecDestroyVecs(PetscInt m, Vec *vv[])
652: {
653:   PetscFunctionBegin;
654:   PetscAssertPointer(vv, 2);
655:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of vectors %" PetscInt_FMT, m);
656:   if (!m || !*vv) {
657:     *vv = NULL;
658:     PetscFunctionReturn(PETSC_SUCCESS);
659:   }
662:   PetscCall((*(**vv)->ops->destroyvecs)(m, *vv));
663:   *vv = NULL;
664:   PetscFunctionReturn(PETSC_SUCCESS);
665: }

667: /*@
668:   VecViewFromOptions - View a vector based on values in the options database

670:   Collective

672:   Input Parameters:
673: + A    - the vector
674: . obj  - optional object that provides the options prefix for this viewing, use 'NULL' to use the prefix of `A`
675: - name - command line option

677:   Level: intermediate

679:   Note:
680:   See `PetscObjectViewFromOptions()` to see the `PetscViewer` and PetscViewerFormat` available

682: .seealso: [](ch_vectors), `Vec`, `VecView`, `PetscObjectViewFromOptions()`, `VecCreate()`
683: @*/
684: PetscErrorCode VecViewFromOptions(Vec A, PeOp PetscObject obj, const char name[])
685: {
686:   PetscFunctionBegin;
688:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
689:   PetscFunctionReturn(PETSC_SUCCESS);
690: }

692: /*@
693:   VecView - Views a vector object.

695:   Collective

697:   Input Parameters:
698: + vec    - the vector
699: - viewer - an optional `PetscViewer` visualization context

701:   Level: beginner

703:   Notes:
704:   The available visualization contexts include
705: +     `PETSC_VIEWER_STDOUT_SELF` - for sequential vectors
706: .     `PETSC_VIEWER_STDOUT_WORLD` - for parallel vectors created on `PETSC_COMM_WORLD`
707: -     `PETSC_VIEWER_STDOUT`_(comm) - for parallel vectors created on MPI communicator comm

709:   You can change the format the vector is printed using the
710:   option `PetscViewerPushFormat()`.

712:   The user can open alternative viewers with
713: +    `PetscViewerASCIIOpen()` - Outputs vector to a specified file
714: .    `PetscViewerBinaryOpen()` - Outputs vector in binary to a
715:   specified file; corresponding input uses `VecLoad()`
716: .    `PetscViewerDrawOpen()` - Outputs vector to an X window display
717: .    `PetscViewerSocketOpen()` - Outputs vector to Socket viewer
718: -    `PetscViewerHDF5Open()` - Outputs vector to HDF5 file viewer

720:   The user can call `PetscViewerPushFormat()` to specify the output
721:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
722:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
723: +    `PETSC_VIEWER_DEFAULT` - default, prints vector contents
724: .    `PETSC_VIEWER_ASCII_MATLAB` - prints vector contents in MATLAB format
725: .    `PETSC_VIEWER_ASCII_INDEX` - prints vector contents, including indices of vector elements
726: -    `PETSC_VIEWER_ASCII_COMMON` - prints vector contents, using a
727:   format common among all vector types

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

731:   In the debugger you can do call `VecView`(v,0) to display the vector. (The same holds for any PETSc object viewer).

733:   Notes for binary viewer:
734:   If you pass multiple vectors to a binary viewer you can read them back in the same order
735:   with `VecLoad()`.

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

743:   See the manual page for `VecLoad()` on the exact format the binary viewer stores
744:   the values in the file.

746:   Notes for HDF5 Viewer:
747:   The name of the `Vec` (given with `PetscObjectSetName()` is the name that is used
748:   for the object in the HDF5 file. If you wish to store the same Vec into multiple
749:   datasets in the same file (typically with different values), you must change its
750:   name each time before calling the `VecView()`. To load the same vector,
751:   the name of the Vec object passed to `VecLoad()` must be the same.

753:   If the block size of the vector is greater than 1 then it is used as the first dimension in the HDF5 array.
754:   If the function `PetscViewerHDF5SetBaseDimension2()`is called then even if the block size is one it will
755:   be used as the first dimension in the HDF5 array (that is the HDF5 array will always be two dimensional)
756:   See also `PetscViewerHDF5SetTimestep()` which adds an additional complication to reading and writing `Vec`
757:   with the HDF5 viewer.

759: .seealso: [](ch_vectors), `Vec`, `VecViewFromOptions()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`,
760:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
761:           `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
762: @*/
763: PetscErrorCode VecView(Vec vec, PetscViewer viewer)
764: {
765:   PetscBool         iascii;
766:   PetscViewerFormat format;
767:   PetscMPIInt       size;

769:   PetscFunctionBegin;
772:   VecCheckAssembled(vec);
773:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
775:   PetscCall(PetscViewerGetFormat(viewer, &format));
776:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
777:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

779:   PetscCheck(!vec->stash.n && !vec->bstash.n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call VecAssemblyBegin/End() before viewing this vector");

781:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
782:   if (iascii) {
783:     PetscInt rows, bs;

785:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)vec, viewer));
786:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
787:       PetscCall(PetscViewerASCIIPushTab(viewer));
788:       PetscCall(VecGetSize(vec, &rows));
789:       PetscCall(VecGetBlockSize(vec, &bs));
790:       if (bs != 1) {
791:         PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT ", bs=%" PetscInt_FMT "\n", rows, bs));
792:       } else {
793:         PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT "\n", rows));
794:       }
795:       PetscCall(PetscViewerASCIIPopTab(viewer));
796:     }
797:   }
798:   PetscCall(VecLockReadPush(vec));
799:   PetscCall(PetscLogEventBegin(VEC_View, vec, viewer, 0, 0));
800:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && vec->ops->viewnative) {
801:     PetscUseTypeMethod(vec, viewnative, viewer);
802:   } else {
803:     PetscUseTypeMethod(vec, view, viewer);
804:   }
805:   PetscCall(VecLockReadPop(vec));
806:   PetscCall(PetscLogEventEnd(VEC_View, vec, viewer, 0, 0));
807:   PetscFunctionReturn(PETSC_SUCCESS);
808: }

810: #if defined(PETSC_USE_DEBUG)
811: #include <../src/sys/totalview/tv_data_display.h>
812: PETSC_UNUSED static int TV_display_type(const struct _p_Vec *v)
813: {
814:   const PetscScalar *values;
815:   char               type[32];

817:   TV_add_row("Local rows", "int", &v->map->n);
818:   TV_add_row("Global rows", "int", &v->map->N);
819:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)v)->type_name);
820:   PetscCall(VecGetArrayRead((Vec)v, &values));
821:   PetscCall(PetscSNPrintf(type, 32, "double[%" PetscInt_FMT "]", v->map->n));
822:   TV_add_row("values", type, values);
823:   PetscCall(VecRestoreArrayRead((Vec)v, &values));
824:   return TV_format_OK;
825: }
826: #endif

828: /*@C
829:   VecViewNative - Views a vector object with the original type specific viewer

831:   Collective

833:   Input Parameters:
834: + vec    - the vector
835: - viewer - an optional `PetscViewer` visualization context

837:   Level: developer

839:   Note:
840:   This can be used with, for example, vectors obtained with `DMCreateGlobalVector()` for a `DMDA` to display the vector
841:   in the PETSc storage format (each MPI process values follow the previous MPI processes) instead of the "natural" grid
842:   ordering.

844: .seealso: [](ch_vectors), `Vec`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`, `VecView()`
845:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
846:           `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
847: @*/
848: PetscErrorCode VecViewNative(Vec vec, PetscViewer viewer)
849: {
850:   PetscFunctionBegin;
853:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
855:   PetscUseTypeMethod(vec, viewnative, viewer);
856:   PetscFunctionReturn(PETSC_SUCCESS);
857: }

859: /*@
860:   VecGetSize - Returns the global number of elements of the vector.

862:   Not Collective

864:   Input Parameter:
865: . x - the vector

867:   Output Parameter:
868: . size - the global length of the vector

870:   Level: beginner

872: .seealso: [](ch_vectors), `Vec`, `VecGetLocalSize()`
873: @*/
874: PetscErrorCode VecGetSize(Vec x, PetscInt *size)
875: {
876:   PetscFunctionBegin;
878:   PetscAssertPointer(size, 2);
880:   PetscUseTypeMethod(x, getsize, size);
881:   PetscFunctionReturn(PETSC_SUCCESS);
882: }

884: /*@
885:   VecGetLocalSize - Returns the number of elements of the vector stored
886:   in local memory (that is on this MPI process)

888:   Not Collective

890:   Input Parameter:
891: . x - the vector

893:   Output Parameter:
894: . size - the length of the local piece of the vector

896:   Level: beginner

898: .seealso: [](ch_vectors), `Vec`, `VecGetSize()`
899: @*/
900: PetscErrorCode VecGetLocalSize(Vec x, PetscInt *size)
901: {
902:   PetscFunctionBegin;
904:   PetscAssertPointer(size, 2);
906:   PetscUseTypeMethod(x, getlocalsize, size);
907:   PetscFunctionReturn(PETSC_SUCCESS);
908: }

910: /*@
911:   VecGetOwnershipRange - Returns the range of indices owned by
912:   this process. The vector is laid out with the
913:   first `n1` elements on the first processor, next `n2` elements on the
914:   second, etc.  For certain parallel layouts this range may not be
915:   well defined.

917:   Not Collective

919:   Input Parameter:
920: . x - the vector

922:   Output Parameters:
923: + low  - the first local element, pass in `NULL` if not interested
924: - high - one more than the last local element, pass in `NULL` if not interested

926:   Level: beginner

928:   Notes:
929:   If the `Vec` was obtained from a `DM` with `DMCreateGlobalVector()`, then the range values are determined by the specific `DM`.

931:   If the `Vec` was created directly the range values are determined by the local size passed to `VecSetSizes()` or `VecCreateMPI()`.
932:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

934:   The high argument is one more than the last element stored locally.

936:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
937:   the local values in the vector.

939: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRanges()`, `PetscSplitOwnership()`,
940:           `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
941: @*/
942: PetscErrorCode VecGetOwnershipRange(Vec x, PetscInt *low, PetscInt *high)
943: {
944:   PetscFunctionBegin;
947:   if (low) PetscAssertPointer(low, 2);
948:   if (high) PetscAssertPointer(high, 3);
949:   if (low) *low = x->map->rstart;
950:   if (high) *high = x->map->rend;
951:   PetscFunctionReturn(PETSC_SUCCESS);
952: }

954: /*@C
955:   VecGetOwnershipRanges - Returns the range of indices owned by EACH processor,
956:   The vector is laid out with the
957:   first `n1` elements on the first processor, next `n2` elements on the
958:   second, etc.  For certain parallel layouts this range may not be
959:   well defined.

961:   Not Collective

963:   Input Parameter:
964: . x - the vector

966:   Output Parameter:
967: . ranges - array of length `size` + 1 with the start and end+1 for each process

969:   Level: beginner

971:   Notes:
972:   If the `Vec` was obtained from a `DM` with `DMCreateGlobalVector()`, then the range values are determined by the specific `DM`.

974:   If the `Vec` was created directly the range values are determined by the local size passed to `VecSetSizes()` or `VecCreateMPI()`.
975:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

977:   The high argument is one more than the last element stored locally.

979:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
980:   the local values in the vector.

982:   The high argument is one more than the last element stored locally.

984:   If `ranges` are used after all vectors that share the ranges has been destroyed, then the program will crash accessing `ranges`.

986:   Fortran Note:
987:   The argument `ranges` must be declared as
988: .vb
989:   PetscInt, pointer :: ranges(:)
990: .ve
991:   and you have to return it with a call to `VecRestoreOwnershipRanges()` when no longer needed

993: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRange()`, `PetscSplitOwnership()`,
994:           `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
995: @*/
996: PetscErrorCode VecGetOwnershipRanges(Vec x, const PetscInt *ranges[])
997: {
998:   PetscFunctionBegin;
1001:   PetscCall(PetscLayoutGetRanges(x->map, ranges));
1002:   PetscFunctionReturn(PETSC_SUCCESS);
1003: }

1005: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1006: /*@
1007:   VecSetOption - Sets an option for controlling a vector's behavior.

1009:   Collective

1011:   Input Parameters:
1012: + x    - the vector
1013: . op   - the option
1014: - flag - turn the option on or off

1016:   Supported Options:
1017: + `VEC_IGNORE_OFF_PROC_ENTRIES` - which causes `VecSetValues()` to ignore
1018:           entries destined to be stored on a separate processor. This can be used
1019:           to eliminate the global reduction in the `VecAssemblyBegin()` if you know
1020:           that you have only used `VecSetValues()` to set local elements
1021: . `VEC_IGNORE_NEGATIVE_INDICES` - which means you can pass negative indices
1022:           in ix in calls to `VecSetValues()` or `VecGetValues()`. These rows are simply
1023:           ignored.
1024: - `VEC_SUBSET_OFF_PROC_ENTRIES` - which causes `VecAssemblyBegin()` to assume that the off-process
1025:           entries will always be a subset (possibly equal) of the off-process entries set on the
1026:           first assembly which had a true `VEC_SUBSET_OFF_PROC_ENTRIES` and the vector has not
1027:           changed this flag afterwards. If this assembly is not such first assembly, then this
1028:           assembly can reuse the communication pattern setup in that first assembly, thus avoiding
1029:           a global reduction. Subsequent assemblies setting off-process values should use the same
1030:           InsertMode as the first assembly.

1032:   Level: intermediate

1034:   Developer Notes:
1035:   The `InsertMode` restriction could be removed by packing the stash messages out of place.

1037: .seealso: [](ch_vectors), `Vec`, `VecSetValues()`
1038: @*/
1039: PetscErrorCode VecSetOption(Vec x, VecOption op, PetscBool flag)
1040: {
1041:   PetscFunctionBegin;
1044:   PetscTryTypeMethod(x, setoption, op, flag);
1045:   PetscFunctionReturn(PETSC_SUCCESS);
1046: }

1048: /* Default routines for obtaining and releasing; */
1049: /* may be used by any implementation */
1050: PetscErrorCode VecDuplicateVecs_Default(Vec w, PetscInt m, Vec *V[])
1051: {
1052:   PetscFunctionBegin;
1053:   PetscCheck(m > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "m must be > 0: m = %" PetscInt_FMT, m);
1054:   PetscCall(PetscMalloc1(m, V));
1055:   for (PetscInt i = 0; i < m; i++) PetscCall(VecDuplicate(w, *V + i));
1056:   PetscFunctionReturn(PETSC_SUCCESS);
1057: }

1059: PetscErrorCode VecDestroyVecs_Default(PetscInt m, Vec v[])
1060: {
1061:   PetscInt i;

1063:   PetscFunctionBegin;
1064:   PetscAssertPointer(v, 2);
1065:   for (i = 0; i < m; i++) PetscCall(VecDestroy(&v[i]));
1066:   PetscCall(PetscFree(v));
1067:   PetscFunctionReturn(PETSC_SUCCESS);
1068: }

1070: /*@
1071:   VecResetArray - Resets a vector to use its default memory. Call this
1072:   after the use of `VecPlaceArray()`.

1074:   Not Collective

1076:   Input Parameter:
1077: . vec - the vector

1079:   Level: developer

1081: .seealso: [](ch_vectors), `Vec`, `VecGetArray()`, `VecRestoreArray()`, `VecReplaceArray()`, `VecPlaceArray()`
1082: @*/
1083: PetscErrorCode VecResetArray(Vec vec)
1084: {
1085:   PetscFunctionBegin;
1088:   PetscUseTypeMethod(vec, resetarray);
1089:   PetscCall(PetscObjectStateIncrease((PetscObject)vec));
1090:   PetscFunctionReturn(PETSC_SUCCESS);
1091: }

1093: /*@
1094:   VecLoad - Loads a vector that has been stored in binary or HDF5 format
1095:   with `VecView()`.

1097:   Collective

1099:   Input Parameters:
1100: + vec    - the newly loaded vector, this needs to have been created with `VecCreate()` or
1101:            some related function before the call to `VecLoad()`.
1102: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
1103:            HDF5 file viewer, obtained from `PetscViewerHDF5Open()`

1105:   Level: intermediate

1107:   Notes:
1108:   Defaults to the standard `VECSEQ` or `VECMPI`, if you want some other type of `Vec` call `VecSetFromOptions()`
1109:   before calling this.

1111:   The input file must contain the full global vector, as
1112:   written by the routine `VecView()`.

1114:   If the type or size of `vec` is not set before a call to `VecLoad()`, PETSc
1115:   sets the type and the local and global sizes based on the vector it is reading in. If type and/or
1116:   sizes are already set, then the same are used.

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

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

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

1133:   Notes for advanced users when using the binary viewer:
1134:   Most users should not need to know the details of the binary storage
1135:   format, since `VecLoad()` and `VecView()` completely hide these details.
1136:   But for anyone who's interested, the standard binary vector storage
1137:   format is
1138: .vb
1139:      PetscInt    VEC_FILE_CLASSID
1140:      PetscInt    number of rows
1141:      PetscScalar *values of all entries
1142: .ve

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

1149: .seealso: [](ch_vectors), `Vec`, `PetscViewerBinaryOpen()`, `VecView()`, `MatLoad()`
1150: @*/
1151: PetscErrorCode VecLoad(Vec vec, PetscViewer viewer)
1152: {
1153:   PetscBool         isbinary, ishdf5, isadios, isexodusii, iscgns;
1154:   PetscViewerFormat format;

1156:   PetscFunctionBegin;
1159:   PetscCheckSameComm(vec, 1, viewer, 2);
1160:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1161:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
1162:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERCGNS, &iscgns));
1163:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERADIOS, &isadios));
1164:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWEREXODUSII, &isexodusii));
1165:   PetscCheck(isbinary || ishdf5 || isadios || isexodusii || iscgns, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");

1167:   PetscCall(VecSetErrorIfLocked(vec, 1));
1168:   if (!((PetscObject)vec)->type_name && !vec->ops->create) PetscCall(VecSetType(vec, VECSTANDARD));
1169:   PetscCall(PetscLogEventBegin(VEC_Load, viewer, 0, 0, 0));
1170:   PetscCall(PetscViewerGetFormat(viewer, &format));
1171:   if (format == PETSC_VIEWER_NATIVE && vec->ops->loadnative) {
1172:     PetscUseTypeMethod(vec, loadnative, viewer);
1173:   } else {
1174:     PetscUseTypeMethod(vec, load, viewer);
1175:   }
1176:   PetscCall(PetscLogEventEnd(VEC_Load, viewer, 0, 0, 0));
1177:   PetscFunctionReturn(PETSC_SUCCESS);
1178: }

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

1183:   Logically Collective

1185:   Input Parameter:
1186: . vec - the vector

1188:   Output Parameter:
1189: . vec - the vector reciprocal

1191:   Level: intermediate

1193:   Note:
1194:   Vector entries with value 0.0 are not changed

1196: .seealso: [](ch_vectors), `Vec`, `VecLog()`, `VecExp()`, `VecSqrtAbs()`
1197: @*/
1198: PetscErrorCode VecReciprocal(Vec vec)
1199: {
1200:   PetscFunctionBegin;
1201:   PetscCall(VecReciprocalAsync_Private(vec, NULL));
1202:   PetscFunctionReturn(PETSC_SUCCESS);
1203: }

1205: /*@C
1206:   VecSetOperation - Allows the user to override a particular vector operation.

1208:   Logically Collective; No Fortran Support

1210:   Input Parameters:
1211: + vec - The vector to modify
1212: . op  - The name of the operation
1213: - f   - The function that provides the operation.

1215:   Notes:
1216:   `f` may be `NULL` to remove the operation from `vec`. Depending on the operation this may be
1217:   allowed, however some always expect a valid function. In these cases an error will be raised
1218:   when calling the interface routine in question.

1220:   See `VecOperation` for an up-to-date list of override-able operations. The operations listed
1221:   there have the form `VECOP_<OPERATION>`, where `<OPERATION>` is the suffix (in all capital
1222:   letters) of the public interface routine (e.g., `VecView()` -> `VECOP_VIEW`).

1224:   Overriding a particular `Vec`'s operation has no affect on any other `Vec`s past, present,
1225:   or future. The user should also note that overriding a method is "destructive"; the previous
1226:   method is not retained in any way.

1228:   Level: advanced

1230:   Example Usage:
1231: .vb
1232:   // some new VecView() implementation, must have the same signature as the function it seeks
1233:   // to replace
1234:   PetscErrorCode UserVecView(Vec x, PetscViewer viewer)
1235:   {
1236:     PetscFunctionBeginUser;
1237:     // ...
1238:     PetscFunctionReturn(PETSC_SUCCESS);
1239:   }

1241:   // Create a VECMPI which has a pre-defined VecView() implementation
1242:   VecCreateMPI(comm, n, N, &x);
1243:   // Calls the VECMPI implementation for VecView()
1244:   VecView(x, viewer);

1246:   VecSetOperation(x, VECOP_VIEW, (void (*)(void))UserVecView);
1247:   // Now calls UserVecView()
1248:   VecView(x, viewer);
1249: .ve

1251: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `MatShellSetOperation()`
1252: @*/
1253: PetscErrorCode VecSetOperation(Vec vec, VecOperation op, void (*f)(void))
1254: {
1255:   PetscFunctionBegin;
1257:   if (op == VECOP_VIEW && !vec->ops->viewnative) {
1258:     vec->ops->viewnative = vec->ops->view;
1259:   } else if (op == VECOP_LOAD && !vec->ops->loadnative) {
1260:     vec->ops->loadnative = vec->ops->load;
1261:   }
1262:   ((void (**)(void))vec->ops)[(int)op] = f;
1263:   PetscFunctionReturn(PETSC_SUCCESS);
1264: }

1266: /*@
1267:   VecStashSetInitialSize - sets the sizes of the vec-stash, that is
1268:   used during the assembly process to store values that belong to
1269:   other processors.

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

1273:   Input Parameters:
1274: + vec   - the vector
1275: . size  - the initial size of the stash.
1276: - bsize - the initial size of the block-stash(if used).

1278:   Options Database Keys:
1279: + -vecstash_initial_size <size> or <size0,size1,...sizep-1>           - set initial size
1280: - -vecstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1> - set initial block size

1282:   Level: intermediate

1284:   Notes:
1285:   The block-stash is used for values set with `VecSetValuesBlocked()` while
1286:   the stash is used for values set with `VecSetValues()`

1288:   Run with the option -info and look for output of the form
1289:   VecAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
1290:   to determine the appropriate value, MM, to use for size and
1291:   VecAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
1292:   to determine the value, BMM to use for bsize

1294:   PETSc attempts to smartly manage the stash size so there is little likelihood setting a
1295:   a specific value here will affect performance

1297: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`, `VecStashView()`
1298: @*/
1299: PetscErrorCode VecStashSetInitialSize(Vec vec, PetscInt size, PetscInt bsize)
1300: {
1301:   PetscFunctionBegin;
1303:   PetscCall(VecStashSetInitialSize_Private(&vec->stash, size));
1304:   PetscCall(VecStashSetInitialSize_Private(&vec->bstash, bsize));
1305:   PetscFunctionReturn(PETSC_SUCCESS);
1306: }

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

1311:   Logically Collective

1313:   Input Parameters:
1314: + x    - the vector
1315: - rctx - the random number context, formed by `PetscRandomCreate()`, or use `NULL` and it will create one internally.

1317:   Output Parameter:
1318: . x - the vector

1320:   Example of Usage:
1321: .vb
1322:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
1323:      VecSetRandom(x,rctx);
1324:      PetscRandomDestroy(&rctx);
1325: .ve

1327:   Level: intermediate

1329: .seealso: [](ch_vectors), `Vec`, `VecSet()`, `VecSetValues()`, `PetscRandomCreate()`, `PetscRandomDestroy()`
1330: @*/
1331: PetscErrorCode VecSetRandom(Vec x, PetscRandom rctx)
1332: {
1333:   PetscRandom randObj = NULL;

1335:   PetscFunctionBegin;
1339:   VecCheckAssembled(x);
1340:   PetscCall(VecSetErrorIfLocked(x, 1));

1342:   if (!rctx) {
1343:     PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)x), &randObj));
1344:     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
1345:     PetscCall(PetscRandomSetFromOptions(randObj));
1346:     rctx = randObj;
1347:   }

1349:   PetscCall(PetscLogEventBegin(VEC_SetRandom, x, rctx, 0, 0));
1350:   PetscUseTypeMethod(x, setrandom, rctx);
1351:   PetscCall(PetscLogEventEnd(VEC_SetRandom, x, rctx, 0, 0));

1353:   PetscCall(PetscRandomDestroy(&randObj));
1354:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
1355:   PetscFunctionReturn(PETSC_SUCCESS);
1356: }

1358: /*@
1359:   VecZeroEntries - puts a `0.0` in each element of a vector

1361:   Logically Collective

1363:   Input Parameter:
1364: . vec - The vector

1366:   Level: beginner

1368:   Note:
1369:   If the norm of the vector is known to be zero then this skips the unneeded zeroing process

1371: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`, `VecSet()`, `VecSetValues()`
1372: @*/
1373: PetscErrorCode VecZeroEntries(Vec vec)
1374: {
1375:   PetscFunctionBegin;
1376:   PetscCall(VecSet(vec, 0));
1377:   PetscFunctionReturn(PETSC_SUCCESS);
1378: }

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

1384:   Collective

1386:   Input Parameter:
1387: . vec - The vector

1389:   Level: intermediate

1391: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`, `VecSetType()`
1392: */
1393: static PetscErrorCode VecSetTypeFromOptions_Private(Vec vec, PetscOptionItems PetscOptionsObject)
1394: {
1395:   PetscBool   opt;
1396:   VecType     defaultType;
1397:   char        typeName[256];
1398:   PetscMPIInt size;

1400:   PetscFunctionBegin;
1401:   if (((PetscObject)vec)->type_name) defaultType = ((PetscObject)vec)->type_name;
1402:   else {
1403:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
1404:     if (size > 1) defaultType = VECMPI;
1405:     else defaultType = VECSEQ;
1406:   }

1408:   PetscCall(VecRegisterAll());
1409:   PetscCall(PetscOptionsFList("-vec_type", "Vector type", "VecSetType", VecList, defaultType, typeName, 256, &opt));
1410:   if (opt) {
1411:     PetscCall(VecSetType(vec, typeName));
1412:   } else {
1413:     PetscCall(VecSetType(vec, defaultType));
1414:   }
1415:   PetscFunctionReturn(PETSC_SUCCESS);
1416: }

1418: /*@
1419:   VecSetFromOptions - Configures the vector from the options database.

1421:   Collective

1423:   Input Parameter:
1424: . vec - The vector

1426:   Level: beginner

1428:   Notes:
1429:   To see all options, run your program with the -help option.

1431:   Must be called after `VecCreate()` but before the vector is used.

1433: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`
1434: @*/
1435: PetscErrorCode VecSetFromOptions(Vec vec)
1436: {
1437:   PetscBool flg;
1438:   PetscInt  bind_below = 0;

1440:   PetscFunctionBegin;

1443:   PetscObjectOptionsBegin((PetscObject)vec);
1444:   /* Handle vector type options */
1445:   PetscCall(VecSetTypeFromOptions_Private(vec, PetscOptionsObject));

1447:   /* Handle specific vector options */
1448:   PetscTryTypeMethod(vec, setfromoptions, PetscOptionsObject);

1450:   /* Bind to CPU if below a user-specified size threshold.
1451:    * This perhaps belongs in the options for the GPU Vec types, but VecBindToCPU() does nothing when called on non-GPU types,
1452:    * and putting it here makes is more maintainable than duplicating this for all. */
1453:   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));
1454:   if (flg && vec->map->n < bind_below) PetscCall(VecBindToCPU(vec, PETSC_TRUE));

1456:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1457:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)vec, PetscOptionsObject));
1458:   PetscOptionsEnd();
1459:   PetscFunctionReturn(PETSC_SUCCESS);
1460: }

1462: /*@
1463:   VecSetSizes - Sets the local and global sizes, and checks to determine compatibility of the sizes

1465:   Collective

1467:   Input Parameters:
1468: + v - the vector
1469: . n - the local size (or `PETSC_DECIDE` to have it set)
1470: - N - the global size (or `PETSC_DETERMINE` to have it set)

1472:   Level: intermediate

1474:   Notes:
1475:   `N` cannot be `PETSC_DETERMINE` if `n` is `PETSC_DECIDE`

1477:   If one processor calls this with `N` of `PETSC_DETERMINE` then all processors must, otherwise the program will hang.

1479:   If `n` is not `PETSC_DECIDE`, then the value determines the `PetscLayout` of the vector and the ranges returned by
1480:   `VecGetOwnershipRange()` and `VecGetOwnershipRanges()`

1482: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecCreateSeq()`, `VecCreateMPI()`, `VecGetSize()`, `PetscSplitOwnership()`, `PetscLayout`,
1483:           `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`, `MatSetSizes()`
1484: @*/
1485: PetscErrorCode VecSetSizes(Vec v, PetscInt n, PetscInt N)
1486: {
1487:   PetscFunctionBegin;
1489:   if (N >= 0) {
1491:     PetscCheck(n <= N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Local size %" PetscInt_FMT " cannot be larger than global size %" PetscInt_FMT, n, N);
1492:   }
1493:   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,
1494:              v->map->n, v->map->N);
1495:   v->map->n = n;
1496:   v->map->N = N;
1497:   PetscTryTypeMethod(v, create);
1498:   v->ops->create = NULL;
1499:   PetscFunctionReturn(PETSC_SUCCESS);
1500: }

1502: /*@
1503:   VecSetBlockSize - Sets the block size for future calls to `VecSetValuesBlocked()`
1504:   and `VecSetValuesBlockedLocal()`.

1506:   Logically Collective

1508:   Input Parameters:
1509: + v  - the vector
1510: - bs - the blocksize

1512:   Level: advanced

1514:   Note:
1515:   All vectors obtained by `VecDuplicate()` inherit the same blocksize.

1517:   Vectors obtained with `DMCreateGlobalVector()` and `DMCreateLocalVector()` generally already have a blocksize set based on the state of the `DM`

1519: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecGetBlockSize()`
1520: @*/
1521: PetscErrorCode VecSetBlockSize(Vec v, PetscInt bs)
1522: {
1523:   PetscFunctionBegin;
1526:   PetscCall(PetscLayoutSetBlockSize(v->map, bs));
1527:   v->bstash.bs = bs; /* use the same blocksize for the vec's block-stash */
1528:   PetscFunctionReturn(PETSC_SUCCESS);
1529: }

1531: /*@
1532:   VecGetBlockSize - Gets the blocksize for the vector, i.e. what is used for `VecSetValuesBlocked()`
1533:   and `VecSetValuesBlockedLocal()`.

1535:   Not Collective

1537:   Input Parameter:
1538: . v - the vector

1540:   Output Parameter:
1541: . bs - the blocksize

1543:   Level: advanced

1545:   Note:
1546:   All vectors obtained by `VecDuplicate()` inherit the same blocksize.

1548: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecSetBlockSize()`
1549: @*/
1550: PetscErrorCode VecGetBlockSize(Vec v, PetscInt *bs)
1551: {
1552:   PetscFunctionBegin;
1554:   PetscAssertPointer(bs, 2);
1555:   PetscCall(PetscLayoutGetBlockSize(v->map, bs));
1556:   PetscFunctionReturn(PETSC_SUCCESS);
1557: }

1559: /*@
1560:   VecSetOptionsPrefix - Sets the prefix used for searching for all
1561:   `Vec` options in the database.

1563:   Logically Collective

1565:   Input Parameters:
1566: + v      - the `Vec` context
1567: - prefix - the prefix to prepend to all option names

1569:   Level: advanced

1571:   Note:
1572:   A hyphen (-) must NOT be given at the beginning of the prefix name.
1573:   The first character of all runtime options is AUTOMATICALLY the hyphen.

1575: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`
1576: @*/
1577: PetscErrorCode VecSetOptionsPrefix(Vec v, const char prefix[])
1578: {
1579:   PetscFunctionBegin;
1581:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)v, prefix));
1582:   PetscFunctionReturn(PETSC_SUCCESS);
1583: }

1585: /*@
1586:   VecAppendOptionsPrefix - Appends to the prefix used for searching for all
1587:   `Vec` options in the database.

1589:   Logically Collective

1591:   Input Parameters:
1592: + v      - the `Vec` context
1593: - prefix - the prefix to prepend to all option names

1595:   Level: advanced

1597:   Note:
1598:   A hyphen (-) must NOT be given at the beginning of the prefix name.
1599:   The first character of all runtime options is AUTOMATICALLY the hyphen.

1601: .seealso: [](ch_vectors), `Vec`, `VecGetOptionsPrefix()`
1602: @*/
1603: PetscErrorCode VecAppendOptionsPrefix(Vec v, const char prefix[])
1604: {
1605:   PetscFunctionBegin;
1607:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)v, prefix));
1608:   PetscFunctionReturn(PETSC_SUCCESS);
1609: }

1611: /*@
1612:   VecGetOptionsPrefix - Sets the prefix used for searching for all
1613:   Vec options in the database.

1615:   Not Collective

1617:   Input Parameter:
1618: . v - the `Vec` context

1620:   Output Parameter:
1621: . prefix - pointer to the prefix string used

1623:   Level: advanced

1625: .seealso: [](ch_vectors), `Vec`, `VecAppendOptionsPrefix()`
1626: @*/
1627: PetscErrorCode VecGetOptionsPrefix(Vec v, const char *prefix[])
1628: {
1629:   PetscFunctionBegin;
1631:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)v, prefix));
1632:   PetscFunctionReturn(PETSC_SUCCESS);
1633: }

1635: /*@C
1636:   VecGetState - Gets the state of a `Vec`.

1638:   Not Collective

1640:   Input Parameter:
1641: . v - the `Vec` context

1643:   Output Parameter:
1644: . state - the object state

1646:   Level: advanced

1648:   Note:
1649:   Object state is an integer which gets increased every time
1650:   the object is changed. By saving and later querying the object state
1651:   one can determine whether information about the object is still current.

1653: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `PetscObjectStateGet()`
1654: @*/
1655: PetscErrorCode VecGetState(Vec v, PetscObjectState *state)
1656: {
1657:   PetscFunctionBegin;
1659:   PetscAssertPointer(state, 2);
1660:   PetscCall(PetscObjectStateGet((PetscObject)v, state));
1661:   PetscFunctionReturn(PETSC_SUCCESS);
1662: }

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

1667:   Collective

1669:   Input Parameter:
1670: . v - the `Vec` context

1672:   Level: advanced

1674:   Notes:
1675:   For basic use of the `Vec` classes the user need not explicitly call
1676:   `VecSetUp()`, since these actions will happen automatically.

1678: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDestroy()`
1679: @*/
1680: PetscErrorCode VecSetUp(Vec v)
1681: {
1682:   PetscMPIInt size;

1684:   PetscFunctionBegin;
1686:   PetscCheck(v->map->n >= 0 || v->map->N >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Sizes not set");
1687:   if (!((PetscObject)v)->type_name) {
1688:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)v), &size));
1689:     if (size == 1) {
1690:       PetscCall(VecSetType(v, VECSEQ));
1691:     } else {
1692:       PetscCall(VecSetType(v, VECMPI));
1693:     }
1694:   }
1695:   PetscFunctionReturn(PETSC_SUCCESS);
1696: }

1698: /*
1699:     These currently expose the PetscScalar/PetscReal in updating the
1700:     cached norm. If we push those down into the implementation these
1701:     will become independent of PetscScalar/PetscReal
1702: */

1704: PetscErrorCode VecCopyAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1705: {
1706:   PetscBool flgs[4];
1707:   PetscReal norms[4] = {0.0, 0.0, 0.0, 0.0};

1709:   PetscFunctionBegin;
1714:   if (x == y) PetscFunctionReturn(PETSC_SUCCESS);
1715:   VecCheckSameLocalSize(x, 1, y, 2);
1716:   VecCheckAssembled(x);
1717:   PetscCall(VecSetErrorIfLocked(y, 2));

1719: #if !defined(PETSC_USE_MIXED_PRECISION)
1720:   for (PetscInt i = 0; i < 4; i++) PetscCall(PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], norms[i], flgs[i]));
1721: #endif

1723:   PetscCall(PetscLogEventBegin(VEC_Copy, x, y, 0, 0));
1724: #if defined(PETSC_USE_MIXED_PRECISION)
1725:   extern PetscErrorCode VecGetArray(Vec, double **);
1726:   extern PetscErrorCode VecRestoreArray(Vec, double **);
1727:   extern PetscErrorCode VecGetArray(Vec, float **);
1728:   extern PetscErrorCode VecRestoreArray(Vec, float **);
1729:   extern PetscErrorCode VecGetArrayRead(Vec, const double **);
1730:   extern PetscErrorCode VecRestoreArrayRead(Vec, const double **);
1731:   extern PetscErrorCode VecGetArrayRead(Vec, const float **);
1732:   extern PetscErrorCode VecRestoreArrayRead(Vec, const float **);
1733:   if ((((PetscObject)x)->precision == PETSC_PRECISION_SINGLE) && (((PetscObject)y)->precision == PETSC_PRECISION_DOUBLE)) {
1734:     PetscInt     i, n;
1735:     const float *xx;
1736:     double      *yy;
1737:     PetscCall(VecGetArrayRead(x, &xx));
1738:     PetscCall(VecGetArray(y, &yy));
1739:     PetscCall(VecGetLocalSize(x, &n));
1740:     for (i = 0; i < n; i++) yy[i] = xx[i];
1741:     PetscCall(VecRestoreArrayRead(x, &xx));
1742:     PetscCall(VecRestoreArray(y, &yy));
1743:   } else if ((((PetscObject)x)->precision == PETSC_PRECISION_DOUBLE) && (((PetscObject)y)->precision == PETSC_PRECISION_SINGLE)) {
1744:     PetscInt      i, n;
1745:     float        *yy;
1746:     const double *xx;
1747:     PetscCall(VecGetArrayRead(x, &xx));
1748:     PetscCall(VecGetArray(y, &yy));
1749:     PetscCall(VecGetLocalSize(x, &n));
1750:     for (i = 0; i < n; i++) yy[i] = (float)xx[i];
1751:     PetscCall(VecRestoreArrayRead(x, &xx));
1752:     PetscCall(VecRestoreArray(y, &yy));
1753:   } else PetscUseTypeMethod(x, copy, y);
1754: #else
1755:   VecMethodDispatch(x, dctx, VecAsyncFnName(Copy), copy, (Vec, Vec, PetscDeviceContext), y);
1756: #endif

1758:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
1759: #if !defined(PETSC_USE_MIXED_PRECISION)
1760:   for (PetscInt i = 0; i < 4; i++) {
1761:     if (flgs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], norms[i]));
1762:   }
1763: #endif

1765:   PetscCall(PetscLogEventEnd(VEC_Copy, x, y, 0, 0));
1766:   PetscFunctionReturn(PETSC_SUCCESS);
1767: }

1769: /*@
1770:   VecCopy - Copies a vector `y = x`

1772:   Logically Collective

1774:   Input Parameter:
1775: . x - the vector

1777:   Output Parameter:
1778: . y - the copy

1780:   Level: beginner

1782:   Note:
1783:   For default parallel PETSc vectors, both `x` and `y` must be distributed in
1784:   the same manner; local copies are done.

1786:   Developer Notes:
1787:   `PetscCheckSameTypeAndComm`(x,1,y,2) is not used on these vectors because we allow one
1788:   of the vectors to be sequential and one to be parallel so long as both have the same
1789:   local sizes. This is used in some internal functions in PETSc.

1791: .seealso: [](ch_vectors), `Vec`, `VecDuplicate()`
1792: @*/
1793: PetscErrorCode VecCopy(Vec x, Vec y)
1794: {
1795:   PetscFunctionBegin;
1796:   PetscCall(VecCopyAsync_Private(x, y, NULL));
1797:   PetscFunctionReturn(PETSC_SUCCESS);
1798: }

1800: PetscErrorCode VecSwapAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1801: {
1802:   PetscReal normxs[4], normys[4];
1803:   PetscBool flgxs[4], flgys[4];

1805:   PetscFunctionBegin;
1810:   PetscCheckSameTypeAndComm(x, 1, y, 2);
1811:   VecCheckSameSize(x, 1, y, 2);
1812:   VecCheckAssembled(x);
1813:   VecCheckAssembled(y);
1814:   PetscCall(VecSetErrorIfLocked(x, 1));
1815:   PetscCall(VecSetErrorIfLocked(y, 2));

1817:   for (PetscInt i = 0; i < 4; i++) {
1818:     PetscCall(PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], normxs[i], flgxs[i]));
1819:     PetscCall(PetscObjectComposedDataGetReal((PetscObject)y, NormIds[i], normys[i], flgys[i]));
1820:   }

1822:   PetscCall(PetscLogEventBegin(VEC_Swap, x, y, 0, 0));
1823:   VecMethodDispatch(x, dctx, VecAsyncFnName(Swap), swap, (Vec, Vec, PetscDeviceContext), y);
1824:   PetscCall(PetscLogEventEnd(VEC_Swap, x, y, 0, 0));

1826:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
1827:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
1828:   for (PetscInt i = 0; i < 4; i++) {
1829:     if (flgxs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], normxs[i]));
1830:     if (flgys[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)x, NormIds[i], normys[i]));
1831:   }
1832:   PetscFunctionReturn(PETSC_SUCCESS);
1833: }
1834: /*@
1835:   VecSwap - Swaps the values between two vectors, `x` and `y`.

1837:   Logically Collective

1839:   Input Parameters:
1840: + x - the first vector
1841: - y - the second vector

1843:   Level: advanced

1845: .seealso: [](ch_vectors), `Vec`, `VecSet()`
1846: @*/
1847: PetscErrorCode VecSwap(Vec x, Vec y)
1848: {
1849:   PetscFunctionBegin;
1850:   PetscCall(VecSwapAsync_Private(x, y, NULL));
1851:   PetscFunctionReturn(PETSC_SUCCESS);
1852: }

1854: /*@
1855:   VecStashViewFromOptions - Processes command line options to determine if/how a `VecStash` object is to be viewed.

1857:   Collective

1859:   Input Parameters:
1860: + obj        - the `Vec` containing a stash
1861: . bobj       - optional other object that provides the prefix
1862: - optionname - option to activate viewing

1864:   Level: intermediate

1866:   Developer Notes:
1867:   This cannot use `PetscObjectViewFromOptions()` because it takes a `Vec` as an argument but does not use `VecView()`

1869: .seealso: [](ch_vectors), `Vec`, `VecStashSetInitialSize()`
1870: @*/
1871: PetscErrorCode VecStashViewFromOptions(Vec obj, PetscObject bobj, const char optionname[])
1872: {
1873:   PetscViewer       viewer;
1874:   PetscBool         flg;
1875:   PetscViewerFormat format;
1876:   char             *prefix;

1878:   PetscFunctionBegin;
1879:   prefix = bobj ? bobj->prefix : ((PetscObject)obj)->prefix;
1880:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)obj), ((PetscObject)obj)->options, prefix, optionname, &viewer, &format, &flg));
1881:   if (flg) {
1882:     PetscCall(PetscViewerPushFormat(viewer, format));
1883:     PetscCall(VecStashView(obj, viewer));
1884:     PetscCall(PetscViewerPopFormat(viewer));
1885:     PetscCall(PetscViewerDestroy(&viewer));
1886:   }
1887:   PetscFunctionReturn(PETSC_SUCCESS);
1888: }

1890: /*@
1891:   VecStashView - Prints the entries in the vector stash and block stash.

1893:   Collective

1895:   Input Parameters:
1896: + v      - the vector
1897: - viewer - the viewer

1899:   Level: advanced

1901: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`
1902: @*/
1903: PetscErrorCode VecStashView(Vec v, PetscViewer viewer)
1904: {
1905:   PetscMPIInt rank;
1906:   PetscInt    i, j;
1907:   PetscBool   match;
1908:   VecStash   *s;
1909:   PetscScalar val;

1911:   PetscFunctionBegin;
1914:   PetscCheckSameComm(v, 1, viewer, 2);

1916:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &match));
1917:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_SUP, "Stash viewer only works with ASCII viewer not %s", ((PetscObject)v)->type_name);
1918:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
1919:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)v), &rank));
1920:   s = &v->bstash;

1922:   /* print block stash */
1923:   PetscCall(PetscViewerASCIIPushSynchronized(viewer));
1924:   PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector Block stash size %" PetscInt_FMT " block size %" PetscInt_FMT "\n", rank, s->n, s->bs));
1925:   for (i = 0; i < s->n; i++) {
1926:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " ", rank, s->idx[i]));
1927:     for (j = 0; j < s->bs; j++) {
1928:       val = s->array[i * s->bs + j];
1929: #if defined(PETSC_USE_COMPLEX)
1930:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "(%18.16e %18.16e) ", (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
1931: #else
1932:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%18.16e ", (double)val));
1933: #endif
1934:     }
1935:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
1936:   }
1937:   PetscCall(PetscViewerFlush(viewer));

1939:   s = &v->stash;

1941:   /* print basic stash */
1942:   PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector stash size %" PetscInt_FMT "\n", rank, s->n));
1943:   for (i = 0; i < s->n; i++) {
1944:     val = s->array[i];
1945: #if defined(PETSC_USE_COMPLEX)
1946:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " (%18.16e %18.16e) ", rank, s->idx[i], (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
1947: #else
1948:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " %18.16e\n", rank, s->idx[i], (double)val));
1949: #endif
1950:   }
1951:   PetscCall(PetscViewerFlush(viewer));
1952:   PetscCall(PetscViewerASCIIPopSynchronized(viewer));
1953:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
1954:   PetscFunctionReturn(PETSC_SUCCESS);
1955: }

1957: PetscErrorCode PetscOptionsGetVec(PetscOptions options, const char prefix[], const char key[], Vec v, PetscBool *set)
1958: {
1959:   PetscInt     i, N, rstart, rend;
1960:   PetscScalar *xx;
1961:   PetscReal   *xreal;
1962:   PetscBool    iset;

1964:   PetscFunctionBegin;
1965:   PetscCall(VecGetOwnershipRange(v, &rstart, &rend));
1966:   PetscCall(VecGetSize(v, &N));
1967:   PetscCall(PetscCalloc1(N, &xreal));
1968:   PetscCall(PetscOptionsGetRealArray(options, prefix, key, xreal, &N, &iset));
1969:   if (iset) {
1970:     PetscCall(VecGetArray(v, &xx));
1971:     for (i = rstart; i < rend; i++) xx[i - rstart] = xreal[i];
1972:     PetscCall(VecRestoreArray(v, &xx));
1973:   }
1974:   PetscCall(PetscFree(xreal));
1975:   if (set) *set = iset;
1976:   PetscFunctionReturn(PETSC_SUCCESS);
1977: }

1979: /*@
1980:   VecGetLayout - get `PetscLayout` describing a vector layout

1982:   Not Collective

1984:   Input Parameter:
1985: . x - the vector

1987:   Output Parameter:
1988: . map - the layout

1990:   Level: developer

1992:   Note:
1993:   The layout determines what vector elements are contained on each MPI process

1995: .seealso: [](ch_vectors), `PetscLayout`, `Vec`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
1996: @*/
1997: PetscErrorCode VecGetLayout(Vec x, PetscLayout *map)
1998: {
1999:   PetscFunctionBegin;
2001:   PetscAssertPointer(map, 2);
2002:   *map = x->map;
2003:   PetscFunctionReturn(PETSC_SUCCESS);
2004: }

2006: /*@
2007:   VecSetLayout - set `PetscLayout` describing vector layout

2009:   Not Collective

2011:   Input Parameters:
2012: + x   - the vector
2013: - map - the layout

2015:   Level: developer

2017:   Note:
2018:   It is normally only valid to replace the layout with a layout known to be equivalent.

2020: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2021: @*/
2022: PetscErrorCode VecSetLayout(Vec x, PetscLayout map)
2023: {
2024:   PetscFunctionBegin;
2026:   PetscCall(PetscLayoutReference(map, &x->map));
2027:   PetscFunctionReturn(PETSC_SUCCESS);
2028: }

2030: /*@
2031:   VecFlag - set infinity into the local part of the vector on any subset of MPI processes

2033:   Logically Collective

2035:   Input Parameters:
2036: + xin - the vector, can be `NULL` but only if on all processes
2037: - flg - indicates if this processes portion of the vector should be set to infinity

2039:   Level: developer

2041:   Note:
2042:   This removes the values from the vector norm cache for all processes by calling `PetscObjectIncrease()`.

2044:   This is used for any subset of MPI processes to indicate an failure in a solver, after the next use of `VecNorm()` if
2045:   `KSPCheckNorm()` detects an infinity and at least one of the MPI processes has a not converged reason then the `KSP`
2046:   object collectively is labeled as not converged.

2048: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2049: @*/
2050: PetscErrorCode VecFlag(Vec xin, PetscInt flg)
2051: {
2052:   // MSVC gives "divide by zero" error at compile time - so declare as volatile to skip this check.
2053:   volatile PetscReal one = 1.0, zero = 0.0;
2054:   PetscScalar        inf;

2056:   PetscFunctionBegin;
2057:   if (!xin) PetscFunctionReturn(PETSC_SUCCESS);
2059:   PetscCall(PetscObjectStateIncrease((PetscObject)xin));
2060:   if (flg) {
2061:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2062:     inf = one / zero;
2063:     PetscCall(PetscFPTrapPop());
2064:     if (xin->ops->set) {
2065:       PetscUseTypeMethod(xin, set, inf);
2066:     } else {
2067:       PetscInt     n;
2068:       PetscScalar *xx;

2070:       PetscCall(VecGetLocalSize(xin, &n));
2071:       PetscCall(VecGetArrayWrite(xin, &xx));
2072:       for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2073:       PetscCall(VecRestoreArrayWrite(xin, &xx));
2074:     }
2075:   }
2076:   PetscFunctionReturn(PETSC_SUCCESS);
2077: }

2079: /*@
2080:   VecSetInf - set infinity into the local part of the vector

2082:   Not Collective

2084:   Input Parameters:
2085: . xin - the vector

2087:   Level: developer

2089:   Note:
2090:   Deprecated, see  `VecFlag()`
2091:   This is used for any subset of MPI processes to indicate an failure in a solver, after the next use of `VecNorm()` if
2092:   `KSPCheckNorm()` detects an infinity and at least one of the MPI processes has a not converged reason then the `KSP`
2093:   object collectively is labeled as not converged.

2095:   This cannot be called if `xin` has a cached norm available

2097: .seealso: [](ch_vectors), `VecFlag()`, `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2098: @*/
2099: PetscErrorCode VecSetInf(Vec xin)
2100: {
2101:   // MSVC gives "divide by zero" error at compile time - so declare as volatile to skip this check.
2102:   volatile PetscReal one = 1.0, zero = 0.0;
2103:   PetscScalar        inf;
2104:   PetscBool          flg;

2106:   PetscFunctionBegin;
2107:   PetscCall(VecNormAvailable(xin, NORM_2, &flg, NULL));
2108:   PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot call VecSetInf() if the vector has a cached norm");
2109:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2110:   inf = one / zero;
2111:   PetscCall(PetscFPTrapPop());
2112:   if (xin->ops->set) {
2113:     PetscUseTypeMethod(xin, set, inf);
2114:   } else {
2115:     PetscInt     n;
2116:     PetscScalar *xx;

2118:     PetscCall(VecGetLocalSize(xin, &n));
2119:     PetscCall(VecGetArrayWrite(xin, &xx));
2120:     for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2121:     PetscCall(VecRestoreArrayWrite(xin, &xx));
2122:   }
2123:   PetscFunctionReturn(PETSC_SUCCESS);
2124: }

2126: /*@
2127:   VecBindToCPU - marks a vector to temporarily stay on the CPU and perform computations on the CPU

2129:   Logically collective

2131:   Input Parameters:
2132: + v   - the vector
2133: - flg - bind to the CPU if value of `PETSC_TRUE`

2135:   Level: intermediate

2137: .seealso: [](ch_vectors), `Vec`, `VecBoundToCPU()`
2138: @*/
2139: PetscErrorCode VecBindToCPU(Vec v, PetscBool flg)
2140: {
2141:   PetscFunctionBegin;
2144: #if defined(PETSC_HAVE_DEVICE)
2145:   if (v->boundtocpu == flg) PetscFunctionReturn(PETSC_SUCCESS);
2146:   v->boundtocpu = flg;
2147:   PetscTryTypeMethod(v, bindtocpu, flg);
2148: #endif
2149:   PetscFunctionReturn(PETSC_SUCCESS);
2150: }

2152: /*@
2153:   VecBoundToCPU - query if a vector is bound to the CPU

2155:   Not collective

2157:   Input Parameter:
2158: . v - the vector

2160:   Output Parameter:
2161: . flg - the logical flag

2163:   Level: intermediate

2165: .seealso: [](ch_vectors), `Vec`, `VecBindToCPU()`
2166: @*/
2167: PetscErrorCode VecBoundToCPU(Vec v, PetscBool *flg)
2168: {
2169:   PetscFunctionBegin;
2171:   PetscAssertPointer(flg, 2);
2172: #if defined(PETSC_HAVE_DEVICE)
2173:   *flg = v->boundtocpu;
2174: #else
2175:   *flg = PETSC_TRUE;
2176: #endif
2177:   PetscFunctionReturn(PETSC_SUCCESS);
2178: }

2180: /*@
2181:   VecSetBindingPropagates - Sets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects

2183:   Input Parameters:
2184: + v   - the vector
2185: - flg - flag indicating whether the boundtocpu flag should be propagated

2187:   Level: developer

2189:   Notes:
2190:   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.
2191:   The created vectors will also have their bindingpropagates flag set to true.

2193:   Developer Notes:
2194:   If a `DMDA` has the `-dm_bind_below option` set to true, then vectors created by `DMCreateGlobalVector()` will have `VecSetBindingPropagates()` called on them to
2195:   set their bindingpropagates flag to true.

2197: .seealso: [](ch_vectors), `Vec`, `MatSetBindingPropagates()`, `VecGetBindingPropagates()`
2198: @*/
2199: PetscErrorCode VecSetBindingPropagates(Vec v, PetscBool flg)
2200: {
2201:   PetscFunctionBegin;
2203: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2204:   v->bindingpropagates = flg;
2205: #endif
2206:   PetscFunctionReturn(PETSC_SUCCESS);
2207: }

2209: /*@
2210:   VecGetBindingPropagates - Gets whether the state of being bound to the CPU for a GPU vector type propagates to child and some other associated objects

2212:   Input Parameter:
2213: . v - the vector

2215:   Output Parameter:
2216: . flg - flag indicating whether the boundtocpu flag will be propagated

2218:   Level: developer

2220: .seealso: [](ch_vectors), `Vec`, `VecSetBindingPropagates()`
2221: @*/
2222: PetscErrorCode VecGetBindingPropagates(Vec v, PetscBool *flg)
2223: {
2224:   PetscFunctionBegin;
2226:   PetscAssertPointer(flg, 2);
2227: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2228:   *flg = v->bindingpropagates;
2229: #else
2230:   *flg = PETSC_FALSE;
2231: #endif
2232:   PetscFunctionReturn(PETSC_SUCCESS);
2233: }

2235: /*@C
2236:   VecSetPinnedMemoryMin - Set the minimum data size for which pinned memory will be used for host (CPU) allocations.

2238:   Logically Collective

2240:   Input Parameters:
2241: + v      - the vector
2242: - mbytes - minimum data size in bytes

2244:   Options Database Key:
2245: . -vec_pinned_memory_min <size> - minimum size (in bytes) for an allocation to use pinned memory on host.

2247:   Level: developer

2249:   Note:
2250:   Specifying -1 ensures that pinned memory will never be used.

2252: .seealso: [](ch_vectors), `Vec`, `VecGetPinnedMemoryMin()`
2253: @*/
2254: PetscErrorCode VecSetPinnedMemoryMin(Vec v, size_t mbytes)
2255: {
2256:   PetscFunctionBegin;
2258: #if PetscDefined(HAVE_DEVICE)
2259:   v->minimum_bytes_pinned_memory = mbytes;
2260: #endif
2261:   PetscFunctionReturn(PETSC_SUCCESS);
2262: }

2264: /*@C
2265:   VecGetPinnedMemoryMin - Get the minimum data size for which pinned memory will be used for host (CPU) allocations.

2267:   Logically Collective

2269:   Input Parameter:
2270: . v - the vector

2272:   Output Parameter:
2273: . mbytes - minimum data size in bytes

2275:   Level: developer

2277: .seealso: [](ch_vectors), `Vec`, `VecSetPinnedMemoryMin()`
2278: @*/
2279: PetscErrorCode VecGetPinnedMemoryMin(Vec v, size_t *mbytes)
2280: {
2281:   PetscFunctionBegin;
2283:   PetscAssertPointer(mbytes, 2);
2284: #if PetscDefined(HAVE_DEVICE)
2285:   *mbytes = v->minimum_bytes_pinned_memory;
2286: #endif
2287:   PetscFunctionReturn(PETSC_SUCCESS);
2288: }

2290: /*@
2291:   VecGetOffloadMask - Get the offload mask of a `Vec`

2293:   Not Collective

2295:   Input Parameter:
2296: . v - the vector

2298:   Output Parameter:
2299: . mask - corresponding `PetscOffloadMask` enum value.

2301:   Level: intermediate

2303: .seealso: [](ch_vectors), `Vec`, `VecCreateSeqCUDA()`, `VecCreateSeqViennaCL()`, `VecGetArray()`, `VecGetType()`
2304: @*/
2305: PetscErrorCode VecGetOffloadMask(Vec v, PetscOffloadMask *mask)
2306: {
2307:   PetscFunctionBegin;
2309:   PetscAssertPointer(mask, 2);
2310:   *mask = v->offloadmask;
2311:   PetscFunctionReturn(PETSC_SUCCESS);
2312: }

2314: #if !defined(PETSC_HAVE_VIENNACL)
2315: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLContext(Vec v, PETSC_UINTPTR_T *ctx)
2316: {
2317:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_context");
2318: }

2320: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLQueue(Vec v, PETSC_UINTPTR_T *queue)
2321: {
2322:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_command_queue");
2323: }

2325: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMem(Vec v, PETSC_UINTPTR_T *queue)
2326: {
2327:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2328: }

2330: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemRead(Vec v, PETSC_UINTPTR_T *queue)
2331: {
2332:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2333: }

2335: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLMemWrite(Vec v, PETSC_UINTPTR_T *queue)
2336: {
2337:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_mem");
2338: }

2340: PETSC_EXTERN PetscErrorCode VecViennaCLRestoreCLMemWrite(Vec v)
2341: {
2342:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to restore a Vec's cl_mem");
2343: }
2344: #endif

2346: 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)
2347: {
2348:   const PetscScalar *u, *y;
2349:   const PetscScalar *atola = NULL, *rtola = NULL, *erra = NULL;
2350:   PetscInt           n, n_loc = 0, na_loc = 0, nr_loc = 0;
2351:   PetscReal          nrm = 0, nrma = 0, nrmr = 0, err_loc[6];

2353:   PetscFunctionBegin;
2354: #define SkipSmallValue(a, b, tol) \
2355:   if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue

2357:   PetscCall(VecGetLocalSize(U, &n));
2358:   PetscCall(VecGetArrayRead(U, &u));
2359:   PetscCall(VecGetArrayRead(Y, &y));
2360:   if (E) PetscCall(VecGetArrayRead(E, &erra));
2361:   if (vatol) PetscCall(VecGetArrayRead(vatol, &atola));
2362:   if (vrtol) PetscCall(VecGetArrayRead(vrtol, &rtola));
2363:   for (PetscInt i = 0; i < n; i++) {
2364:     PetscReal err, tol, tola, tolr;

2366:     SkipSmallValue(y[i], u[i], ignore_max);
2367:     atol = atola ? PetscRealPart(atola[i]) : atol;
2368:     rtol = rtola ? PetscRealPart(rtola[i]) : rtol;
2369:     err  = erra ? PetscAbsScalar(erra[i]) : PetscAbsScalar(y[i] - u[i]);
2370:     tola = atol;
2371:     tolr = rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
2372:     tol  = tola + tolr;
2373:     if (tola > 0.) {
2374:       if (wnormtype == NORM_INFINITY) nrma = PetscMax(nrma, err / tola);
2375:       else nrma += PetscSqr(err / tola);
2376:       na_loc++;
2377:     }
2378:     if (tolr > 0.) {
2379:       if (wnormtype == NORM_INFINITY) nrmr = PetscMax(nrmr, err / tolr);
2380:       else nrmr += PetscSqr(err / tolr);
2381:       nr_loc++;
2382:     }
2383:     if (tol > 0.) {
2384:       if (wnormtype == NORM_INFINITY) nrm = PetscMax(nrm, err / tol);
2385:       else nrm += PetscSqr(err / tol);
2386:       n_loc++;
2387:     }
2388:   }
2389:   if (E) PetscCall(VecRestoreArrayRead(E, &erra));
2390:   if (vatol) PetscCall(VecRestoreArrayRead(vatol, &atola));
2391:   if (vrtol) PetscCall(VecRestoreArrayRead(vrtol, &rtola));
2392:   PetscCall(VecRestoreArrayRead(U, &u));
2393:   PetscCall(VecRestoreArrayRead(Y, &y));
2394: #undef SkipSmallValue

2396:   err_loc[0] = nrm;
2397:   err_loc[1] = nrma;
2398:   err_loc[2] = nrmr;
2399:   err_loc[3] = (PetscReal)n_loc;
2400:   err_loc[4] = (PetscReal)na_loc;
2401:   err_loc[5] = (PetscReal)nr_loc;
2402:   if (wnormtype == NORM_2) {
2403:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2404:   } else {
2405:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)U)));
2406:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc + 3, 3, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2407:   }
2408:   if (wnormtype == NORM_2) {
2409:     *norm  = PetscSqrtReal(err_loc[0]);
2410:     *norma = PetscSqrtReal(err_loc[1]);
2411:     *normr = PetscSqrtReal(err_loc[2]);
2412:   } else {
2413:     *norm  = err_loc[0];
2414:     *norma = err_loc[1];
2415:     *normr = err_loc[2];
2416:   }
2417:   *norm_loc  = (PetscInt)err_loc[3];
2418:   *norma_loc = (PetscInt)err_loc[4];
2419:   *normr_loc = (PetscInt)err_loc[5];
2420:   PetscFunctionReturn(PETSC_SUCCESS);
2421: }

2423: /*@
2424:   VecErrorWeightedNorms - compute a weighted norm of the difference between two vectors

2426:   Collective

2428:   Input Parameters:
2429: + U          - first vector to be compared
2430: . Y          - second vector to be compared
2431: . E          - optional third vector representing the error (if not provided, the error is ||U-Y||)
2432: . wnormtype  - norm type
2433: . atol       - scalar for absolute tolerance
2434: . vatol      - vector representing per-entry absolute tolerances (can be ``NULL``)
2435: . rtol       - scalar for relative tolerance
2436: . vrtol      - vector representing per-entry relative tolerances (can be ``NULL``)
2437: - ignore_max - ignore values smaller then this value in absolute terms.

2439:   Output Parameters:
2440: + norm      - weighted norm
2441: . norm_loc  - number of vector locations used for the weighted norm
2442: . norma     - weighted norm based on the absolute tolerance
2443: . norma_loc - number of vector locations used for the absolute weighted norm
2444: . normr     - weighted norm based on the relative tolerance
2445: - normr_loc - number of vector locations used for the relative weighted norm

2447:   Level: developer

2449:   Notes:
2450:   This is primarily used for computing weighted local truncation errors in ``TS``.

2452: .seealso: [](ch_vectors), `Vec`, `NormType`, `TSErrorWeightedNorm()`, `TSErrorWeightedENorm()`
2453: @*/
2454: 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)
2455: {
2456:   PetscFunctionBegin;
2461:   if (E) {
2464:   }
2467:   if (vatol) {
2470:   }
2472:   if (vrtol) {
2475:   }
2477:   PetscAssertPointer(norm, 10);
2478:   PetscAssertPointer(norm_loc, 11);
2479:   PetscAssertPointer(norma, 12);
2480:   PetscAssertPointer(norma_loc, 13);
2481:   PetscAssertPointer(normr, 14);
2482:   PetscAssertPointer(normr_loc, 15);
2483:   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)U), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);

2485:   /* There are potentially 5 vectors involved, some of them may happen to be of different type or bound to cpu.
2486:      Here we check that they all implement the same operation and call it if so.
2487:      Otherwise, we call the _Basic implementation that always works (provided VecGetArrayRead is implemented). */
2488:   PetscBool sameop = (PetscBool)(U->ops->errorwnorm && U->ops->errorwnorm == Y->ops->errorwnorm);
2489:   if (sameop && E) sameop = (PetscBool)(U->ops->errorwnorm == E->ops->errorwnorm);
2490:   if (sameop && vatol) sameop = (PetscBool)(U->ops->errorwnorm == vatol->ops->errorwnorm);
2491:   if (sameop && vrtol) sameop = (PetscBool)(U->ops->errorwnorm == vrtol->ops->errorwnorm);
2492:   if (sameop) PetscUseTypeMethod(U, errorwnorm, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc);
2493:   else PetscCall(VecErrorWeightedNorms_Basic(U, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc));
2494:   PetscFunctionReturn(PETSC_SUCCESS);
2495: }