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_Reciprocal, 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 [viewertype][:...]      - Display the vector. See `VecViewFromOptions()`/`PetscObjectViewFromOptions()` for the possible arguments
140: - -vecstash_view [viewertype][:...] - Display the vector stash. See `VecStashViewFromOptions()`/`PetscObjectViewFromOptions()` for the possible arguments

142:   Level: beginner

144: .seealso: [](ch_vectors), `Vec`, `VecAssemblyBegin()`, `VecSetValues()`, `VecViewFromOptions()`, `VecStashViewFromOptions()`,
145:           `PetscObjectViewFromOptions()`
146: @*/
147: PetscErrorCode VecAssemblyEnd(Vec vec)
148: {
149:   PetscFunctionBegin;
151:   PetscCall(PetscLogEventBegin(VEC_AssemblyEnd, vec, 0, 0, 0));
153:   PetscTryTypeMethod(vec, assemblyend);
154:   PetscCall(PetscLogEventEnd(VEC_AssemblyEnd, vec, 0, 0, 0));
155:   PetscCall(VecViewFromOptions(vec, NULL, "-vec_view"));
156:   PetscFunctionReturn(PETSC_SUCCESS);
157: }

159: /*@
160:   VecSetPreallocationCOO - set preallocation for a vector using a coordinate format of the entries with global indices

162:   Collective

164:   Input Parameters:
165: + x     - vector being preallocated
166: . ncoo  - number of entries
167: - coo_i - entry indices

169:   Level: beginner

171:   Notes:
172:   This and `VecSetValuesCOO()` provide an alternative API to using `VecSetValues()` to provide vector values.

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

176:   Entries can be repeated, see `VecSetValuesCOO()`. Negative indices are not allowed unless vector option `VEC_IGNORE_NEGATIVE_INDICES` is set,
177:   in which case they, along with the corresponding entries in `VecSetValuesCOO()`, are ignored. If vector option `VEC_NO_OFF_PROC_ENTRIES` is set,
178:   remote entries are ignored, otherwise, they will be properly added or inserted to the vector.

180:   The array coo_i[] may be freed immediately after calling this function.

182: .seealso: [](ch_vectors), `Vec`, `VecSetValuesCOO()`, `VecSetPreallocationCOOLocal()`
183: @*/
184: PetscErrorCode VecSetPreallocationCOO(Vec x, PetscCount ncoo, const PetscInt coo_i[])
185: {
186:   PetscFunctionBegin;
189:   if (ncoo) PetscAssertPointer(coo_i, 3);
190:   PetscCall(PetscLogEventBegin(VEC_SetPreallocateCOO, x, 0, 0, 0));
191:   PetscCall(PetscLayoutSetUp(x->map));
192:   if (x->ops->setpreallocationcoo) {
193:     PetscUseTypeMethod(x, setpreallocationcoo, ncoo, coo_i);
194:   } else {
195:     PetscInt ncoo_i;
196:     IS       is_coo_i;

198:     PetscCall(PetscIntCast(ncoo, &ncoo_i));
199:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, ncoo_i, coo_i, PETSC_COPY_VALUES, &is_coo_i));
200:     PetscCall(PetscObjectCompose((PetscObject)x, "__PETSc_coo_i", (PetscObject)is_coo_i));
201:     PetscCall(ISDestroy(&is_coo_i));
202:   }
203:   PetscCall(PetscLogEventEnd(VEC_SetPreallocateCOO, x, 0, 0, 0));
204:   PetscFunctionReturn(PETSC_SUCCESS);
205: }

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

210:   Collective

212:   Input Parameters:
213: + x     - vector being preallocated
214: . ncoo  - number of entries
215: - coo_i - row indices (local numbering; may be modified)

217:   Level: beginner

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

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

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

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

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

233: .seealso: [](ch_vectors), `Vec`, `VecSetPreallocationCOO()`, `VecSetValuesCOO()`
234: @*/
235: PetscErrorCode VecSetPreallocationCOOLocal(Vec x, PetscCount ncoo, PetscInt coo_i[])
236: {
237:   PetscInt               ncoo_i;
238:   ISLocalToGlobalMapping ltog;

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

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

255:   Collective

257:   Input Parameters:
258: + x     - vector being set
259: . coo_v - the value array
260: - imode - the insert mode

262:   Level: beginner

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

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

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

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

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

308: 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))
309: {
310:   PetscErrorCode (*async_fn)(Vec, Vec, Vec, PetscDeviceContext) = NULL;

312:   PetscFunctionBegin;
319:   PetscCheckSameTypeAndComm(x, 2, y, 3);
320:   PetscCheckSameTypeAndComm(y, 3, w, 1);
321:   VecCheckSameSize(w, 1, x, 2);
322:   VecCheckSameSize(w, 1, y, 3);
323:   VecCheckAssembled(x);
324:   VecCheckAssembled(y);
325:   PetscCall(VecSetErrorIfLocked(w, 1));

328:   if (dctx) PetscCall(PetscObjectQueryFunction((PetscObject)w, async_name, &async_fn));
329:   if (event) PetscCall(PetscLogEventBegin(event, x, y, w, 0));
330:   if (async_fn) PetscCall((*async_fn)(w, x, y, dctx));
331:   else PetscCall((*pointwise_op)(w, x, y));
332:   if (event) PetscCall(PetscLogEventEnd(event, x, y, w, 0));
333:   PetscCall(PetscObjectStateIncrease((PetscObject)w));
334:   PetscFunctionReturn(PETSC_SUCCESS);
335: }

337: PetscErrorCode VecPointwiseMaxAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
338: {
339:   PetscFunctionBegin;
340:   // REVIEW ME: no log event?
341:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMax), w->ops->pointwisemax));
342:   PetscFunctionReturn(PETSC_SUCCESS);
343: }

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

348:   Logically Collective

350:   Input Parameters:
351: + x - the first input vector
352: - y - the second input vector

354:   Output Parameter:
355: . w - the result

357:   Level: advanced

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

362:   For complex numbers compares only the real part

364: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
365: @*/
366: PetscErrorCode VecPointwiseMax(Vec w, Vec x, Vec y)
367: {
368:   PetscFunctionBegin;
369:   PetscCall(VecPointwiseMaxAsync_Private(w, x, y, NULL));
370:   PetscFunctionReturn(PETSC_SUCCESS);
371: }

373: PetscErrorCode VecPointwiseMinAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
374: {
375:   PetscFunctionBegin;
376:   // REVIEW ME: no log event?
377:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMin), w->ops->pointwisemin));
378:   PetscFunctionReturn(PETSC_SUCCESS);
379: }

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

384:   Logically Collective

386:   Input Parameters:
387: + x - the first input vector
388: - y - the second input vector

390:   Output Parameter:
391: . w - the result

393:   Level: advanced

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

398:   For complex numbers compares only the real part

400: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
401: @*/
402: PetscErrorCode VecPointwiseMin(Vec w, Vec x, Vec y)
403: {
404:   PetscFunctionBegin;
405:   PetscCall(VecPointwiseMinAsync_Private(w, x, y, NULL));
406:   PetscFunctionReturn(PETSC_SUCCESS);
407: }

409: PetscErrorCode VecPointwiseMaxAbsAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
410: {
411:   PetscFunctionBegin;
412:   // REVIEW ME: no log event?
413:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, 0, VecAsyncFnName(PointwiseMaxAbs), w->ops->pointwisemaxabs));
414:   PetscFunctionReturn(PETSC_SUCCESS);
415: }

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

420:   Logically Collective

422:   Input Parameters:
423: + x - the first input vector
424: - y - the second input vector

426:   Output Parameter:
427: . w - the result

429:   Level: advanced

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

434: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMult()`, `VecPointwiseMin()`, `VecPointwiseMax()`, `VecMaxPointwiseDivide()`
435: @*/
436: PetscErrorCode VecPointwiseMaxAbs(Vec w, Vec x, Vec y)
437: {
438:   PetscFunctionBegin;
439:   PetscCall(VecPointwiseMaxAbsAsync_Private(w, x, y, NULL));
440:   PetscFunctionReturn(PETSC_SUCCESS);
441: }

443: PetscErrorCode VecPointwiseDivideAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
444: {
445:   PetscFunctionBegin;
446:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseDivide, VecAsyncFnName(PointwiseDivide), w->ops->pointwisedivide));
447:   PetscFunctionReturn(PETSC_SUCCESS);
448: }

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

453:   Logically Collective

455:   Input Parameters:
456: + x - the numerator vector
457: - y - the denominator vector

459:   Output Parameter:
460: . w - the result

462:   Level: advanced

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

467: .seealso: [](ch_vectors), `Vec`, `VecPointwiseMult()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
468: @*/
469: PetscErrorCode VecPointwiseDivide(Vec w, Vec x, Vec y)
470: {
471:   PetscFunctionBegin;
472:   PetscCall(VecPointwiseDivideAsync_Private(w, x, y, NULL));
473:   PetscFunctionReturn(PETSC_SUCCESS);
474: }

476: #define VEC_POINTWISE_SIGN_LOOP(y, x, n, func) \
477:   PetscPragmaSIMD \
478:   for (PetscInt i = 0; i < (n); i++) (y)[i] = func(PetscRealPart((x)[i]))

480: #define VEC_POINTWISE_SIGN_DISPATCH(y, x, n, sign_type) \
481:   do { \
482:     switch (sign_type) { \
483:     case VEC_SIGN_ZERO_TO_ZERO: \
484:       VEC_POINTWISE_SIGN_LOOP(y, x, n, VecSignZeroToZero_Private); \
485:       break; \
486:     case VEC_SIGN_ZERO_TO_SIGNED_ZERO: \
487:       VEC_POINTWISE_SIGN_LOOP(y, x, n, VecSignZeroToSignedZero_Private); \
488:       break; \
489:     case VEC_SIGN_ZERO_TO_SIGNED_UNIT: \
490:       VEC_POINTWISE_SIGN_LOOP(y, x, n, VecSignZeroToSignedUnit_Private); \
491:       break; \
492:     default: \
493:       PetscUnreachable(); \
494:     } \
495:   } while (0)

497: PetscErrorCode VecPointwiseSignAsync_Private(Vec y, Vec x, VecSignMode sign_type, PetscDeviceContext dctx)
498: {
499:   PetscOffloadMask mask;
500:   PetscBool        is_host;
501:   PetscErrorCode (*async_fn)(Vec, Vec, VecSignMode, PetscDeviceContext) = NULL;

503:   PetscFunctionBegin;
508:   VecCheckSameSize(y, 1, x, 2);
509:   VecCheckAssembled(x);
510:   VecCheckAssembled(y);
511:   PetscCall(VecSetErrorIfLocked(y, 1));

513:   PetscCall(VecGetOffloadMask(x, &mask));
514:   is_host = PetscOffloadHost(mask) ? PETSC_TRUE : PETSC_FALSE;
515:   if (!is_host) PetscCall(PetscObjectQueryFunction((PetscObject)y, VEC_ASYNC_FN_NAME("PointwiseSign"), &async_fn));
516:   if (async_fn) PetscCall((*async_fn)(y, x, sign_type, dctx));
517:   else {
518:     PetscInt n;

520:     PetscCall(VecGetLocalSize(y, &n));
521:     if (y == x) {
522:       PetscScalar *_y;

524:       PetscCall(VecGetArray(y, &_y));
525:       VEC_POINTWISE_SIGN_DISPATCH(_y, _y, n, sign_type);
526:       PetscCall(VecRestoreArray(y, &_y));
527:     } else {
528:       PetscScalar       *_y;
529:       const PetscScalar *_x;

531:       PetscCall(VecGetArrayWrite(y, &_y));
532:       PetscCall(VecGetArrayRead(x, &_x));
533:       VEC_POINTWISE_SIGN_DISPATCH(_y, _x, n, sign_type);
534:       PetscCall(VecRestoreArrayRead(x, &_x));
535:       PetscCall(VecRestoreArrayWrite(y, &_y));
536:     }
537:   }
538:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
539:   PetscFunctionReturn(PETSC_SUCCESS);
540: }

542: /*@
543:   VecPointwiseSign - Computes the component-wise sign `y[i] = sign(x[i])`.

545:   Logically Collective

547:   Input Parameters:
548: + x         - the input vector
549: - sign_type - `VecSignMode` indicating how the function should map zero values.

551:   Output Parameter:
552: . y - the sign vector of `x`

554:   Level: beginner

556: .seealso: [](ch_vectors), `Vec`, `VecSignMode`
557: @*/
558: PetscErrorCode VecPointwiseSign(Vec y, Vec x, VecSignMode sign_type)
559: {
560:   PetscFunctionBegin;
561:   PetscCall(VecPointwiseSignAsync_Private(y, x, sign_type, NULL));
562:   PetscFunctionReturn(PETSC_SUCCESS);
563: }

565: PetscErrorCode VecPointwiseMultAsync_Private(Vec w, Vec x, Vec y, PetscDeviceContext dctx)
566: {
567:   PetscFunctionBegin;
569:   PetscCall(VecPointwiseApply_Private(w, x, y, dctx, VEC_PointwiseMult, VecAsyncFnName(PointwiseMult), w->ops->pointwisemult));
570:   PetscFunctionReturn(PETSC_SUCCESS);
571: }

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

576:   Logically Collective

578:   Input Parameters:
579: + x - the first vector
580: - y - the second vector

582:   Output Parameter:
583: . w - the result

585:   Level: advanced

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

590: .seealso: [](ch_vectors), `Vec`, `VecPointwiseDivide()`, `VecPointwiseMax()`, `VecPointwiseMin()`, `VecPointwiseMaxAbs()`, `VecMaxPointwiseDivide()`
591: @*/
592: PetscErrorCode VecPointwiseMult(Vec w, Vec x, Vec y)
593: {
594:   PetscFunctionBegin;
595:   PetscCall(VecPointwiseMultAsync_Private(w, x, y, NULL));
596:   PetscFunctionReturn(PETSC_SUCCESS);
597: }

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

602:   Collective

604:   Input Parameter:
605: . v - a vector to mimic

607:   Output Parameter:
608: . newv - location to put new vector

610:   Level: beginner

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

616:   Use `VecDestroy()` to free the space. Use `VecDuplicateVecs()` to get several
617:   vectors.

619: .seealso: [](ch_vectors), `Vec`, `VecDestroy()`, `VecDuplicateVecs()`, `VecCreate()`, `VecCopy()`
620: @*/
621: PetscErrorCode VecDuplicate(Vec v, Vec *newv)
622: {
623:   PetscFunctionBegin;
625:   PetscAssertPointer(newv, 2);
627:   PetscUseTypeMethod(v, duplicate, newv);
628: #if PetscDefined(HAVE_DEVICE)
629:   if (v->boundtocpu && v->bindingpropagates) {
630:     PetscCall(VecSetBindingPropagates(*newv, PETSC_TRUE));
631:     PetscCall(VecBindToCPU(*newv, PETSC_TRUE));
632:   }
633: #endif
634:   PetscCall(PetscObjectStateIncrease((PetscObject)*newv));
635:   PetscFunctionReturn(PETSC_SUCCESS);
636: }

638: /*@
639:   VecDestroy - Destroys a vector.

641:   Collective

643:   Input Parameter:
644: . v - the vector

646:   Level: beginner

648: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDuplicate()`, `VecDestroyVecs()`
649: @*/
650: PetscErrorCode VecDestroy(Vec *v)
651: {
652:   PetscFunctionBegin;
653:   PetscAssertPointer(v, 1);
654:   if (!*v) PetscFunctionReturn(PETSC_SUCCESS);
656:   if (--((PetscObject)*v)->refct > 0) {
657:     *v = NULL;
658:     PetscFunctionReturn(PETSC_SUCCESS);
659:   }

661:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*v));
662:   /* destroy the internal part */
663:   PetscTryTypeMethod(*v, destroy);
664:   PetscCall(PetscFree((*v)->defaultrandtype));
665:   /* destroy the external/common part */
666:   PetscCall(PetscLayoutDestroy(&(*v)->map));
667:   PetscCall(PetscHeaderDestroy(v));
668:   PetscFunctionReturn(PETSC_SUCCESS);
669: }

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

674:   Collective

676:   Input Parameters:
677: + m - the number of vectors to obtain
678: - v - a vector to mimic

680:   Output Parameter:
681: . V - location to put pointer to array of vectors

683:   Level: intermediate

685:   Notes:
686:   Use `VecDestroyVecs()` to free the space. Use `VecDuplicate()` to form a single
687:   vector.

689:   Some implementations ensure that the arrays accessed by each vector are contiguous in memory. Certain `VecMDot()` and `VecMAXPY()`
690:   implementations utilize this property to use BLAS 2 operations for higher efficiency. This is especially useful in `KSPGMRES`, see
691:   `KSPGMRESSetPreAllocateVectors()`.

693:   Fortran Note:
694: .vb
695:   Vec, pointer :: V(:)
696: .ve

698: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDestroyVecs()`, `VecDuplicate()`, `VecCreate()`, `VecMDot()`, `VecMAXPY()`, `KSPGMRES`,
699:           `KSPGMRESSetPreAllocateVectors()`
700: @*/
701: PetscErrorCode VecDuplicateVecs(Vec v, PetscInt m, Vec *V[])
702: {
703:   PetscFunctionBegin;
705:   PetscAssertPointer(V, 3);
707:   PetscUseTypeMethod(v, duplicatevecs, m, V);
708: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
709:   if (v->boundtocpu && v->bindingpropagates) {
710:     PetscInt i;

712:     for (i = 0; i < m; i++) {
713:       /* Since ops->duplicatevecs might itself propagate the value of boundtocpu,
714:        * avoid unnecessary overhead by only calling VecBindToCPU() if the vector isn't already bound. */
715:       if (!(*V)[i]->boundtocpu) {
716:         PetscCall(VecSetBindingPropagates((*V)[i], PETSC_TRUE));
717:         PetscCall(VecBindToCPU((*V)[i], PETSC_TRUE));
718:       }
719:     }
720:   }
721: #endif
722:   PetscFunctionReturn(PETSC_SUCCESS);
723: }

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

728:   Collective

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

734:   Level: intermediate

736: .seealso: [](ch_vectors), `Vec`, [](ch_fortran), `VecDuplicateVecs()`, `VecDestroyVecsf90()`
737: @*/
738: PetscErrorCode VecDestroyVecs(PetscInt m, Vec *vv[])
739: {
740:   PetscFunctionBegin;
741:   PetscAssertPointer(vv, 2);
742:   PetscCheck(m >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of vectors %" PetscInt_FMT, m);
743:   if (!m || !*vv) {
744:     *vv = NULL;
745:     PetscFunctionReturn(PETSC_SUCCESS);
746:   }
749:   PetscCall((*(**vv)->ops->destroyvecs)(m, *vv));
750:   *vv = NULL;
751:   PetscFunctionReturn(PETSC_SUCCESS);
752: }

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

757:   Collective

759:   Input Parameters:
760: + A    - the vector
761: . obj  - optional object that provides the options prefix for this viewing, use 'NULL' to use the prefix of `A`
762: - name - command line option

764:   Options Database Key:
765: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

767:   Level: intermediate

769: .seealso: [](ch_vectors), `Vec`, `VecView`, `PetscObjectViewFromOptions()`, `VecCreate()`
770: @*/
771: PetscErrorCode VecViewFromOptions(Vec A, PeOp PetscObject obj, const char name[])
772: {
773:   PetscFunctionBegin;
775:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
776:   PetscFunctionReturn(PETSC_SUCCESS);
777: }

779: /*@
780:   VecView - Views a vector object.

782:   Collective

784:   Input Parameters:
785: + vec    - the vector
786: - viewer - an optional `PetscViewer` visualization context

788:   Level: beginner

790:   Notes:
791:   The available visualization contexts include
792: +     `PETSC_VIEWER_STDOUT_SELF` - for sequential vectors
793: .     `PETSC_VIEWER_STDOUT_WORLD` - for parallel vectors created on `PETSC_COMM_WORLD`
794: -     `PETSC_VIEWER_STDOUT`_(comm) - for parallel vectors created on MPI communicator comm

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

799:   The user can open alternative viewers with
800: +    `PetscViewerASCIIOpen()` - Outputs vector to a specified file
801: .    `PetscViewerBinaryOpen()` - Outputs vector in binary to a
802:   specified file; corresponding input uses `VecLoad()`
803: .    `PetscViewerDrawOpen()` - Outputs vector to an X window display
804: .    `PetscViewerSocketOpen()` - Outputs vector to Socket viewer
805: -    `PetscViewerHDF5Open()` - Outputs vector to HDF5 file viewer

807:   The user can call `PetscViewerPushFormat()` to specify the output
808:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
809:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
810: +    `PETSC_VIEWER_DEFAULT` - default, prints vector contents
811: .    `PETSC_VIEWER_ASCII_MATLAB` - prints vector contents in MATLAB format
812: .    `PETSC_VIEWER_ASCII_INDEX` - prints vector contents, including indices of vector elements
813: -    `PETSC_VIEWER_ASCII_COMMON` - prints vector contents, using a
814:   format common among all vector types

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

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

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

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

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

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

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

846: .seealso: [](ch_vectors), `Vec`, `VecViewFromOptions()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`,
847:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
848:           `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
849: @*/
850: PetscErrorCode VecView(Vec vec, PetscViewer viewer)
851: {
852:   PetscBool         isascii;
853:   PetscViewerFormat format;
854:   PetscMPIInt       size;

856:   PetscFunctionBegin;
859:   VecCheckAssembled(vec);
860:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
862:   PetscCall(PetscViewerGetFormat(viewer, &format));
863:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
864:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

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

868:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
869:   if (isascii) {
870:     PetscInt rows, bs;

872:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)vec, viewer));
873:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
874:       PetscCall(PetscViewerASCIIPushTab(viewer));
875:       PetscCall(VecGetSize(vec, &rows));
876:       PetscCall(VecGetBlockSize(vec, &bs));
877:       if (bs != 1) {
878:         PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT ", bs=%" PetscInt_FMT "\n", rows, bs));
879:       } else {
880:         PetscCall(PetscViewerASCIIPrintf(viewer, "length=%" PetscInt_FMT "\n", rows));
881:       }
882:       PetscCall(PetscViewerASCIIPopTab(viewer));
883:     }
884:   }
885:   PetscCall(VecLockReadPush(vec));
886:   PetscCall(PetscLogEventBegin(VEC_View, vec, viewer, 0, 0));
887:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && vec->ops->viewnative) {
888:     PetscUseTypeMethod(vec, viewnative, viewer);
889:   } else {
890:     PetscUseTypeMethod(vec, view, viewer);
891:   }
892:   PetscCall(VecLockReadPop(vec));
893:   PetscCall(PetscLogEventEnd(VEC_View, vec, viewer, 0, 0));
894:   PetscFunctionReturn(PETSC_SUCCESS);
895: }

897: #if defined(PETSC_USE_DEBUG)
898: #include <../src/sys/totalview/tv_data_display.h>
899: PETSC_UNUSED static int TV_display_type(const struct _p_Vec *v)
900: {
901:   const PetscScalar *values;
902:   char               type[32];

904:   TV_add_row("Local rows", "int", &v->map->n);
905:   TV_add_row("Global rows", "int", &v->map->N);
906:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)v)->type_name);
907:   PetscCall(VecGetArrayRead((Vec)v, &values));
908:   PetscCall(PetscSNPrintf(type, 32, "double[%" PetscInt_FMT "]", v->map->n));
909:   TV_add_row("values", type, values);
910:   PetscCall(VecRestoreArrayRead((Vec)v, &values));
911:   return TV_format_OK;
912: }
913: #endif

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

918:   Collective

920:   Input Parameters:
921: + vec    - the vector
922: - viewer - an optional `PetscViewer` visualization context

924:   Level: developer

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

931: .seealso: [](ch_vectors), `Vec`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscDrawLGCreate()`, `VecView()`,
932:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `VecLoad()`, `PetscViewerCreate()`,
933:           `PetscRealView()`, `PetscScalarView()`, `PetscIntView()`, `PetscViewerHDF5SetTimestep()`
934: @*/
935: PetscErrorCode VecViewNative(Vec vec, PetscViewer viewer)
936: {
937:   PetscFunctionBegin;
940:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)vec), &viewer));
942:   PetscUseTypeMethod(vec, viewnative, viewer);
943:   PetscFunctionReturn(PETSC_SUCCESS);
944: }

946: /*@
947:   VecGetSize - Returns the global number of elements of the vector.

949:   Not Collective

951:   Input Parameter:
952: . x - the vector

954:   Output Parameter:
955: . size - the global length of the vector

957:   Level: beginner

959: .seealso: [](ch_vectors), `Vec`, `VecGetLocalSize()`
960: @*/
961: PetscErrorCode VecGetSize(Vec x, PetscInt *size)
962: {
963:   PetscFunctionBegin;
965:   PetscAssertPointer(size, 2);
967:   PetscUseTypeMethod(x, getsize, size);
968:   PetscFunctionReturn(PETSC_SUCCESS);
969: }

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

975:   Not Collective

977:   Input Parameter:
978: . x - the vector

980:   Output Parameter:
981: . size - the length of the local piece of the vector

983:   Level: beginner

985: .seealso: [](ch_vectors), `Vec`, `VecGetSize()`
986: @*/
987: PetscErrorCode VecGetLocalSize(Vec x, PetscInt *size)
988: {
989:   PetscFunctionBegin;
991:   PetscAssertPointer(size, 2);
993:   PetscUseTypeMethod(x, getlocalsize, size);
994:   PetscFunctionReturn(PETSC_SUCCESS);
995: }

997: /*@
998:   VecGetOwnershipRange - Returns the range of indices owned by
999:   this process. The vector is laid out with the
1000:   first `n1` elements on the first processor, next `n2` elements on the
1001:   second, etc.  For certain parallel layouts this range may not be
1002:   well defined.

1004:   Not Collective

1006:   Input Parameter:
1007: . x - the vector

1009:   Output Parameters:
1010: + low  - the first local element, pass in `NULL` if not interested
1011: - high - one more than the last local element, pass in `NULL` if not interested

1013:   Level: beginner

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

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

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

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

1026: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRanges()`, `PetscSplitOwnership()`,
1027:           `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
1028: @*/
1029: PetscErrorCode VecGetOwnershipRange(Vec x, PetscInt *low, PetscInt *high)
1030: {
1031:   PetscFunctionBegin;
1034:   if (low) PetscAssertPointer(low, 2);
1035:   if (high) PetscAssertPointer(high, 3);
1036:   if (low) *low = x->map->rstart;
1037:   if (high) *high = x->map->rend;
1038:   PetscFunctionReturn(PETSC_SUCCESS);
1039: }

1041: /*@C
1042:   VecGetOwnershipRanges - Returns the range of indices owned by EACH processor,
1043:   The vector is laid out with the
1044:   first `n1` elements on the first processor, next `n2` elements on the
1045:   second, etc.  For certain parallel layouts this range may not be
1046:   well defined.

1048:   Not Collective

1050:   Input Parameter:
1051: . x - the vector

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

1056:   Level: beginner

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

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

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

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

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

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

1073:   Fortran Note:
1074:   The argument `ranges` must be declared as
1075: .vb
1076:   PetscInt, pointer :: ranges(:)
1077: .ve
1078:   and you have to return it with a call to `VecRestoreOwnershipRanges()` when no longer needed

1080: .seealso: [](ch_vectors), `Vec`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `VecGetOwnershipRange()`, `PetscSplitOwnership()`,
1081:           `VecSetSizes()`, `VecCreateMPI()`, `PetscLayout`, `DMDAGetGhostCorners()`, `DM`
1082: @*/
1083: PetscErrorCode VecGetOwnershipRanges(Vec x, const PetscInt *ranges[])
1084: {
1085:   PetscFunctionBegin;
1088:   PetscCall(PetscLayoutGetRanges(x->map, ranges));
1089:   PetscFunctionReturn(PETSC_SUCCESS);
1090: }

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

1096:   Collective

1098:   Input Parameters:
1099: + x    - the vector
1100: . op   - the option
1101: - flag - turn the option on or off

1103:   Supported Options:
1104: + `VEC_IGNORE_OFF_PROC_ENTRIES` - which causes `VecSetValues()` to ignore
1105:           entries destined to be stored on a separate processor. This can be used
1106:           to eliminate the global reduction in the `VecAssemblyBegin()` if you know
1107:           that you have only used `VecSetValues()` to set local elements
1108: . `VEC_IGNORE_NEGATIVE_INDICES` - which means you can pass negative indices
1109:           in ix in calls to `VecSetValues()` or `VecGetValues()`. These rows are simply
1110:           ignored.
1111: - `VEC_SUBSET_OFF_PROC_ENTRIES` - which causes `VecAssemblyBegin()` to assume that the off-process
1112:           entries will always be a subset (possibly equal) of the off-process entries set on the
1113:           first assembly which had a true `VEC_SUBSET_OFF_PROC_ENTRIES` and the vector has not
1114:           changed this flag afterwards. If this assembly is not such first assembly, then this
1115:           assembly can reuse the communication pattern setup in that first assembly, thus avoiding
1116:           a global reduction. Subsequent assemblies setting off-process values should use the same
1117:           InsertMode as the first assembly.

1119:   Level: intermediate

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

1124: .seealso: [](ch_vectors), `Vec`, `VecSetValues()`
1125: @*/
1126: PetscErrorCode VecSetOption(Vec x, VecOption op, PetscBool flag)
1127: {
1128:   PetscFunctionBegin;
1131:   PetscTryTypeMethod(x, setoption, op, flag);
1132:   PetscFunctionReturn(PETSC_SUCCESS);
1133: }

1135: /* Default routines for obtaining and releasing; */
1136: /* may be used by any implementation */
1137: PetscErrorCode VecDuplicateVecs_Default(Vec w, PetscInt m, Vec *V[])
1138: {
1139:   PetscFunctionBegin;
1140:   PetscCheck(m > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "m must be > 0: m = %" PetscInt_FMT, m);
1141:   PetscCall(PetscMalloc1(m, V));
1142:   for (PetscInt i = 0; i < m; i++) PetscCall(VecDuplicate(w, *V + i));
1143:   PetscFunctionReturn(PETSC_SUCCESS);
1144: }

1146: PetscErrorCode VecDestroyVecs_Default(PetscInt m, Vec v[])
1147: {
1148:   PetscInt i;

1150:   PetscFunctionBegin;
1151:   PetscAssertPointer(v, 2);
1152:   for (i = 0; i < m; i++) PetscCall(VecDestroy(&v[i]));
1153:   PetscCall(PetscFree(v));
1154:   PetscFunctionReturn(PETSC_SUCCESS);
1155: }

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

1161:   Not Collective

1163:   Input Parameter:
1164: . vec - the vector

1166:   Level: developer

1168: .seealso: [](ch_vectors), `Vec`, `VecGetArray()`, `VecRestoreArray()`, `VecReplaceArray()`, `VecPlaceArray()`
1169: @*/
1170: PetscErrorCode VecResetArray(Vec vec)
1171: {
1172:   PetscFunctionBegin;
1175:   PetscUseTypeMethod(vec, resetarray);
1176:   PetscCall(PetscObjectStateIncrease((PetscObject)vec));
1177:   PetscFunctionReturn(PETSC_SUCCESS);
1178: }

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

1184:   Collective

1186:   Input Parameters:
1187: + vec    - the newly loaded vector, this needs to have been created with `VecCreate()` or
1188:            some related function before the call to `VecLoad()`.
1189: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()` or
1190:            HDF5 file viewer, obtained from `PetscViewerHDF5Open()`

1192:   Level: intermediate

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

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

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

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

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

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

1220:   Notes for advanced users when using the binary viewer:
1221:   Most users should not need to know the details of the binary storage
1222:   format, since `VecLoad()` and `VecView()` completely hide these details.
1223:   But for anyone who's interested, the standard binary vector storage
1224:   format is
1225: .vb
1226:      PetscInt    VEC_FILE_CLASSID
1227:      PetscInt    number of rows
1228:      PetscScalar *values of all entries
1229: .ve

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

1236: .seealso: [](ch_vectors), `Vec`, `PetscViewerBinaryOpen()`, `VecView()`, `MatLoad()`
1237: @*/
1238: PetscErrorCode VecLoad(Vec vec, PetscViewer viewer)
1239: {
1240:   PetscViewerFormat format;

1242:   PetscFunctionBegin;
1245:   PetscCheckSameComm(vec, 1, viewer, 2);

1247:   PetscCall(VecSetErrorIfLocked(vec, 1));
1248:   if (!((PetscObject)vec)->type_name && !vec->ops->create) PetscCall(VecSetType(vec, VECSTANDARD));
1249:   PetscCall(PetscLogEventBegin(VEC_Load, viewer, 0, 0, 0));
1250:   PetscCall(PetscViewerGetFormat(viewer, &format));
1251:   if (format == PETSC_VIEWER_NATIVE && vec->ops->loadnative) {
1252:     PetscUseTypeMethod(vec, loadnative, viewer);
1253:   } else {
1254:     PetscUseTypeMethod(vec, load, viewer);
1255:   }
1256:   PetscCall(PetscLogEventEnd(VEC_Load, viewer, 0, 0, 0));
1257:   PetscFunctionReturn(PETSC_SUCCESS);
1258: }

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

1263:   Logically Collective

1265:   Input Parameter:
1266: . vec - the vector

1268:   Output Parameter:
1269: . vec - the vector reciprocal

1271:   Level: intermediate

1273:   Note:
1274:   Vector entries with value 0.0 are not changed

1276: .seealso: [](ch_vectors), `Vec`, `VecLog()`, `VecExp()`, `VecSqrtAbs()`
1277: @*/
1278: PetscErrorCode VecReciprocal(Vec vec)
1279: {
1280:   PetscFunctionBegin;
1281:   PetscCall(VecReciprocalAsync_Private(vec, NULL));
1282:   PetscFunctionReturn(PETSC_SUCCESS);
1283: }

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

1288:   Logically Collective; No Fortran Support

1290:   Input Parameters:
1291: + vec - The vector to modify
1292: . op  - The name of the operation
1293: - f   - The function that provides the operation.

1295:   Level: advanced

1297:   Example Usage:
1298: .vb
1299:   // some new VecView() implementation, must have the same signature as the function it seeks
1300:   // to replace
1301:   PetscErrorCode UserVecView(Vec x, PetscViewer viewer)
1302:   {
1303:     PetscFunctionBeginUser;
1304:     // ...
1305:     PetscFunctionReturn(PETSC_SUCCESS);
1306:   }

1308:   // Create a VECMPI which has a pre-defined VecView() implementation
1309:   VecCreateMPI(comm, n, N, &x);
1310:   // Calls the VECMPI implementation for VecView()
1311:   VecView(x, viewer);

1313:   VecSetOperation(x, VECOP_VIEW, (PetscErrorCodeFn *)UserVecView);
1314:   // Now calls UserVecView()
1315:   VecView(x, viewer);
1316: .ve

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

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

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

1331:   Each function MUST return `PETSC_SUCCESS` on success and
1332:   nonzero on failure.

1334: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecGetOperation()`, `MatSetOperation()`, `MatShellSetOperation()`
1335: @*/
1336: PetscErrorCode VecSetOperation(Vec vec, VecOperation op, PetscErrorCodeFn *f)
1337: {
1338:   PetscFunctionBegin;
1340:   if (op == VECOP_VIEW && !vec->ops->viewnative) {
1341:     vec->ops->viewnative = vec->ops->view;
1342:   } else if (op == VECOP_LOAD && !vec->ops->loadnative) {
1343:     vec->ops->loadnative = vec->ops->load;
1344:   }
1345:   ((PetscErrorCodeFn **)vec->ops)[(int)op] = f;
1346:   PetscFunctionReturn(PETSC_SUCCESS);
1347: }

1349: /*@
1350:   VecStashSetInitialSize - sets the sizes of the vec-stash, that is
1351:   used during the assembly process to store values that belong to
1352:   other processors.

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

1356:   Input Parameters:
1357: + vec   - the vector
1358: . size  - the initial size of the stash.
1359: - bsize - the initial size of the block-stash(if used).

1361:   Options Database Keys:
1362: + -vecstash_initial_size size or size0,size1,...,sizep-1           - set initial size
1363: - -vecstash_block_initial_size bsize or bsize0,bsize1,...,bsizep-1 - set initial block size

1365:   Level: intermediate

1367:   Notes:
1368:   The block-stash is used for values set with `VecSetValuesBlocked()` while
1369:   the stash is used for values set with `VecSetValues()`

1371:   Run with the option -info and look for output of the form
1372:   VecAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
1373:   to determine the appropriate value, MM, to use for size and
1374:   VecAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
1375:   to determine the value, BMM to use for bsize

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

1380: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`, `VecStashView()`
1381: @*/
1382: PetscErrorCode VecStashSetInitialSize(Vec vec, PetscInt size, PetscInt bsize)
1383: {
1384:   PetscFunctionBegin;
1386:   PetscCall(VecStashSetInitialSize_Private(&vec->stash, size));
1387:   PetscCall(VecStashSetInitialSize_Private(&vec->bstash, bsize));
1388:   PetscFunctionReturn(PETSC_SUCCESS);
1389: }

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

1394:   Logically Collective

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

1400:   Output Parameter:
1401: . x - the vector

1403:   Example of Usage:
1404: .vb
1405:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
1406:      VecSetRandom(x,rctx);
1407:      PetscRandomDestroy(&rctx);
1408: .ve

1410:   Level: intermediate

1412: .seealso: [](ch_vectors), `Vec`, `VecSet()`, `VecSetValues()`, `PetscRandomCreate()`, `PetscRandomDestroy()`
1413: @*/
1414: PetscErrorCode VecSetRandom(Vec x, PetscRandom rctx)
1415: {
1416:   PetscRandom randObj = NULL;

1418:   PetscFunctionBegin;
1422:   VecCheckAssembled(x);
1423:   PetscCall(VecSetErrorIfLocked(x, 1));

1425:   if (!rctx) {
1426:     PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)x), &randObj));
1427:     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
1428:     PetscCall(PetscRandomSetFromOptions(randObj));
1429:     rctx = randObj;
1430:   }

1432:   PetscCall(PetscLogEventBegin(VEC_SetRandom, x, rctx, 0, 0));
1433:   PetscUseTypeMethod(x, setrandom, rctx);
1434:   PetscCall(PetscLogEventEnd(VEC_SetRandom, x, rctx, 0, 0));

1436:   PetscCall(PetscRandomDestroy(&randObj));
1437:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
1438:   PetscFunctionReturn(PETSC_SUCCESS);
1439: }

1441: /*@
1442:   VecSetRandomGaussian - Fills a vector with Gaussian random values of the given mean and standard deviation.

1444:   Collective

1446:   Input Parameters:
1447: + v       - the vector to fill
1448: . rng     - PETSc random number generator
1449: . mean    - desired mean of the Gaussian samples
1450: - std_dev - desired standard deviation

1452:   Level: advanced

1454:   Note:
1455:   For complex builds where `PetscScalar` is complex the imaginary part of all the vector entries is zero

1457:   Developer Note:
1458:   Uses the Box-Muller transform to generate normally distributed random numbers
1459:   from uniform random numbers. Handles edge cases where uniform random values
1460:   approach 0 or 1.

1462: .seealso: [](ch_vectors), [](ch_da), `PetscDA`, `PetscRandom`, `PetscRandomSetInterval()`, `VecSetRandom()`
1463: @*/
1464: PetscErrorCode VecSetRandomGaussian(Vec v, PetscRandom rng, PetscReal mean, PetscReal std_dev)
1465: {
1466:   PetscInt        n, i;
1467:   PetscScalar    *array;
1468:   PetscReal       u1, u2;
1469:   PetscReal       gauss_sample1, gauss_sample2, magnitude, theta;
1470:   const PetscReal min_uniform     = PETSC_MACHINE_EPSILON;
1471:   const PetscInt  max_retry_count = 100;

1473:   PetscFunctionBegin;
1478:   PetscCheck(!PetscIsInfOrNanReal(mean), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Mean must be a finite real number");
1479:   PetscCheck(std_dev >= 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Standard deviation must be non-negative, got %g", (double)std_dev);
1480:   PetscCheck(!PetscIsInfOrNanReal(std_dev), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Standard deviation must be a finite real number");

1482:   PetscCall(VecGetLocalSize(v, &n));
1483:   if (n == 0) PetscFunctionReturn(PETSC_SUCCESS);

1485:   if (std_dev == 0.0) {
1486:     PetscCall(VecSet(v, mean));
1487:     PetscFunctionReturn(PETSC_SUCCESS);
1488:   }

1490:   PetscCall(VecGetArrayWrite(v, &array));

1492:   /*
1493:     Generate Gaussian-distributed random values using the Box-Muller transform.
1494:     This transform converts pairs of uniform random variables U1, U2 ~ Uniform(0,1)
1495:     into pairs of independent standard normal variables Z0, Z1 ~ N(0,1):
1496:       Z0 = sqrt(-2 * ln(U1)) * cos(2pi * U2)
1497:       Z1 = sqrt(-2 * ln(U1)) * sin(2pi * U2)
1498:     Then scale and shift to get desired mean and standard deviation.
1499:   */
1500:   for (i = 0; i < n; i += 2) {
1501:     PetscInt retry_count = 0;

1503:     /*
1504:       Generate U1 and ensure it's not too close to 0 to avoid log(0) singularity.
1505:       Add retry limit to prevent infinite loops in case of RNG failure.
1506:     */
1507:     do {
1508:       PetscCall(PetscRandomGetValueReal(rng, &u1));
1509:       retry_count++;
1510:       PetscCheck(retry_count < max_retry_count, PETSC_COMM_SELF, PETSC_ERR_LIB, "Random number generator failed to produce valid values after %" PetscInt_FMT " attempts", (PetscInt)max_retry_count);
1511:     } while (u1 < min_uniform);

1513:     PetscCall(PetscRandomGetValueReal(rng, &u2));

1515:     /*
1516:       Apply Box-Muller transform:
1517:       - magnitude: sqrt(-2 * ln(U1)) represents the radial distance from origin
1518:       - theta: 2pi * U2 represents the angle uniformly distributed on [0, 2pi]
1519:       - Converting from polar to Cartesian coordinates yields two independent samples
1520:     */
1521:     magnitude     = PetscSqrtReal(-2.0 * PetscLogReal(u1));
1522:     theta         = 2.0 * PETSC_PI * u2;
1523:     gauss_sample1 = magnitude * PetscCosReal(theta);
1524:     gauss_sample2 = magnitude * PetscSinReal(theta);

1526:     /* Scale and shift to achieve desired mean and standard deviation */
1527:     array[i] = mean + std_dev * gauss_sample1;
1528:     if (i + 1 < n) array[i + 1] = mean + std_dev * gauss_sample2;
1529:   }

1531:   PetscCall(VecRestoreArrayWrite(v, &array));
1532:   PetscFunctionReturn(PETSC_SUCCESS);
1533: }

1535: /*@
1536:   VecZeroEntries - puts a `0.0` in each element of a vector

1538:   Logically Collective

1540:   Input Parameter:
1541: . vec - The vector

1543:   Level: beginner

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

1548: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`, `VecSet()`, `VecSetValues()`
1549: @*/
1550: PetscErrorCode VecZeroEntries(Vec vec)
1551: {
1552:   PetscFunctionBegin;
1553:   PetscCall(VecSet(vec, 0));
1554:   PetscFunctionReturn(PETSC_SUCCESS);
1555: }

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

1561:   Collective

1563:   Input Parameter:
1564: . vec - The vector

1566:   Level: intermediate

1568: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`, `VecSetType()`
1569: */
1570: static PetscErrorCode VecSetTypeFromOptions_Private(Vec vec, PetscOptionItems PetscOptionsObject)
1571: {
1572:   PetscBool   opt;
1573:   VecType     defaultType;
1574:   char        typeName[256];
1575:   PetscMPIInt size;

1577:   PetscFunctionBegin;
1578:   if (((PetscObject)vec)->type_name) defaultType = ((PetscObject)vec)->type_name;
1579:   else {
1580:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)vec), &size));
1581:     if (size > 1) defaultType = VECMPI;
1582:     else defaultType = VECSEQ;
1583:   }

1585:   PetscCall(VecRegisterAll());
1586:   PetscCall(PetscOptionsFList("-vec_type", "Vector type", "VecSetType", VecList, defaultType, typeName, 256, &opt));
1587:   if (opt) PetscCall(VecSetType(vec, typeName));
1588:   else PetscCall(VecSetType(vec, defaultType));
1589:   PetscFunctionReturn(PETSC_SUCCESS);
1590: }

1592: /*@
1593:   VecSetFromOptions - Configures the vector from the options database.

1595:   Collective

1597:   Input Parameter:
1598: . vec - The vector

1600:   Level: beginner

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

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

1607: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecSetOptionsPrefix()`
1608: @*/
1609: PetscErrorCode VecSetFromOptions(Vec vec)
1610: {
1611:   PetscBool flg;
1612:   PetscInt  bind_below = 0;

1614:   PetscFunctionBegin;

1617:   PetscObjectOptionsBegin((PetscObject)vec);
1618:   /* Handle vector type options */
1619:   PetscCall(VecSetTypeFromOptions_Private(vec, PetscOptionsObject));

1621:   /* Handle specific vector options */
1622:   PetscTryTypeMethod(vec, setfromoptions, PetscOptionsObject);

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

1630:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1631:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)vec, PetscOptionsObject));
1632:   PetscOptionsEnd();
1633:   PetscFunctionReturn(PETSC_SUCCESS);
1634: }

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

1639:   Collective

1641:   Input Parameters:
1642: + v - the vector
1643: . n - the local size (or `PETSC_DECIDE` to have it set)
1644: - N - the global size (or `PETSC_DETERMINE` to have it set)

1646:   Level: intermediate

1648:   Notes:
1649:   `N` cannot be `PETSC_DETERMINE` if `n` is `PETSC_DECIDE`

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

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

1656: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecCreateSeq()`, `VecCreateMPI()`, `VecGetSize()`, `PetscSplitOwnership()`, `PetscLayout`,
1657:           `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`, `MatSetSizes()`
1658: @*/
1659: PetscErrorCode VecSetSizes(Vec v, PetscInt n, PetscInt N)
1660: {
1661:   PetscFunctionBegin;
1663:   if (N >= 0) {
1665:     PetscCheck(n <= N, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Local size %" PetscInt_FMT " cannot be larger than global size %" PetscInt_FMT, n, N);
1666:   }
1667:   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,
1668:              v->map->n, v->map->N);
1669:   v->map->n = n;
1670:   v->map->N = N;
1671:   PetscTryTypeMethod(v, create);
1672:   v->ops->create = NULL;
1673:   PetscFunctionReturn(PETSC_SUCCESS);
1674: }

1676: /*@
1677:   VecSetBlockSize - Sets the block size for future calls to `VecSetValuesBlocked()`
1678:   and `VecSetValuesBlockedLocal()`.

1680:   Logically Collective

1682:   Input Parameters:
1683: + v  - the vector
1684: - bs - the blocksize

1686:   Level: advanced

1688:   Note:
1689:   All vectors obtained by `VecDuplicate()` inherit the same blocksize.

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

1693: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecGetBlockSize()`
1694: @*/
1695: PetscErrorCode VecSetBlockSize(Vec v, PetscInt bs)
1696: {
1697:   PetscFunctionBegin;
1700:   PetscCall(PetscLayoutSetBlockSize(v->map, bs));
1701:   v->bstash.bs = bs; /* use the same blocksize for the vec's block-stash */
1702:   PetscFunctionReturn(PETSC_SUCCESS);
1703: }

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

1709:   Not Collective

1711:   Input Parameter:
1712: . v - the vector

1714:   Output Parameter:
1715: . bs - the blocksize

1717:   Level: advanced

1719:   Note:
1720:   All vectors obtained by `VecDuplicate()` inherit the same blocksize.

1722: .seealso: [](ch_vectors), `Vec`, `VecSetValuesBlocked()`, `VecSetLocalToGlobalMapping()`, `VecSetBlockSize()`
1723: @*/
1724: PetscErrorCode VecGetBlockSize(Vec v, PetscInt *bs)
1725: {
1726:   PetscFunctionBegin;
1728:   PetscAssertPointer(bs, 2);
1729:   PetscCall(PetscLayoutGetBlockSize(v->map, bs));
1730:   PetscFunctionReturn(PETSC_SUCCESS);
1731: }

1733: /*@
1734:   VecSetOptionsPrefix - Sets the prefix used for searching for all
1735:   `Vec` options in the database.

1737:   Logically Collective

1739:   Input Parameters:
1740: + v      - the `Vec` context
1741: - prefix - the prefix to prepend to all option names

1743:   Level: advanced

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

1749: .seealso: [](ch_vectors), `Vec`, `VecSetFromOptions()`
1750: @*/
1751: PetscErrorCode VecSetOptionsPrefix(Vec v, const char prefix[])
1752: {
1753:   PetscFunctionBegin;
1755:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)v, prefix));
1756:   PetscFunctionReturn(PETSC_SUCCESS);
1757: }

1759: /*@
1760:   VecAppendOptionsPrefix - Appends to the prefix used for searching for all
1761:   `Vec` options in the database.

1763:   Logically Collective

1765:   Input Parameters:
1766: + v      - the `Vec` context
1767: - prefix - the prefix to prepend to all option names

1769:   Level: advanced

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

1775: .seealso: [](ch_vectors), `Vec`, `VecGetOptionsPrefix()`
1776: @*/
1777: PetscErrorCode VecAppendOptionsPrefix(Vec v, const char prefix[])
1778: {
1779:   PetscFunctionBegin;
1781:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)v, prefix));
1782:   PetscFunctionReturn(PETSC_SUCCESS);
1783: }

1785: /*@
1786:   VecGetOptionsPrefix - Sets the prefix used for searching for all
1787:   Vec options in the database.

1789:   Not Collective

1791:   Input Parameter:
1792: . v - the `Vec` context

1794:   Output Parameter:
1795: . prefix - pointer to the prefix string used

1797:   Level: advanced

1799: .seealso: [](ch_vectors), `Vec`, `VecAppendOptionsPrefix()`
1800: @*/
1801: PetscErrorCode VecGetOptionsPrefix(Vec v, const char *prefix[])
1802: {
1803:   PetscFunctionBegin;
1805:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)v, prefix));
1806:   PetscFunctionReturn(PETSC_SUCCESS);
1807: }

1809: /*@C
1810:   VecGetState - Gets the state of a `Vec`.

1812:   Not Collective

1814:   Input Parameter:
1815: . v - the `Vec` context

1817:   Output Parameter:
1818: . state - the object state

1820:   Level: advanced

1822:   Note:
1823:   Object state is an integer which gets increased every time
1824:   the object is changed. By saving and later querying the object state
1825:   one can determine whether information about the object is still current.

1827: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `PetscObjectStateGet()`
1828: @*/
1829: PetscErrorCode VecGetState(Vec v, PetscObjectState *state)
1830: {
1831:   PetscFunctionBegin;
1833:   PetscAssertPointer(state, 2);
1834:   PetscCall(PetscObjectStateGet((PetscObject)v, state));
1835:   PetscFunctionReturn(PETSC_SUCCESS);
1836: }

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

1841:   Collective

1843:   Input Parameter:
1844: . v - the `Vec` context

1846:   Level: advanced

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

1852: .seealso: [](ch_vectors), `Vec`, `VecCreate()`, `VecDestroy()`
1853: @*/
1854: PetscErrorCode VecSetUp(Vec v)
1855: {
1856:   PetscMPIInt size;

1858:   PetscFunctionBegin;
1860:   PetscCheck(v->map->n >= 0 || v->map->N >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Sizes not set");
1861:   if (!((PetscObject)v)->type_name) {
1862:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)v), &size));
1863:     if (size == 1) PetscCall(VecSetType(v, VECSEQ));
1864:     else PetscCall(VecSetType(v, VECMPI));
1865:   }
1866:   PetscFunctionReturn(PETSC_SUCCESS);
1867: }

1869: /*
1870:     These currently expose the PetscScalar/PetscReal in updating the
1871:     cached norm. If we push those down into the implementation these
1872:     will become independent of PetscScalar/PetscReal
1873: */

1875: PetscErrorCode VecCopyAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1876: {
1877:   PetscBool flgs[4];
1878:   PetscReal norms[4] = {0.0, 0.0, 0.0, 0.0};

1880:   PetscFunctionBegin;
1885:   if (x == y) PetscFunctionReturn(PETSC_SUCCESS);
1886:   VecCheckSameLocalSize(x, 1, y, 2);
1887:   VecCheckAssembled(x);
1888:   PetscCall(VecSetErrorIfLocked(y, 2));

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

1894:   PetscCall(PetscLogEventBegin(VEC_Copy, x, y, 0, 0));
1895: #if defined(PETSC_USE_MIXED_PRECISION)
1896:   extern PetscErrorCode VecGetArray(Vec, double **);
1897:   extern PetscErrorCode VecRestoreArray(Vec, double **);
1898:   extern PetscErrorCode VecGetArray(Vec, float **);
1899:   extern PetscErrorCode VecRestoreArray(Vec, float **);
1900:   extern PetscErrorCode VecGetArrayRead(Vec, const double **);
1901:   extern PetscErrorCode VecRestoreArrayRead(Vec, const double **);
1902:   extern PetscErrorCode VecGetArrayRead(Vec, const float **);
1903:   extern PetscErrorCode VecRestoreArrayRead(Vec, const float **);
1904:   if ((((PetscObject)x)->precision == PETSC_PRECISION_SINGLE) && (((PetscObject)y)->precision == PETSC_PRECISION_DOUBLE)) {
1905:     PetscInt     i, n;
1906:     const float *xx;
1907:     double      *yy;
1908:     PetscCall(VecGetArrayRead(x, &xx));
1909:     PetscCall(VecGetArray(y, &yy));
1910:     PetscCall(VecGetLocalSize(x, &n));
1911:     for (i = 0; i < n; i++) yy[i] = xx[i];
1912:     PetscCall(VecRestoreArrayRead(x, &xx));
1913:     PetscCall(VecRestoreArray(y, &yy));
1914:   } else if ((((PetscObject)x)->precision == PETSC_PRECISION_DOUBLE) && (((PetscObject)y)->precision == PETSC_PRECISION_SINGLE)) {
1915:     PetscInt      i, n;
1916:     float        *yy;
1917:     const double *xx;
1918:     PetscCall(VecGetArrayRead(x, &xx));
1919:     PetscCall(VecGetArray(y, &yy));
1920:     PetscCall(VecGetLocalSize(x, &n));
1921:     for (i = 0; i < n; i++) yy[i] = (float)xx[i];
1922:     PetscCall(VecRestoreArrayRead(x, &xx));
1923:     PetscCall(VecRestoreArray(y, &yy));
1924:   } else PetscUseTypeMethod(x, copy, y);
1925: #else
1926:   VecMethodDispatch(x, dctx, VecAsyncFnName(Copy), copy, (Vec, Vec, PetscDeviceContext), y);
1927: #endif

1929:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
1930: #if !defined(PETSC_USE_MIXED_PRECISION)
1931:   for (PetscInt i = 0; i < 4; i++) {
1932:     if (flgs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], norms[i]));
1933:   }
1934: #endif

1936:   PetscCall(PetscLogEventEnd(VEC_Copy, x, y, 0, 0));
1937:   PetscFunctionReturn(PETSC_SUCCESS);
1938: }

1940: /*@
1941:   VecCopy - Copies a vector `y = x`

1943:   Logically Collective

1945:   Input Parameter:
1946: . x - the vector

1948:   Output Parameter:
1949: . y - the copy

1951:   Level: beginner

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

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

1962: .seealso: [](ch_vectors), `Vec`, `VecDuplicate()`
1963: @*/
1964: PetscErrorCode VecCopy(Vec x, Vec y)
1965: {
1966:   PetscFunctionBegin;
1967:   PetscCall(VecCopyAsync_Private(x, y, NULL));
1968:   PetscFunctionReturn(PETSC_SUCCESS);
1969: }

1971: PetscErrorCode VecSwapAsync_Private(Vec x, Vec y, PetscDeviceContext dctx)
1972: {
1973:   PetscReal normxs[4], normys[4];
1974:   PetscBool flgxs[4], flgys[4];

1976:   PetscFunctionBegin;
1981:   PetscCheckSameTypeAndComm(x, 1, y, 2);
1982:   VecCheckSameSize(x, 1, y, 2);
1983:   VecCheckAssembled(x);
1984:   VecCheckAssembled(y);
1985:   PetscCall(VecSetErrorIfLocked(x, 1));
1986:   PetscCall(VecSetErrorIfLocked(y, 2));

1988:   for (PetscInt i = 0; i < 4; i++) {
1989:     PetscCall(PetscObjectComposedDataGetReal((PetscObject)x, NormIds[i], normxs[i], flgxs[i]));
1990:     PetscCall(PetscObjectComposedDataGetReal((PetscObject)y, NormIds[i], normys[i], flgys[i]));
1991:   }

1993:   PetscCall(PetscLogEventBegin(VEC_Swap, x, y, 0, 0));
1994:   VecMethodDispatch(x, dctx, VecAsyncFnName(Swap), swap, (Vec, Vec, PetscDeviceContext), y);
1995:   PetscCall(PetscLogEventEnd(VEC_Swap, x, y, 0, 0));

1997:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
1998:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
1999:   for (PetscInt i = 0; i < 4; i++) {
2000:     if (flgxs[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)y, NormIds[i], normxs[i]));
2001:     if (flgys[i]) PetscCall(PetscObjectComposedDataSetReal((PetscObject)x, NormIds[i], normys[i]));
2002:   }
2003:   PetscFunctionReturn(PETSC_SUCCESS);
2004: }
2005: /*@
2006:   VecSwap - Swaps the values between two vectors, `x` and `y`.

2008:   Logically Collective

2010:   Input Parameters:
2011: + x - the first vector
2012: - y - the second vector

2014:   Level: advanced

2016: .seealso: [](ch_vectors), `Vec`, `VecSet()`
2017: @*/
2018: PetscErrorCode VecSwap(Vec x, Vec y)
2019: {
2020:   PetscFunctionBegin;
2021:   PetscCall(VecSwapAsync_Private(x, y, NULL));
2022:   PetscFunctionReturn(PETSC_SUCCESS);
2023: }

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

2028:   Collective

2030:   Input Parameters:
2031: + obj  - the `Vec` containing a stash
2032: . bobj - optional other object that provides the prefix
2033: - name - option to activate viewing

2035:   Options Database Key:
2036: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

2038:   Level: intermediate

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

2043: .seealso: [](ch_vectors), `Vec`, `VecStashSetInitialSize()`
2044: @*/
2045: PetscErrorCode VecStashViewFromOptions(Vec obj, PetscObject bobj, const char name[])
2046: {
2047:   PetscViewer       viewer;
2048:   PetscBool         flg;
2049:   PetscViewerFormat format;
2050:   char             *prefix;

2052:   PetscFunctionBegin;
2053:   prefix = bobj ? bobj->prefix : ((PetscObject)obj)->prefix;
2054:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)obj), ((PetscObject)obj)->options, prefix, name, &viewer, &format, &flg));
2055:   if (flg) {
2056:     PetscCall(PetscViewerPushFormat(viewer, format));
2057:     PetscCall(VecStashView(obj, viewer));
2058:     PetscCall(PetscViewerPopFormat(viewer));
2059:     PetscCall(PetscViewerDestroy(&viewer));
2060:   }
2061:   PetscFunctionReturn(PETSC_SUCCESS);
2062: }

2064: /*@
2065:   VecStashView - Prints the entries in the vector stash and block stash.

2067:   Collective

2069:   Input Parameters:
2070: + v      - the vector
2071: - viewer - the viewer

2073:   Level: advanced

2075: .seealso: [](ch_vectors), `Vec`, `VecSetBlockSize()`, `VecSetValues()`, `VecSetValuesBlocked()`
2076: @*/
2077: PetscErrorCode VecStashView(Vec v, PetscViewer viewer)
2078: {
2079:   PetscMPIInt rank;
2080:   PetscInt    i, j;
2081:   PetscBool   match;
2082:   VecStash   *s;
2083:   PetscScalar val;

2085:   PetscFunctionBegin;
2088:   PetscCheckSameComm(v, 1, viewer, 2);

2090:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &match));
2091:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_SUP, "Stash viewer only works with ASCII viewer not %s", ((PetscObject)v)->type_name);
2092:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
2093:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)v), &rank));
2094:   s = &v->bstash;

2096:   /* print block stash */
2097:   PetscCall(PetscViewerASCIIPushSynchronized(viewer));
2098:   PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector Block stash size %" PetscInt_FMT " block size %" PetscInt_FMT "\n", rank, s->n, s->bs));
2099:   for (i = 0; i < s->n; i++) {
2100:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " ", rank, s->idx[i]));
2101:     for (j = 0; j < s->bs; j++) {
2102:       val = s->array[i * s->bs + j];
2103: #if defined(PETSC_USE_COMPLEX)
2104:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "(%18.16e %18.16e) ", (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
2105: #else
2106:       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%18.16e ", (double)val));
2107: #endif
2108:     }
2109:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
2110:   }
2111:   PetscCall(PetscViewerFlush(viewer));

2113:   s = &v->stash;

2115:   /* print basic stash */
2116:   PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d]Vector stash size %" PetscInt_FMT "\n", rank, s->n));
2117:   for (i = 0; i < s->n; i++) {
2118:     val = s->array[i];
2119: #if defined(PETSC_USE_COMPLEX)
2120:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " (%18.16e %18.16e) ", rank, s->idx[i], (double)PetscRealPart(val), (double)PetscImaginaryPart(val)));
2121: #else
2122:     PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Element %" PetscInt_FMT " %18.16e\n", rank, s->idx[i], (double)val));
2123: #endif
2124:   }
2125:   PetscCall(PetscViewerFlush(viewer));
2126:   PetscCall(PetscViewerASCIIPopSynchronized(viewer));
2127:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
2128:   PetscFunctionReturn(PETSC_SUCCESS);
2129: }

2131: PetscErrorCode PetscOptionsGetVec(PetscOptions options, const char prefix[], const char key[], Vec v, PetscBool *set)
2132: {
2133:   PetscInt     i, N, rstart, rend;
2134:   PetscScalar *xx;
2135:   PetscReal   *xreal;
2136:   PetscBool    iset;

2138:   PetscFunctionBegin;
2139:   PetscCall(VecGetOwnershipRange(v, &rstart, &rend));
2140:   PetscCall(VecGetSize(v, &N));
2141:   PetscCall(PetscCalloc1(N, &xreal));
2142:   PetscCall(PetscOptionsGetRealArray(options, prefix, key, xreal, &N, &iset));
2143:   if (iset) {
2144:     PetscCall(VecGetArray(v, &xx));
2145:     for (i = rstart; i < rend; i++) xx[i - rstart] = xreal[i];
2146:     PetscCall(VecRestoreArray(v, &xx));
2147:   }
2148:   PetscCall(PetscFree(xreal));
2149:   if (set) *set = iset;
2150:   PetscFunctionReturn(PETSC_SUCCESS);
2151: }

2153: /*@
2154:   VecGetLayout - get `PetscLayout` describing a vector layout

2156:   Not Collective

2158:   Input Parameter:
2159: . x - the vector

2161:   Output Parameter:
2162: . map - the layout

2164:   Level: developer

2166:   Note:
2167:   The layout determines what vector elements are contained on each MPI process

2169: .seealso: [](ch_vectors), `PetscLayout`, `Vec`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2170: @*/
2171: PetscErrorCode VecGetLayout(Vec x, PetscLayout *map)
2172: {
2173:   PetscFunctionBegin;
2175:   PetscAssertPointer(map, 2);
2176:   *map = x->map;
2177:   PetscFunctionReturn(PETSC_SUCCESS);
2178: }

2180: /*@
2181:   VecSetLayout - set `PetscLayout` describing vector layout

2183:   Not Collective

2185:   Input Parameters:
2186: + x   - the vector
2187: - map - the layout

2189:   Level: developer

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

2194: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2195: @*/
2196: PetscErrorCode VecSetLayout(Vec x, PetscLayout map)
2197: {
2198:   PetscFunctionBegin;
2200:   PetscCall(PetscLayoutReference(map, &x->map));
2201:   PetscFunctionReturn(PETSC_SUCCESS);
2202: }

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

2207:   Logically Collective

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

2213:   Level: developer

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

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

2222: .seealso: [](ch_vectors), `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2223: @*/
2224: PetscErrorCode VecFlag(Vec xin, PetscInt flg)
2225: {
2226:   // MSVC gives "divide by zero" error at compile time - so declare as volatile to skip this check.
2227:   volatile PetscReal one = 1.0, zero = 0.0;
2228:   PetscScalar        inf;

2230:   PetscFunctionBegin;
2231:   if (!xin) PetscFunctionReturn(PETSC_SUCCESS);
2233:   PetscCall(PetscObjectStateIncrease((PetscObject)xin));
2234:   if (flg) {
2235:     PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2236:     inf = one / zero;
2237:     PetscCall(PetscFPTrapPop());
2238:     if (xin->ops->set) PetscUseTypeMethod(xin, set, inf);
2239:     else {
2240:       PetscInt     n;
2241:       PetscScalar *xx;

2243:       PetscCall(VecGetLocalSize(xin, &n));
2244:       PetscCall(VecGetArrayWrite(xin, &xx));
2245:       for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2246:       PetscCall(VecRestoreArrayWrite(xin, &xx));
2247:     }
2248:   }
2249:   PetscFunctionReturn(PETSC_SUCCESS);
2250: }

2252: /*@
2253:   VecSetInf - set infinity into the local part of the vector

2255:   Not Collective

2257:   Input Parameters:
2258: . xin - the vector

2260:   Level: developer

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

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

2270: .seealso: [](ch_vectors), `VecFlag()`, `Vec`, `PetscLayout`, `VecGetLayout()`, `VecGetSize()`, `VecGetOwnershipRange()`, `VecGetOwnershipRanges()`
2271: @*/
2272: PetscErrorCode VecSetInf(Vec xin)
2273: {
2274:   // MSVC gives "divide by zero" error at compile time - so declare as volatile to skip this check.
2275:   volatile PetscReal one = 1.0, zero = 0.0;
2276:   PetscScalar        inf;
2277:   PetscBool          flg;

2279:   PetscFunctionBegin;
2280:   PetscCall(VecNormAvailable(xin, NORM_2, &flg, NULL));
2281:   PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot call VecSetInf() if the vector has a cached norm");
2282:   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
2283:   inf = one / zero;
2284:   PetscCall(PetscFPTrapPop());
2285:   if (xin->ops->set) PetscUseTypeMethod(xin, set, inf);
2286:   else {
2287:     PetscInt     n;
2288:     PetscScalar *xx;

2290:     PetscCall(VecGetLocalSize(xin, &n));
2291:     PetscCall(VecGetArrayWrite(xin, &xx));
2292:     for (PetscInt i = 0; i < n; ++i) xx[i] = inf;
2293:     PetscCall(VecRestoreArrayWrite(xin, &xx));
2294:   }
2295:   PetscFunctionReturn(PETSC_SUCCESS);
2296: }

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

2301:   Logically collective

2303:   Input Parameters:
2304: + v   - the vector
2305: - flg - bind to the CPU if value of `PETSC_TRUE`

2307:   Level: intermediate

2309: .seealso: [](ch_vectors), `Vec`, `VecBoundToCPU()`
2310: @*/
2311: PetscErrorCode VecBindToCPU(Vec v, PetscBool flg)
2312: {
2313:   PetscFunctionBegin;
2316: #if defined(PETSC_HAVE_DEVICE)
2317:   if (v->boundtocpu == flg) PetscFunctionReturn(PETSC_SUCCESS);
2318:   v->boundtocpu = flg;
2319:   PetscTryTypeMethod(v, bindtocpu, flg);
2320: #endif
2321:   PetscFunctionReturn(PETSC_SUCCESS);
2322: }

2324: /*@
2325:   VecBoundToCPU - query if a vector is bound to the CPU

2327:   Not collective

2329:   Input Parameter:
2330: . v - the vector

2332:   Output Parameter:
2333: . flg - the logical flag

2335:   Level: intermediate

2337: .seealso: [](ch_vectors), `Vec`, `VecBindToCPU()`
2338: @*/
2339: PetscErrorCode VecBoundToCPU(Vec v, PetscBool *flg)
2340: {
2341:   PetscFunctionBegin;
2343:   PetscAssertPointer(flg, 2);
2344: #if defined(PETSC_HAVE_DEVICE)
2345:   *flg = v->boundtocpu;
2346: #else
2347:   *flg = PETSC_TRUE;
2348: #endif
2349:   PetscFunctionReturn(PETSC_SUCCESS);
2350: }

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

2355:   Input Parameters:
2356: + v   - the vector
2357: - flg - flag indicating whether the boundtocpu flag should be propagated

2359:   Level: developer

2361:   Notes:
2362:   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.
2363:   The created vectors will also have their bindingpropagates flag set to true.

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

2369: .seealso: [](ch_vectors), `Vec`, `MatSetBindingPropagates()`, `VecGetBindingPropagates()`
2370: @*/
2371: PetscErrorCode VecSetBindingPropagates(Vec v, PetscBool flg)
2372: {
2373:   PetscFunctionBegin;
2375: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2376:   v->bindingpropagates = flg;
2377: #endif
2378:   PetscFunctionReturn(PETSC_SUCCESS);
2379: }

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

2384:   Input Parameter:
2385: . v - the vector

2387:   Output Parameter:
2388: . flg - flag indicating whether the boundtocpu flag will be propagated

2390:   Level: developer

2392: .seealso: [](ch_vectors), `Vec`, `VecSetBindingPropagates()`
2393: @*/
2394: PetscErrorCode VecGetBindingPropagates(Vec v, PetscBool *flg)
2395: {
2396:   PetscFunctionBegin;
2398:   PetscAssertPointer(flg, 2);
2399: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
2400:   *flg = v->bindingpropagates;
2401: #else
2402:   *flg = PETSC_FALSE;
2403: #endif
2404:   PetscFunctionReturn(PETSC_SUCCESS);
2405: }

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

2410:   Logically Collective

2412:   Input Parameters:
2413: + v      - the vector
2414: - mbytes - minimum data size in bytes

2416:   Options Database Key:
2417: . -vec_pinned_memory_min size - minimum size (in bytes) for an allocation to use pinned memory on host.

2419:   Level: developer

2421:   Note:
2422:   Specifying -1 ensures that pinned memory will never be used.

2424: .seealso: [](ch_vectors), `Vec`, `VecGetPinnedMemoryMin()`
2425: @*/
2426: PetscErrorCode VecSetPinnedMemoryMin(Vec v, size_t mbytes)
2427: {
2428:   PetscFunctionBegin;
2430: #if PetscDefined(HAVE_DEVICE)
2431:   v->minimum_bytes_pinned_memory = mbytes;
2432: #endif
2433:   PetscFunctionReturn(PETSC_SUCCESS);
2434: }

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

2439:   Logically Collective

2441:   Input Parameter:
2442: . v - the vector

2444:   Output Parameter:
2445: . mbytes - minimum data size in bytes

2447:   Level: developer

2449: .seealso: [](ch_vectors), `Vec`, `VecSetPinnedMemoryMin()`
2450: @*/
2451: PetscErrorCode VecGetPinnedMemoryMin(Vec v, size_t *mbytes)
2452: {
2453:   PetscFunctionBegin;
2455:   PetscAssertPointer(mbytes, 2);
2456: #if PetscDefined(HAVE_DEVICE)
2457:   *mbytes = v->minimum_bytes_pinned_memory;
2458: #endif
2459:   PetscFunctionReturn(PETSC_SUCCESS);
2460: }

2462: /*@
2463:   VecGetOffloadMask - Get the offload mask of a `Vec`

2465:   Not Collective

2467:   Input Parameter:
2468: . v - the vector

2470:   Output Parameter:
2471: . mask - corresponding `PetscOffloadMask` enum value.

2473:   Level: intermediate

2475: .seealso: [](ch_vectors), `Vec`, `VecCreateSeqCUDA()`, `VecCreateSeqViennaCL()`, `VecGetArray()`, `VecGetType()`
2476: @*/
2477: PetscErrorCode VecGetOffloadMask(Vec v, PetscOffloadMask *mask)
2478: {
2479:   PetscFunctionBegin;
2481:   PetscAssertPointer(mask, 2);
2482:   *mask = v->offloadmask;
2483:   PetscFunctionReturn(PETSC_SUCCESS);
2484: }

2486: #if !defined(PETSC_HAVE_VIENNACL)
2487: PETSC_EXTERN PetscErrorCode VecViennaCLGetCLContext(Vec v, PETSC_UINTPTR_T *ctx)
2488: {
2489:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to get a Vec's cl_context");
2490: }

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

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

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

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

2512: PETSC_EXTERN PetscErrorCode VecViennaCLRestoreCLMemWrite(Vec v)
2513: {
2514:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "PETSc must be configured with --with-opencl to restore a Vec's cl_mem");
2515: }
2516: #endif

2518: 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)
2519: {
2520:   const PetscScalar *u, *y;
2521:   const PetscScalar *atola = NULL, *rtola = NULL, *erra = NULL;
2522:   PetscInt           n, n_loc = 0, na_loc = 0, nr_loc = 0;
2523:   PetscReal          nrm = 0, nrma = 0, nrmr = 0, err_loc[6];

2525:   PetscFunctionBegin;
2526: #define SkipSmallValue(a, b, tol) \
2527:   if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue

2529:   PetscCall(VecGetLocalSize(U, &n));
2530:   PetscCall(VecGetArrayRead(U, &u));
2531:   PetscCall(VecGetArrayRead(Y, &y));
2532:   if (E) PetscCall(VecGetArrayRead(E, &erra));
2533:   if (vatol) PetscCall(VecGetArrayRead(vatol, &atola));
2534:   if (vrtol) PetscCall(VecGetArrayRead(vrtol, &rtola));
2535:   for (PetscInt i = 0; i < n; i++) {
2536:     PetscReal err, tol, tola, tolr;

2538:     SkipSmallValue(y[i], u[i], ignore_max);
2539:     atol = atola ? PetscRealPart(atola[i]) : atol;
2540:     rtol = rtola ? PetscRealPart(rtola[i]) : rtol;
2541:     err  = erra ? PetscAbsScalar(erra[i]) : PetscAbsScalar(y[i] - u[i]);
2542:     tola = atol;
2543:     tolr = rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
2544:     tol  = tola + tolr;
2545:     if (tola > 0.) {
2546:       if (wnormtype == NORM_INFINITY) nrma = PetscMax(nrma, err / tola);
2547:       else nrma += PetscSqr(err / tola);
2548:       na_loc++;
2549:     }
2550:     if (tolr > 0.) {
2551:       if (wnormtype == NORM_INFINITY) nrmr = PetscMax(nrmr, err / tolr);
2552:       else nrmr += PetscSqr(err / tolr);
2553:       nr_loc++;
2554:     }
2555:     if (tol > 0.) {
2556:       if (wnormtype == NORM_INFINITY) nrm = PetscMax(nrm, err / tol);
2557:       else nrm += PetscSqr(err / tol);
2558:       n_loc++;
2559:     }
2560:   }
2561:   if (E) PetscCall(VecRestoreArrayRead(E, &erra));
2562:   if (vatol) PetscCall(VecRestoreArrayRead(vatol, &atola));
2563:   if (vrtol) PetscCall(VecRestoreArrayRead(vrtol, &rtola));
2564:   PetscCall(VecRestoreArrayRead(U, &u));
2565:   PetscCall(VecRestoreArrayRead(Y, &y));
2566: #undef SkipSmallValue

2568:   err_loc[0] = nrm;
2569:   err_loc[1] = nrma;
2570:   err_loc[2] = nrmr;
2571:   err_loc[3] = (PetscReal)n_loc;
2572:   err_loc[4] = (PetscReal)na_loc;
2573:   err_loc[5] = (PetscReal)nr_loc;
2574:   if (wnormtype == NORM_2) {
2575:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2576:   } else {
2577:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)U)));
2578:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, err_loc + 3, 3, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)U)));
2579:   }
2580:   if (wnormtype == NORM_2) {
2581:     *norm  = PetscSqrtReal(err_loc[0]);
2582:     *norma = PetscSqrtReal(err_loc[1]);
2583:     *normr = PetscSqrtReal(err_loc[2]);
2584:   } else {
2585:     *norm  = err_loc[0];
2586:     *norma = err_loc[1];
2587:     *normr = err_loc[2];
2588:   }
2589:   *norm_loc  = (PetscInt)err_loc[3];
2590:   *norma_loc = (PetscInt)err_loc[4];
2591:   *normr_loc = (PetscInt)err_loc[5];
2592:   PetscFunctionReturn(PETSC_SUCCESS);
2593: }

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

2598:   Collective

2600:   Input Parameters:
2601: + U          - first vector to be compared
2602: . Y          - second vector to be compared
2603: . E          - optional third vector representing the error (if not provided, the error is ||U-Y||)
2604: . wnormtype  - norm type
2605: . atol       - scalar for absolute tolerance
2606: . vatol      - vector representing per-entry absolute tolerances (can be ``NULL``)
2607: . rtol       - scalar for relative tolerance
2608: . vrtol      - vector representing per-entry relative tolerances (can be ``NULL``)
2609: - ignore_max - ignore values smaller than this value in absolute terms.

2611:   Output Parameters:
2612: + norm      - weighted norm
2613: . norm_loc  - number of vector locations used for the weighted norm
2614: . norma     - weighted norm based on the absolute tolerance
2615: . norma_loc - number of vector locations used for the absolute weighted norm
2616: . normr     - weighted norm based on the relative tolerance
2617: - normr_loc - number of vector locations used for the relative weighted norm

2619:   Level: developer

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

2624: .seealso: [](ch_vectors), `Vec`, `NormType`, `TSErrorWeightedNorm()`, `TSErrorWeightedENorm()`
2625: @*/
2626: 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)
2627: {
2628:   PetscFunctionBegin;
2633:   if (E) {
2636:   }
2639:   if (vatol) {
2642:   }
2644:   if (vrtol) {
2647:   }
2649:   PetscAssertPointer(norm, 10);
2650:   PetscAssertPointer(norm_loc, 11);
2651:   PetscAssertPointer(norma, 12);
2652:   PetscAssertPointer(norma_loc, 13);
2653:   PetscAssertPointer(normr, 14);
2654:   PetscAssertPointer(normr_loc, 15);
2655:   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)U), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);

2657:   /* There are potentially 5 vectors involved, some of them may happen to be of different type or bound to cpu.
2658:      Here we check that they all implement the same operation and call it if so.
2659:      Otherwise, we call the _Basic implementation that always works (provided VecGetArrayRead is implemented). */
2660:   PetscBool sameop = (PetscBool)(U->ops->errorwnorm && U->ops->errorwnorm == Y->ops->errorwnorm);
2661:   if (sameop && E) sameop = (PetscBool)(U->ops->errorwnorm == E->ops->errorwnorm);
2662:   if (sameop && vatol) sameop = (PetscBool)(U->ops->errorwnorm == vatol->ops->errorwnorm);
2663:   if (sameop && vrtol) sameop = (PetscBool)(U->ops->errorwnorm == vrtol->ops->errorwnorm);
2664:   if (sameop) PetscUseTypeMethod(U, errorwnorm, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc);
2665:   else PetscCall(VecErrorWeightedNorms_Basic(U, Y, E, wnormtype, atol, vatol, rtol, vrtol, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc));
2666:   PetscFunctionReturn(PETSC_SUCCESS);
2667: }