Actual source code: matrix.c

  1: /*
  2:    This is where the abstract matrix operations are defined
  3:    Portions of this code are under:
  4:    Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
  5: */

  7: #include <petsc/private/matimpl.h>
  8: #include <petsc/private/isimpl.h>
  9: #include <petsc/private/vecimpl.h>

 11: /* Logging support */
 12: PetscClassId MAT_CLASSID;
 13: PetscClassId MAT_COLORING_CLASSID;
 14: PetscClassId MAT_FDCOLORING_CLASSID;
 15: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;

 17: PetscLogEvent MAT_Mult, MAT_MultAdd, MAT_MultTranspose;
 18: PetscLogEvent MAT_ADot, MAT_ANorm;
 19: PetscLogEvent MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve, MAT_MatTrSolve;
 20: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
 21: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
 22: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
 23: PetscLogEvent MAT_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
 24: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 25: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 26: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply, MAT_Transpose, MAT_FDColoringFunction, MAT_CreateSubMat;
 27: PetscLogEvent MAT_TransposeColoringCreate;
 28: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
 29: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric, MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
 30: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
 31: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
 32: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
 33: PetscLogEvent MAT_MultHermitianTranspose, MAT_MultHermitianTransposeAdd;
 34: PetscLogEvent MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
 35: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
 36: PetscLogEvent MAT_GetMultiProcBlock;
 37: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
 38: PetscLogEvent MAT_HIPSPARSECopyToGPU, MAT_HIPSPARSECopyFromGPU, MAT_HIPSPARSEGenerateTranspose, MAT_HIPSPARSESolveAnalysis;
 39: PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
 40: PetscLogEvent MAT_CreateGraph;
 41: PetscLogEvent MAT_SetValuesBatch;
 42: PetscLogEvent MAT_ViennaCLCopyToGPU;
 43: PetscLogEvent MAT_CUDACopyToGPU, MAT_HIPCopyToGPU;
 44: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
 45: PetscLogEvent MAT_Merge, MAT_Residual, MAT_SetRandom;
 46: PetscLogEvent MAT_FactorFactS, MAT_FactorInvS;
 47: PetscLogEvent MATCOLORING_Apply, MATCOLORING_Comm, MATCOLORING_Local, MATCOLORING_ISCreate, MATCOLORING_SetUp, MATCOLORING_Weights;
 48: PetscLogEvent MAT_H2Opus_Build, MAT_H2Opus_Compress, MAT_H2Opus_Orthog, MAT_H2Opus_LR;

 50: const char *const MatFactorTypes[] = {"NONE", "LU", "CHOLESKY", "ILU", "ICC", "ILUDT", "QR", "MatFactorType", "MAT_FACTOR_", NULL};

 52: /*@
 53:   MatSetRandom - Sets all components of a matrix to random numbers.

 55:   Logically Collective

 57:   Input Parameters:
 58: + x    - the matrix
 59: - rctx - the `PetscRandom` object, formed by `PetscRandomCreate()`, or `NULL` and
 60:           it will create one internally.

 62:   Example:
 63: .vb
 64:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
 65:      MatSetRandom(x,rctx);
 66:      PetscRandomDestroy(rctx);
 67: .ve

 69:   Level: intermediate

 71:   Notes:
 72:   For sparse matrices that have been preallocated but not been assembled, it randomly selects appropriate locations,

 74:   for sparse matrices that already have nonzero locations, it fills the locations with random numbers.

 76:   It generates an error if used on unassembled sparse matrices that have not been preallocated.

 78: .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
 79: @*/
 80: PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
 81: {
 82:   PetscRandom randObj = NULL;

 84:   PetscFunctionBegin;
 88:   MatCheckPreallocated(x, 1);

 90:   if (!rctx) {
 91:     MPI_Comm comm;
 92:     PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
 93:     PetscCall(PetscRandomCreate(comm, &randObj));
 94:     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
 95:     PetscCall(PetscRandomSetFromOptions(randObj));
 96:     rctx = randObj;
 97:   }
 98:   PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
 99:   PetscUseTypeMethod(x, setrandom, rctx);
100:   PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));

102:   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
103:   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
104:   PetscCall(PetscRandomDestroy(&randObj));
105:   PetscFunctionReturn(PETSC_SUCCESS);
106: }

108: /*@
109:   MatCopyHashToXAIJ - copy hash table entries into an XAIJ matrix type

111:   Logically Collective

113:   Input Parameter:
114: . A - A matrix in unassembled, hash table form

116:   Output Parameter:
117: . B - The XAIJ matrix. This can either be `A` or some matrix of equivalent size, e.g. obtained from `A` via `MatDuplicate()`

119:   Example:
120: .vb
121:      PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
122:      PetscCall(MatCopyHashToXAIJ(A, B));
123: .ve

125:   Level: advanced

127:   Notes:
128:   If `B` is `A`, then the hash table data structure will be destroyed. `B` is assembled

130: .seealso: [](ch_matrices), `Mat`, `MAT_USE_HASH_TABLE`
131: @*/
132: PetscErrorCode MatCopyHashToXAIJ(Mat A, Mat B)
133: {
134:   PetscFunctionBegin;
136:   PetscUseTypeMethod(A, copyhashtoxaij, B);
137:   PetscFunctionReturn(PETSC_SUCCESS);
138: }

140: /*@
141:   MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in

143:   Logically Collective

145:   Input Parameter:
146: . mat - the factored matrix

148:   Output Parameters:
149: + pivot - the pivot value computed
150: - row   - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
151:          the share the matrix

153:   Level: advanced

155:   Notes:
156:   This routine does not work for factorizations done with external packages.

158:   This routine should only be called if `MatGetFactorError()` returns a value of `MAT_FACTOR_NUMERIC_ZEROPIVOT`

160:   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.

162: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
163: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
164: `MAT_FACTOR_NUMERIC_ZEROPIVOT`
165: @*/
166: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
167: {
168:   PetscFunctionBegin;
170:   PetscAssertPointer(pivot, 2);
171:   PetscAssertPointer(row, 3);
172:   *pivot = mat->factorerror_zeropivot_value;
173:   *row   = mat->factorerror_zeropivot_row;
174:   PetscFunctionReturn(PETSC_SUCCESS);
175: }

177: /*@
178:   MatFactorGetError - gets the error code from a factorization

180:   Logically Collective

182:   Input Parameter:
183: . mat - the factored matrix

185:   Output Parameter:
186: . err - the error code

188:   Level: advanced

190:   Note:
191:   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.

193: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
194:           `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
195: @*/
196: PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
197: {
198:   PetscFunctionBegin;
200:   PetscAssertPointer(err, 2);
201:   *err = mat->factorerrortype;
202:   PetscFunctionReturn(PETSC_SUCCESS);
203: }

205: /*@
206:   MatFactorClearError - clears the error code in a factorization

208:   Logically Collective

210:   Input Parameter:
211: . mat - the factored matrix

213:   Level: developer

215:   Note:
216:   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.

218: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
219:           `MatGetErrorCode()`, `MatFactorError`
220: @*/
221: PetscErrorCode MatFactorClearError(Mat mat)
222: {
223:   PetscFunctionBegin;
225:   mat->factorerrortype             = MAT_FACTOR_NOERROR;
226:   mat->factorerror_zeropivot_value = 0.0;
227:   mat->factorerror_zeropivot_row   = 0;
228:   PetscFunctionReturn(PETSC_SUCCESS);
229: }

231: PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
232: {
233:   Vec                r, l;
234:   const PetscScalar *al;
235:   PetscInt           i, nz, gnz, N, n, st;

237:   PetscFunctionBegin;
238:   PetscCall(MatCreateVecs(mat, &r, &l));
239:   if (!cols) { /* nonzero rows */
240:     PetscCall(MatGetOwnershipRange(mat, &st, NULL));
241:     PetscCall(MatGetSize(mat, &N, NULL));
242:     PetscCall(MatGetLocalSize(mat, &n, NULL));
243:     PetscCall(VecSetRandom(r, NULL));
244:     PetscCall(MatMult(mat, r, l));
245:     PetscCall(VecGetArrayRead(l, &al));
246:   } else { /* nonzero columns */
247:     PetscCall(MatGetOwnershipRangeColumn(mat, &st, NULL));
248:     PetscCall(MatGetSize(mat, NULL, &N));
249:     PetscCall(MatGetLocalSize(mat, NULL, &n));
250:     PetscCall(VecSet(r, 0.0));
251:     PetscCall(VecSetRandom(l, NULL));
252:     PetscCall(MatMultTranspose(mat, l, r));
253:     PetscCall(VecGetArrayRead(r, &al));
254:   }
255:   if (tol <= 0.0) {
256:     for (i = 0, nz = 0; i < n; i++)
257:       if (al[i] != 0.0) nz++;
258:   } else {
259:     for (i = 0, nz = 0; i < n; i++)
260:       if (PetscAbsScalar(al[i]) > tol) nz++;
261:   }
262:   PetscCallMPI(MPIU_Allreduce(&nz, &gnz, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
263:   if (gnz != N) {
264:     PetscInt *nzr;
265:     PetscCall(PetscMalloc1(nz, &nzr));
266:     if (nz) {
267:       if (tol < 0) {
268:         for (i = 0, nz = 0; i < n; i++)
269:           if (al[i] != 0.0) nzr[nz++] = i + st;
270:       } else {
271:         for (i = 0, nz = 0; i < n; i++)
272:           if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i + st;
273:       }
274:     }
275:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nz, nzr, PETSC_OWN_POINTER, nonzero));
276:   } else *nonzero = NULL;
277:   if (!cols) { /* nonzero rows */
278:     PetscCall(VecRestoreArrayRead(l, &al));
279:   } else {
280:     PetscCall(VecRestoreArrayRead(r, &al));
281:   }
282:   PetscCall(VecDestroy(&l));
283:   PetscCall(VecDestroy(&r));
284:   PetscFunctionReturn(PETSC_SUCCESS);
285: }

287: /*@
288:   MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix

290:   Input Parameter:
291: . mat - the matrix

293:   Output Parameter:
294: . keptrows - the rows that are not completely zero

296:   Level: intermediate

298:   Note:
299:   `keptrows` is set to `NULL` if all rows are nonzero.

301:   Developer Note:
302:   If `keptrows` is not `NULL`, it must be sorted.

304: .seealso: [](ch_matrices), `Mat`, `MatFindZeroRows()`
305:  @*/
306: PetscErrorCode MatFindNonzeroRows(Mat mat, IS *keptrows)
307: {
308:   PetscFunctionBegin;
311:   PetscAssertPointer(keptrows, 2);
312:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
313:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
314:   if (mat->ops->findnonzerorows) PetscUseTypeMethod(mat, findnonzerorows, keptrows);
315:   else PetscCall(MatFindNonzeroRowsOrCols_Basic(mat, PETSC_FALSE, 0.0, keptrows));
316:   if (keptrows && *keptrows) PetscCall(ISSetInfo(*keptrows, IS_SORTED, IS_GLOBAL, PETSC_FALSE, PETSC_TRUE));
317:   PetscFunctionReturn(PETSC_SUCCESS);
318: }

320: /*@
321:   MatFindZeroRows - Locate all rows that are completely zero in the matrix

323:   Input Parameter:
324: . mat - the matrix

326:   Output Parameter:
327: . zerorows - the rows that are completely zero

329:   Level: intermediate

331:   Note:
332:   `zerorows` is set to `NULL` if no rows are zero.

334: .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
335:  @*/
336: PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
337: {
338:   IS       keptrows;
339:   PetscInt m, n;

341:   PetscFunctionBegin;
344:   PetscAssertPointer(zerorows, 2);
345:   PetscCall(MatFindNonzeroRows(mat, &keptrows));
346:   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
347:      In keeping with this convention, we set zerorows to NULL if there are no zero
348:      rows. */
349:   if (keptrows == NULL) {
350:     *zerorows = NULL;
351:   } else {
352:     PetscCall(MatGetOwnershipRange(mat, &m, &n));
353:     PetscCall(ISComplement(keptrows, m, n, zerorows));
354:     PetscCall(ISDestroy(&keptrows));
355:   }
356:   PetscFunctionReturn(PETSC_SUCCESS);
357: }

359: /*@
360:   MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling

362:   Not Collective

364:   Input Parameter:
365: . A - the matrix

367:   Output Parameter:
368: . a - the diagonal part (which is a SEQUENTIAL matrix)

370:   Level: advanced

372:   Notes:
373:   See `MatCreateAIJ()` for more information on the "diagonal part" of the matrix.

375:   Use caution, as the reference count on the returned matrix is not incremented and it is used as part of `A`'s normal operation.

377: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MATAIJ`, `MATBAIJ`, `MATSBAIJ`
378: @*/
379: PetscErrorCode MatGetDiagonalBlock(Mat A, Mat *a)
380: {
381:   PetscFunctionBegin;
384:   PetscAssertPointer(a, 2);
385:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
386:   if (A->ops->getdiagonalblock) PetscUseTypeMethod(A, getdiagonalblock, a);
387:   else {
388:     PetscMPIInt size;

390:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
391:     PetscCheck(size == 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for parallel matrix type %s", ((PetscObject)A)->type_name);
392:     *a = A;
393:   }
394:   PetscFunctionReturn(PETSC_SUCCESS);
395: }

397: /*@
398:   MatGetMultPetscSF - Returns the `PetscSF` that communicates to each MPI process the values held on other MPI processes that are coupled to it by the `Mat`

400:   Not Collective

402:   Input Parameter:
403: . A - the matrix

405:   Output Parameter:
406: . sf - the `PetscSF`.

408:   Level: advanced

410:   Notes:
411:   The returned `PetscSF` is owned by the matrix; do not destroy it.

413:   It is only valid if this function is called after the matrix has been assembled
414:   (and for `MATMPIDENSE` after a `MatMult()` has been additionally called).

416:   This is only implemented for the matrix types listed below; calling it on a sequential matrix or a type that does not
417:   build such a `PetscSF` raises an error.

419:   For `MATMPIAIJ`, `MATMPIBAIJ`, `MATMPIDENSE`, and `MATMPISELL`, this `PetscSF` is used within
420:   `MatMult()` to provide the contribution of vector entries that are not local to each MPI process to the matrix-vector product.
421:   For `MATMPISBAIJ` the returned `PetscSF` is instead the off-process column gather used by operations such as
422:   `MatDiagonalScale()`; `MatMult_MPISBAIJ()` uses a separate, augmented scatter context.
423:   In all cases the `PetscSF` maps the global vector layout (the matrix column layout) onto the off-process columns that the local rows couple to,
424:   so it can be reused to communicate any per-column data, for example with `PetscSFBcastBegin()`.

426:   For `MATMPIDENSE` this `PetscSF` is an allgather: every process gathers all columns, including its own, in the natural global
427:   order rather than a sparse `garray` order. The leaf set and ordering therefore differ across matrix types, so callers should use
428:   `PetscSFGetGraph()` rather than assume a particular leaf layout.

430: .seealso: [](ch_matrices), `Mat`, `PetscSF`, `MatGetDiagonalBlock()`, `MatMPIAIJGetSeqAIJ()`, `PetscSFBcastBegin()`, `MatMult()`
431: @*/
432: PetscErrorCode MatGetMultPetscSF(Mat A, PetscSF *sf)
433: {
434:   PetscFunctionBegin;
437:   PetscAssertPointer(sf, 2);
438:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
439:   *sf = NULL;
440:   PetscUseMethod(A, "MatGetMultPetscSF_C", (Mat, PetscSF *), (A, sf));
441:   PetscFunctionReturn(PETSC_SUCCESS);
442: }

444: /*@
445:   MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.

447:   Collective

449:   Input Parameter:
450: . mat - the matrix

452:   Output Parameter:
453: . trace - the sum of the diagonal entries

455:   Level: advanced

457: .seealso: [](ch_matrices), `Mat`
458: @*/
459: PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
460: {
461:   Vec diag;

463:   PetscFunctionBegin;
465:   PetscAssertPointer(trace, 2);
466:   PetscCall(MatCreateVecs(mat, &diag, NULL));
467:   PetscCall(MatGetDiagonal(mat, diag));
468:   PetscCall(VecSum(diag, trace));
469:   PetscCall(VecDestroy(&diag));
470:   PetscFunctionReturn(PETSC_SUCCESS);
471: }

473: /*@
474:   MatRealPart - Zeros out the imaginary part of the matrix

476:   Logically Collective

478:   Input Parameter:
479: . mat - the matrix

481:   Level: advanced

483: .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
484: @*/
485: PetscErrorCode MatRealPart(Mat mat)
486: {
487:   PetscFunctionBegin;
490:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
491:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
492:   MatCheckPreallocated(mat, 1);
493:   PetscUseTypeMethod(mat, realpart);
494:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
495:   PetscFunctionReturn(PETSC_SUCCESS);
496: }

498: /*@
499:   MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix

501:   Collective

503:   Input Parameter:
504: . mat - the matrix

506:   Output Parameters:
507: + nghosts - number of ghosts (for `MATBAIJ` and `MATSBAIJ` matrices there is one ghost for each matrix block)
508: - ghosts  - the global indices of the ghost points

510:   Level: advanced

512:   Note:
513:   `nghosts` and `ghosts` are suitable to pass into `VecCreateGhost()` or `VecCreateGhostBlock()`

515: .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
516: @*/
517: PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
518: {
519:   PetscFunctionBegin;
522:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
523:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
524:   if (mat->ops->getghosts) PetscUseTypeMethod(mat, getghosts, nghosts, ghosts);
525:   else {
526:     if (nghosts) *nghosts = 0;
527:     if (ghosts) *ghosts = NULL;
528:   }
529:   PetscFunctionReturn(PETSC_SUCCESS);
530: }

532: /*@
533:   MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part

535:   Logically Collective

537:   Input Parameter:
538: . mat - the matrix

540:   Level: advanced

542: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
543: @*/
544: PetscErrorCode MatImaginaryPart(Mat mat)
545: {
546:   PetscFunctionBegin;
549:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
550:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
551:   MatCheckPreallocated(mat, 1);
552:   PetscUseTypeMethod(mat, imaginarypart);
553:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
554:   PetscFunctionReturn(PETSC_SUCCESS);
555: }

557: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
558: /*@
559:   MatGetRow - Gets a row of a matrix. You MUST call `MatRestoreRow()`
560:   for each row that you get to ensure that your application does
561:   not bleed memory.

563:   Not Collective

565:   Input Parameters:
566: + mat - the matrix
567: - row - the row to get

569:   Output Parameters:
570: + ncols - if not `NULL`, the number of nonzeros in `row`
571: . cols  - if not `NULL`, the column numbers
572: - vals  - if not `NULL`, the numerical values

574:   Level: advanced

576:   Notes:
577:   This routine is provided for people who need to have direct access
578:   to the structure of a matrix. We hope that we provide enough
579:   high-level matrix routines that few users will need it.

581:   `MatGetRow()` always returns 0-based column indices, regardless of
582:   whether the internal representation is 0-based (default) or 1-based.

584:   For better efficiency, set `cols` and/or `vals` to `NULL` if you do
585:   not wish to extract these quantities.

587:   The user can only examine the values extracted with `MatGetRow()`;
588:   the values CANNOT be altered. To change the matrix entries, one
589:   must use `MatSetValues()`.

591:   You can only have one call to `MatGetRow()` outstanding for a particular
592:   matrix at a time, per process. `MatGetRow()` can only obtain rows
593:   associated with the given process, it cannot get rows from the
594:   other processes; for that we suggest using `MatCreateSubMatrices()`, then
595:   `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
596:   is in the global number of rows.

598:   Use `MatGetRowIJ()` and `MatRestoreRowIJ()` to access all the local indices of the sparse matrix.

600:   Use `MatSeqAIJGetArray()` and similar functions to access the numerical values for certain matrix types directly.

602:   Fortran Note:
603: .vb
604:   PetscInt, pointer :: cols(:)
605:   PetscScalar, pointer :: vals(:)
606: .ve

608: .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
609: @*/
610: PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
611: {
612:   PetscInt incols;

614:   PetscFunctionBegin;
617:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
618:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
619:   MatCheckPreallocated(mat, 1);
620:   PetscCheck(row >= mat->rmap->rstart && row < mat->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Only for local rows, %" PetscInt_FMT " not in [%" PetscInt_FMT ",%" PetscInt_FMT ")", row, mat->rmap->rstart, mat->rmap->rend);
621:   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
622:   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
623:   if (ncols) *ncols = incols;
624:   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
625:   PetscFunctionReturn(PETSC_SUCCESS);
626: }

628: /*@
629:   MatConjugate - replaces the matrix values with their complex conjugates

631:   Logically Collective

633:   Input Parameter:
634: . mat - the matrix

636:   Level: advanced

638: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
639: @*/
640: PetscErrorCode MatConjugate(Mat mat)
641: {
642:   PetscFunctionBegin;
644:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
645:   if (PetscDefined(USE_COMPLEX) && !(mat->symmetric == PETSC_BOOL3_TRUE && mat->hermitian == PETSC_BOOL3_TRUE)) {
646:     PetscUseTypeMethod(mat, conjugate);
647:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
648:   }
649:   PetscFunctionReturn(PETSC_SUCCESS);
650: }

652: /*@
653:   MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.

655:   Not Collective

657:   Input Parameters:
658: + mat   - the matrix
659: . row   - the row to get
660: . ncols - the number of nonzeros
661: . cols  - the columns of the nonzeros
662: - vals  - if nonzero the column values

664:   Level: advanced

666:   Notes:
667:   This routine should be called after you have finished examining the entries.

669:   This routine zeros out `ncols`, `cols`, and `vals`. This is to prevent accidental
670:   us of the array after it has been restored. If you pass `NULL`, it will
671:   not zero the pointers. Use of `cols` or `vals` after `MatRestoreRow()` is invalid.

673:   Fortran Note:
674: .vb
675:   PetscInt, pointer :: cols(:)
676:   PetscScalar, pointer :: vals(:)
677: .ve

679: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
680: @*/
681: PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
682: {
683:   PetscFunctionBegin;
685:   if (ncols) PetscAssertPointer(ncols, 3);
686:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
687:   PetscTryTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
688:   if (ncols) *ncols = 0;
689:   if (cols) *cols = NULL;
690:   if (vals) *vals = NULL;
691:   PetscFunctionReturn(PETSC_SUCCESS);
692: }

694: /*@
695:   MatGetRowUpperTriangular - Sets a flag to enable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
696:   You should call `MatRestoreRowUpperTriangular()` after calling` MatGetRow()` and `MatRestoreRow()` to disable the flag.

698:   Not Collective

700:   Input Parameter:
701: . mat - the matrix

703:   Level: advanced

705:   Note:
706:   The flag is to ensure that users are aware that `MatGetRow()` only provides the upper triangular part of the row for the matrices in `MATSBAIJ` format.

708: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
709: @*/
710: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
711: {
712:   PetscFunctionBegin;
715:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
716:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
717:   MatCheckPreallocated(mat, 1);
718:   PetscTryTypeMethod(mat, getrowuppertriangular);
719:   PetscFunctionReturn(PETSC_SUCCESS);
720: }

722: /*@
723:   MatRestoreRowUpperTriangular - Disable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.

725:   Not Collective

727:   Input Parameter:
728: . mat - the matrix

730:   Level: advanced

732:   Note:
733:   This routine should be called after you have finished calls to `MatGetRow()` and `MatRestoreRow()`.

735: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
736: @*/
737: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
738: {
739:   PetscFunctionBegin;
742:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
743:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
744:   MatCheckPreallocated(mat, 1);
745:   PetscTryTypeMethod(mat, restorerowuppertriangular);
746:   PetscFunctionReturn(PETSC_SUCCESS);
747: }

749: /*@
750:   MatSetOptionsPrefix - Sets the prefix used for searching for all
751:   `Mat` options in the database.

753:   Logically Collective

755:   Input Parameters:
756: + A      - the matrix
757: - prefix - the prefix to prepend to all option names

759:   Level: advanced

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

765:   This is NOT used for options for the factorization of the matrix. Normally the
766:   prefix is automatically passed in from the PC calling the factorization. To set
767:   it directly use  `MatSetOptionsPrefixFactor()`

769: .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
770: @*/
771: PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
772: {
773:   PetscFunctionBegin;
775:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
776:   PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
777:   PetscFunctionReturn(PETSC_SUCCESS);
778: }

780: /*@
781:   MatSetOptionsPrefixFactor - Sets the prefix used for searching for all matrix factor options in the database for
782:   for matrices created with `MatGetFactor()`

784:   Logically Collective

786:   Input Parameters:
787: + A      - the matrix
788: - prefix - the prefix to prepend to all option names for the factored matrix

790:   Level: developer

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

796:   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
797:   it directly when not using `KSP`/`PC` use  `MatSetOptionsPrefixFactor()`

799: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
800: @*/
801: PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
802: {
803:   PetscFunctionBegin;
805:   if (prefix) {
806:     PetscAssertPointer(prefix, 2);
807:     PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
808:     if (prefix != A->factorprefix) {
809:       PetscCall(PetscFree(A->factorprefix));
810:       PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
811:     }
812:   } else PetscCall(PetscFree(A->factorprefix));
813:   PetscFunctionReturn(PETSC_SUCCESS);
814: }

816: /*@
817:   MatAppendOptionsPrefixFactor - Appends to the prefix used for searching for all matrix factor options in the database for
818:   for matrices created with `MatGetFactor()`

820:   Logically Collective

822:   Input Parameters:
823: + A      - the matrix
824: - prefix - the prefix to prepend to all option names for the factored matrix

826:   Level: developer

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

832:   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
833:   it directly when not using `KSP`/`PC` use  `MatAppendOptionsPrefixFactor()`

835: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
836:           `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
837:           `MatSetOptionsPrefix()`
838: @*/
839: PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
840: {
841:   size_t len1, len2, new_len;

843:   PetscFunctionBegin;
845:   if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
846:   if (!A->factorprefix) {
847:     PetscCall(MatSetOptionsPrefixFactor(A, prefix));
848:     PetscFunctionReturn(PETSC_SUCCESS);
849:   }
850:   PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");

852:   PetscCall(PetscStrlen(A->factorprefix, &len1));
853:   PetscCall(PetscStrlen(prefix, &len2));
854:   new_len = len1 + len2 + 1;
855:   PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
856:   PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
857:   PetscFunctionReturn(PETSC_SUCCESS);
858: }

860: /*@
861:   MatAppendOptionsPrefix - Appends to the prefix used for searching for all
862:   matrix options in the database.

864:   Logically Collective

866:   Input Parameters:
867: + A      - the matrix
868: - prefix - the prefix to prepend to all option names

870:   Level: advanced

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

876: .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
877: @*/
878: PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
879: {
880:   PetscFunctionBegin;
882:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
883:   PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
884:   PetscFunctionReturn(PETSC_SUCCESS);
885: }

887: /*@
888:   MatGetOptionsPrefix - Gets the prefix used for searching for all
889:   matrix options in the database.

891:   Not Collective

893:   Input Parameter:
894: . A - the matrix

896:   Output Parameter:
897: . prefix - pointer to the prefix string used

899:   Level: advanced

901: .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
902: @*/
903: PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
904: {
905:   PetscFunctionBegin;
907:   PetscAssertPointer(prefix, 2);
908:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
909:   PetscFunctionReturn(PETSC_SUCCESS);
910: }

912: /*@
913:   MatGetState - Gets a snapshot of the state of a `Mat`

915:   Not Collective, No Fortran Support

917:   Input Parameter:
918: . A - the matrix

920:   Output Parameter:
921: . state - the matrix state

923:   Level: developer

925:   Notes:
926:   The snapshot includes the matrix identity, object state, and nonzero state. Use `MatStateCompare()` to determine whether two snapshots are the same, or `MatStateCompareUpdate()` to compare and update a saved snapshot.

928: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatStateCompare()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
929: @*/
930: PetscErrorCode MatGetState(Mat A, MatState *state)
931: {
932:   PetscFunctionBegin;
934:   PetscAssertPointer(state, 2);
935:   state->id           = ((PetscObject)A)->id;
936:   state->state        = ((PetscObject)A)->state;
937:   state->nonzerostate = A->nonzerostate;
938:   PetscFunctionReturn(PETSC_SUCCESS);
939: }

941: /*@
942:   MatStateCompare - Compares two matrix state snapshots

944:   Not Collective, No Fortran Support

946:   Input Parameters:
947: + state1 - the first matrix state
948: - state2 - the second matrix state

950:   Output Parameter:
951: . same - `PETSC_TRUE` if the matrix identity, object state, and nonzero state are the same, `PETSC_FALSE` otherwise

953:   Level: developer

955: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`
956: @*/
957: PetscErrorCode MatStateCompare(MatState state1, MatState state2, PetscBool *same)
958: {
959:   PetscFunctionBegin;
960:   PetscAssertPointer(same, 3);
961:   *same = (PetscBool)(state1.id == state2.id && state1.state == state2.state && state1.nonzerostate == state2.nonzerostate);
962:   PetscFunctionReturn(PETSC_SUCCESS);
963: }

965: /*@
966:   MatStateCompareUpdate - Compares a matrix with a state snapshot, then updates the snapshot

968:   Not Collective, No Fortran Support

970:   Input Parameter:
971: . A - the matrix

973:   Input/Output Parameter:
974: . state - the matrix state snapshot to compare with and update

976:   Output Parameter:
977: . same - `PETSC_TRUE` if the matrix state matched the snapshot before it was updated, `PETSC_FALSE` otherwise

979:   Level: developer

981: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompare()`, `MatStateInvalidate()`
982: @*/
983: PetscErrorCode MatStateCompareUpdate(Mat A, MatState *state, PetscBool *same)
984: {
985:   MatState current;

987:   PetscFunctionBegin;
989:   PetscAssertPointer(state, 2);
990:   PetscAssertPointer(same, 3);
991:   PetscCall(MatGetState(A, &current));
992:   PetscCall(MatStateCompare(current, *state, same));
993:   *state = current;
994:   PetscFunctionReturn(PETSC_SUCCESS);
995: }

997: /*@
998:   MatResetPreallocation - Reset matrix to use the original preallocation values provided by the user, for example with `MatXAIJSetPreallocation()`

1000:   Collective

1002:   Input Parameter:
1003: . A - the matrix

1005:   Level: beginner

1007:   Notes:
1008:   After calling `MatAssemblyBegin()` and `MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY` the matrix data structures represent the nonzeros assigned to the
1009:   matrix. If that space is less than the preallocated space that extra preallocated space is no longer available to take on new values. `MatResetPreallocation()`
1010:   makes all of the preallocation space available

1012:   Current values in the matrix are lost in this call

1014:   Currently only supported for  `MATAIJ` matrices.

1016: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
1017: @*/
1018: PetscErrorCode MatResetPreallocation(Mat A)
1019: {
1020:   PetscFunctionBegin;
1023:   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
1024:   PetscFunctionReturn(PETSC_SUCCESS);
1025: }

1027: /*@
1028:   MatResetHash - Reset the matrix so that it will use a hash table for the next round of `MatSetValues()` and `MatAssemblyBegin()`/`MatAssemblyEnd()`.

1030:   Collective

1032:   Input Parameter:
1033: . A - the matrix

1035:   Level: intermediate

1037:   Notes:
1038:   The matrix will again delete the hash table data structures after following calls to `MatAssemblyBegin()`/`MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY`.

1040:   Currently only supported for `MATAIJ` matrices.

1042: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
1043: @*/
1044: PetscErrorCode MatResetHash(Mat A)
1045: {
1046:   PetscFunctionBegin;
1049:   PetscCheck(A->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset to hash state after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
1050:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
1051:   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
1052:   /* These flags are used to determine whether certain setups occur */
1053:   A->was_assembled = PETSC_FALSE;
1054:   A->assembled     = PETSC_FALSE;
1055:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
1056:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1057:   PetscFunctionReturn(PETSC_SUCCESS);
1058: }

1060: /*@
1061:   MatSetUp - Sets up the internal matrix data structures for later use by the matrix

1063:   Collective

1065:   Input Parameter:
1066: . A - the matrix

1068:   Level: advanced

1070:   Notes:
1071:   If the user has not set preallocation for this matrix then an efficient algorithm will be used for the first round of
1072:   setting values in the matrix.

1074:   This routine is called internally by other `Mat` functions when needed so rarely needs to be called by users

1076: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
1077: @*/
1078: PetscErrorCode MatSetUp(Mat A)
1079: {
1080:   PetscFunctionBegin;
1082:   if (!((PetscObject)A)->type_name) {
1083:     PetscMPIInt size;

1085:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1086:     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
1087:   }
1088:   if (!A->preallocated) PetscTryTypeMethod(A, setup);
1089:   PetscCall(PetscLayoutSetUp(A->rmap));
1090:   PetscCall(PetscLayoutSetUp(A->cmap));
1091:   A->preallocated = PETSC_TRUE;
1092:   PetscFunctionReturn(PETSC_SUCCESS);
1093: }

1095: #if PetscDefined(HAVE_SAWS)
1096: #include <petscviewersaws.h>
1097: #endif

1099: /*
1100:    If threadsafety is on extraneous matrices may be printed

1102:    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1103: */
1104: #if !PetscDefined(HAVE_THREADSAFETY)
1105: static PetscInt insidematview = 0;
1106: #endif

1108: /*@
1109:   MatViewFromOptions - View properties of the matrix based on options set in the options database

1111:   Collective

1113:   Input Parameters:
1114: + A    - the matrix
1115: . obj  - optional additional object that provides the options prefix to use
1116: - name - command line option

1118:   Options Database Key:
1119: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

1121:   Level: intermediate

1123:   Note:
1124:   This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
1125:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

1127: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`, `PetscOptionsCreateViewer()`
1128: @*/
1129: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1130: {
1131:   PetscFunctionBegin;
1133: #if !PetscDefined(HAVE_THREADSAFETY)
1134:   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1135: #endif
1136:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1137:   PetscFunctionReturn(PETSC_SUCCESS);
1138: }

1140: /*@
1141:   MatView - display information about a matrix in a variety ways

1143:   Collective on viewer

1145:   Input Parameters:
1146: + mat    - the matrix
1147: - viewer - visualization context

1149:   Options Database Key:
1150: . -mat_view viewer_specification - Call `MatView()` at the conclusion of `MatAssemblyEnd()` or other routines that have changed the matrix values.
1151:                                    See `PetscOptionsCreateViewer()` for the values of `viewer_specification`.

1153:   Level: beginner

1155:   Notes:
1156:   The available visualization contexts include
1157: +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1158: .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1159: .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1160: -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure

1162:   The user can open alternative visualization contexts with
1163: +    `PetscViewerASCIIOpen()`  - Outputs matrix to a specified file
1164: .    `PetscViewerBinaryOpen()` - Outputs matrix in binary to a  specified file; corresponding input uses `MatLoad()`
1165: .    `PetscViewerDrawOpen()`   - Outputs nonzero matrix nonzero structure to an X window display
1166: -    `PetscViewerSocketOpen()` - Outputs matrix to Socket viewer, `PETSCVIEWERSOCKET`. Only the `MATSEQDENSE` and `MATAIJ` types support this viewer.

1168:   The user can call `PetscViewerPushFormat()` to specify the output
1169:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1170:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`). Available formats include
1171: +    `PETSC_VIEWER_DEFAULT`           - default, prints matrix contents
1172: .    `PETSC_VIEWER_ASCII_MATLAB`      - prints matrix contents in MATLAB format
1173: .    `PETSC_VIEWER_ASCII_DENSE`       - prints entire matrix including zeros
1174: .    `PETSC_VIEWER_ASCII_COMMON`      - prints matrix contents, using a sparse  format common among all matrix types
1175: .    `PETSC_VIEWER_ASCII_IMPL`        - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1176: .    `PETSC_VIEWER_ASCII_INFO`        - prints basic information about the matrix size and structure (not the matrix entries)
1177: -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)

1179:   The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
1180:   the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.

1182:   In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).

1184:   See the manual page for `MatLoad()` for the exact format of the binary file when the binary
1185:   viewer is used.

1187:   `MatViewFromOptions()` provides an alternative to this routine that only views the matrix if the requested value
1188:   is provided in the options database.

1190:   See `share/petsc/matlab/PetscBinaryRead.m` for a MATLAB code that can read in the binary file when the binary
1191:   viewer is used and `lib/petsc/bin/PetscBinaryIO.py` for loading them into Python.

1193:   One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1194:   and then use the following mouse functions.
1195: .vb
1196:   left mouse: zoom in
1197:   middle mouse: zoom out
1198:   right mouse: continue with the simulation
1199: .ve

1201: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1202:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`, `PetscOptionsCreateViewer()`
1203: @*/
1204: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1205: {
1206:   PetscInt          rows, cols, rbs, cbs;
1207:   PetscBool         isascii, isstring, issaws;
1208:   PetscViewerFormat format;
1209:   PetscMPIInt       size;

1211:   PetscFunctionBegin;
1214:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

1217:   PetscCall(PetscViewerGetFormat(viewer, &format));
1218:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1219:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

1221: #if !PetscDefined(HAVE_THREADSAFETY)
1222:   insidematview++;
1223: #endif
1224:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1225:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1226:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1227:   PetscCheck((isascii && (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) || !mat->factortype, PetscObjectComm((PetscObject)viewer), PETSC_ERR_ARG_WRONGSTATE, "No viewers for factored matrix except ASCII, info, or info_detail");

1229:   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1230:   if (isascii) {
1231:     if (!mat->preallocated) {
1232:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1233: #if !PetscDefined(HAVE_THREADSAFETY)
1234:       insidematview--;
1235: #endif
1236:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1237:       PetscFunctionReturn(PETSC_SUCCESS);
1238:     }
1239:     if (!mat->assembled) {
1240:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1241: #if !PetscDefined(HAVE_THREADSAFETY)
1242:       insidematview--;
1243: #endif
1244:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1245:       PetscFunctionReturn(PETSC_SUCCESS);
1246:     }
1247:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1248:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1249:       MatNullSpace nullsp, transnullsp;
1250:       PetscBool    nz_factor = PETSC_TRUE;

1252:       PetscCall(PetscViewerASCIIPushTab(viewer));
1253:       PetscCall(MatGetSize(mat, &rows, &cols));
1254:       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1255:       if (rbs != 1 || cbs != 1) {
1256:         if (rbs != cbs) PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", rbs=%" PetscInt_FMT ", cbs=%" PetscInt_FMT "%s\n", rows, cols, rbs, cbs, mat->bsizes ? " variable blocks set" : ""));
1257:         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1258:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1259:       if (mat->factortype) {
1260:         MatSolverType solver;

1262:         PetscCall(MatFactorGetSolverType(mat, &solver));
1263:         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1264:         PetscCall(PetscStrcmpAny(solver, &nz_factor, MATSOLVERUMFPACK, MATSOLVERCHOLMOD, MATSOLVERSUPERLU, MATSOLVERSUPERLU_DIST, MATSOLVERSTRUMPACK, MATSOLVERHTOOL, ""));
1265:         nz_factor = !nz_factor;
1266:       }
1267:       if (mat->ops->getinfo) {
1268:         PetscBool is_constant_or_diagonal;

1270:         // Don't print nonzero information for constant or diagonal matrices, it just adds noise to the output
1271:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &is_constant_or_diagonal, MATCONSTANTDIAGONAL, MATDIAGONAL, ""));
1272:         if (!is_constant_or_diagonal && nz_factor) {
1273:           MatInfo info;

1275:           PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1276:           PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1277:           if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1278:         }
1279:       }
1280:       PetscCall(MatGetNullSpace(mat, &nullsp));
1281:       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1282:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1283:       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1284:       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1285:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1286:       PetscCall(PetscViewerASCIIPushTab(viewer));
1287:       PetscCall(MatProductView(mat, viewer));
1288:       PetscCall(PetscViewerASCIIPopTab(viewer));
1289:       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1290:         IS tmp;

1292:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1293:         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1294:         PetscCall(PetscViewerASCIIPushTab(viewer));
1295:         PetscCall(ISView(tmp, viewer));
1296:         PetscCall(PetscViewerASCIIPopTab(viewer));
1297:         PetscCall(ISDestroy(&tmp));
1298:       }
1299:     }
1300:   } else if (issaws) {
1301: #if PetscDefined(HAVE_SAWS)
1302:     PetscMPIInt rank;

1304:     PetscCall(PetscObjectName((PetscObject)mat));
1305:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1306:     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1307: #endif
1308:   } else if (isstring) {
1309:     const char *type;
1310:     PetscCall(MatGetType(mat, &type));
1311:     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1312:     PetscTryTypeMethod(mat, view, viewer);
1313:   }
1314:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1315:     PetscCall(PetscViewerASCIIPushTab(viewer));
1316:     PetscUseTypeMethod(mat, viewnative, viewer);
1317:     PetscCall(PetscViewerASCIIPopTab(viewer));
1318:   } else if (mat->ops->view) {
1319:     PetscCall(PetscViewerASCIIPushTab(viewer));
1320:     PetscUseTypeMethod(mat, view, viewer);
1321:     PetscCall(PetscViewerASCIIPopTab(viewer));
1322:   }
1323:   if (isascii) {
1324:     PetscCall(PetscViewerGetFormat(viewer, &format));
1325:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1326:   }
1327:   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1328: #if !PetscDefined(HAVE_THREADSAFETY)
1329:   insidematview--;
1330: #endif
1331:   PetscFunctionReturn(PETSC_SUCCESS);
1332: }

1334: #if PetscDefined(USE_DEBUG)
1335: #include <../src/sys/totalview/tv_data_display.h>
1336: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1337: {
1338:   TV_add_row("Local rows", "int", &mat->rmap->n);
1339:   TV_add_row("Local columns", "int", &mat->cmap->n);
1340:   TV_add_row("Global rows", "int", &mat->rmap->N);
1341:   TV_add_row("Global columns", "int", &mat->cmap->N);
1342:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1343:   return TV_format_OK;
1344: }
1345: #endif

1347: /*@
1348:   MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1349:   with `MatView()`. The matrix format is determined from the options database.
1350:   Generates a parallel MPI matrix if the communicator has more than one
1351:   process. The default matrix type is `MATAIJ`.

1353:   Collective

1355:   Input Parameters:
1356: + mat    - the newly loaded matrix, this needs to have been created with `MatCreate()`
1357:             or some related function before a call to `MatLoad()`
1358: - viewer - `PETSCVIEWERBINARY`/`PETSCVIEWERHDF5` file viewer

1360:   Options Database Key:
1361: . -matload_block_size bs - set block size

1363:   Level: beginner

1365:   Notes:
1366:   If the `Mat` type has not yet been given then `MATAIJ` is used, call `MatSetFromOptions()` on the
1367:   `Mat` before calling this routine if you wish to set it from the options database.

1369:   `MatLoad()` automatically loads into the options database any options
1370:   given in the file filename.info where filename is the name of the file
1371:   that was passed to the `PetscViewerBinaryOpen()`. The options in the info
1372:   file will be ignored if you use the `-viewer_binary_skip_info` option.

1374:   If the type or size of mat is not set before a call to `MatLoad()`, PETSc
1375:   sets the default matrix type AIJ and sets the local and global sizes.
1376:   If type and/or size is already set, then the same are used.

1378:   In parallel, each process can load a subset of rows (or the
1379:   entire matrix). This routine is especially useful when a large
1380:   matrix is stored on disk and only part of it is desired on each
1381:   process. For example, a parallel solver may access only some of
1382:   the rows from each process. The algorithm used here reads
1383:   relatively small blocks of data rather than reading the entire
1384:   matrix and then subsetting it.

1386:   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1387:   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1388:   or the sequence like
1389: .vb
1390:     PetscViewer v;
1391:     PetscViewerCreate(PETSC_COMM_WORLD, &v);
1392:     PetscViewerSetType(v, PETSCVIEWERBINARY);
1393:     PetscViewerSetFromOptions(v);
1394:     PetscViewerFileSetMode(v, FILE_MODE_READ);
1395:     PetscViewerFileSetName(v, "datafile");
1396: .ve
1397:   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1398: .vb
1399:   -viewer_type (binary|hdf5)
1400: .ve

1402:   See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1403:   and src/mat/tutorials/ex10.c with the second approach.

1405:   In case of `PETSCVIEWERBINARY`, a native PETSc binary format is used. Each of the blocks
1406:   is read onto MPI rank 0 and then shipped to its destination MPI rank, one after another.
1407:   Multiple objects, both matrices and vectors, can be stored within the same file.
1408:   Their `PetscObject` name is ignored; they are loaded in the order of their storage.

1410:   Most users should not need to know the details of the binary storage
1411:   format, since `MatLoad()` and `MatView()` completely hide these details.
1412:   But for anyone who is interested, the standard binary matrix storage
1413:   format is

1415: .vb
1416:     PetscInt    MAT_FILE_CLASSID
1417:     PetscInt    number of rows
1418:     PetscInt    number of columns
1419:     PetscInt    total number of nonzeros
1420:     PetscInt    *number nonzeros in each row
1421:     PetscInt    *column indices of all nonzeros (starting index is zero)
1422:     PetscScalar *values of all nonzeros
1423: .ve
1424:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1425:   stored or loaded (each MPI process part of the matrix must have less than `PETSC_INT_MAX` nonzeros). Since the total nonzero count in this
1426:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

1428:   PETSc automatically does the byte swapping for
1429:   machines that store the bytes reversed. Thus if you write your own binary
1430:   read/write routines you have to swap the bytes; see `PetscBinaryRead()`
1431:   and `PetscBinaryWrite()` to see how this may be done.

1433:   In case of `PETSCVIEWERHDF5`, a parallel HDF5 reader is used.
1434:   Each process's chunk is loaded independently by its owning MPI process.
1435:   Multiple objects, both matrices and vectors, can be stored within the same file.
1436:   They are looked up by their PetscObject name.

1438:   As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1439:   by default the same structure and naming of the AIJ arrays and column count
1440:   within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1441: .vb
1442:   save example.mat A b -v7.3
1443: .ve
1444:   can be directly read by this routine (see Reference 1 for details).

1446:   Depending on your MATLAB version, this format might be a default,
1447:   otherwise you can set it as default in Preferences.

1449:   Unless `-nocompression` flag is used to save the file in MATLAB,
1450:   PETSc must be configured with ZLIB package.

1452:   See also examples `src/mat/tutorials/ex10.c` and `src/ksp/ksp/tutorials/ex27.c`

1454:   This reader currently supports only real `MATSEQAIJ`, `MATMPIAIJ`, `MATSEQDENSE`, and `MATMPIDENSE` matrices for `PETSCVIEWERHDF5`

1456:   Corresponding `MatView()` is not yet implemented.

1458:   The loaded matrix is actually a transpose of the original one in MATLAB,
1459:   unless you push `PETSC_VIEWER_HDF5_MAT` format (see examples above).
1460:   With this format, matrix is automatically transposed by PETSc,
1461:   unless the matrix is marked as SPD or symmetric
1462:   (see `MatSetOption()`, `MAT_SPD`, `MAT_SYMMETRIC`).

1464:   See MATLAB Documentation on `save()`, <https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version>

1466: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1467:  @*/
1468: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1469: {
1470:   PetscBool flg;

1472:   PetscFunctionBegin;

1476:   if (!((PetscObject)mat)->type_name) PetscCall(MatSetType(mat, MATAIJ));

1478:   flg = PETSC_FALSE;
1479:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1480:   if (flg) {
1481:     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1482:     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1483:   }
1484:   flg = PETSC_FALSE;
1485:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1486:   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));

1488:   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1489:   PetscUseTypeMethod(mat, load, viewer);
1490:   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1491:   PetscFunctionReturn(PETSC_SUCCESS);
1492: }

1494: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1495: {
1496:   Mat_Redundant *redund = *redundant;

1498:   PetscFunctionBegin;
1499:   if (redund) {
1500:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1501:       PetscCall(ISDestroy(&redund->isrow));
1502:       PetscCall(ISDestroy(&redund->iscol));
1503:       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1504:     } else {
1505:       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1506:       PetscCall(PetscFree(redund->sbuf_j));
1507:       PetscCall(PetscFree(redund->sbuf_a));
1508:       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1509:         PetscCall(PetscFree(redund->rbuf_j[i]));
1510:         PetscCall(PetscFree(redund->rbuf_a[i]));
1511:       }
1512:       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1513:     }

1515:     PetscCall(PetscCommDestroy(&redund->subcomm));
1516:     PetscCall(PetscFree(redund));
1517:   }
1518:   PetscFunctionReturn(PETSC_SUCCESS);
1519: }

1521: /*@
1522:   MatDestroy - Frees space taken by a matrix.

1524:   Collective

1526:   Input Parameter:
1527: . A - the matrix

1529:   Level: beginner

1531:   Developer Note:
1532:   Some special arrays of matrices are not destroyed in this routine but instead by the routines called by
1533:   `MatDestroySubMatrices()`. Thus one must be sure that any changes here must also be made in those routines.
1534:   `MatHeaderMerge()` and `MatHeaderReplace()` also manipulate the data in the `Mat` object and likely need changes
1535:   if changes are needed here.

1537: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1538: @*/
1539: PetscErrorCode MatDestroy(Mat *A)
1540: {
1541:   PetscFunctionBegin;
1542:   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1544:   if (--((PetscObject)*A)->refct > 0) {
1545:     *A = NULL;
1546:     PetscFunctionReturn(PETSC_SUCCESS);
1547:   }

1549:   /* if memory was published with SAWs then destroy it */
1550:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1551:   PetscTryTypeMethod(*A, destroy);

1553:   PetscCall(PetscFree((*A)->factorprefix));
1554:   PetscCall(PetscFree((*A)->defaultvectype));
1555:   PetscCall(PetscFree((*A)->defaultrandtype));
1556:   PetscCall(PetscFree((*A)->bsizes));
1557:   PetscCall(PetscFree((*A)->solvertype));
1558:   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1559:   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1560:   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1561:   PetscCall(MatProductClear(*A));
1562:   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1563:   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1564:   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1565:   PetscCall(MatDestroy(&(*A)->schur));
1566:   PetscCall(VecDestroy(&(*A)->dot_vec));
1567:   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1568:   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1569:   PetscCall(PetscHeaderDestroy(A));
1570:   PetscFunctionReturn(PETSC_SUCCESS);
1571: }

1573: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1574: /*@
1575:   MatSetValues - Inserts or adds a block of values into a matrix.
1576:   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1577:   MUST be called after all calls to `MatSetValues()` have been completed.

1579:   Not Collective

1581:   Input Parameters:
1582: + mat  - the matrix
1583: . m    - the number of rows
1584: . idxm - the global indices of the rows
1585: . n    - the number of columns
1586: . idxn - the global indices of the columns
1587: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1588:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1589: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

1591:   Level: beginner

1593:   Notes:
1594:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1595:   options cannot be mixed without intervening calls to the assembly
1596:   routines.

1598:   `MatSetValues()` uses 0-based row and column numbers in Fortran
1599:   as well as in C.

1601:   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are simply ignored. This allows easily inserting element stiffness matrices
1602:   with homogeneous Dirichlet boundary conditions that you don't want represented
1603:   in the matrix.

1605:   Efficiency Alert:
1606:   The routine `MatSetValuesBlocked()` may offer much better efficiency
1607:   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).

1609:   Fortran Notes:
1610:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1611: .vb
1612:   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1613: .ve

1615:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1616:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

1618: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1619:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1620: @*/
1621: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1622: {
1623:   PetscFunctionBeginHot;
1626:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1627:   PetscAssertPointer(idxm, 3);
1628:   PetscAssertPointer(idxn, 5);
1629:   MatCheckPreallocated(mat, 1);

1631:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
1632:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");

1634:   if (PetscDefined(USE_DEBUG)) {
1635:     PetscInt i, j;

1637:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1638:     if (v) {
1639:       for (i = 0; i < m; i++) {
1640:         for (j = 0; j < n; j++) {
1641:           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1642: #if PetscDefined(USE_COMPLEX)
1643:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FP, "Inserting %g+i%g at matrix entry (%" PetscInt_FMT ",%" PetscInt_FMT ")", (double)PetscRealPart(v[i * n + j]), (double)PetscImaginaryPart(v[i * n + j]), idxm[i], idxn[j]);
1644: #else
1645:             SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FP, "Inserting %g at matrix entry (%" PetscInt_FMT ",%" PetscInt_FMT ")", (double)v[i * n + j], idxm[i], idxn[j]);
1646: #endif
1647:         }
1648:       }
1649:     }
1650:     for (i = 0; i < m; i++) PetscCheck(idxm[i] < mat->rmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot insert in row %" PetscInt_FMT ", maximum is %" PetscInt_FMT, idxm[i], mat->rmap->N - 1);
1651:     for (i = 0; i < n; i++) PetscCheck(idxn[i] < mat->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot insert in column %" PetscInt_FMT ", maximum is %" PetscInt_FMT, idxn[i], mat->cmap->N - 1);
1652:   }

1654:   if (mat->assembled) {
1655:     mat->was_assembled = PETSC_TRUE;
1656:     mat->assembled     = PETSC_FALSE;
1657:   }
1658:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1659:   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1660:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1661:   PetscFunctionReturn(PETSC_SUCCESS);
1662: }

1664: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1665: /*@
1666:   MatSetValuesIS - Inserts or adds a block of values into a matrix using an `IS` to indicate the rows and columns
1667:   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1668:   MUST be called after all calls to `MatSetValues()` have been completed.

1670:   Not Collective

1672:   Input Parameters:
1673: + mat  - the matrix
1674: . ism  - the rows to provide
1675: . isn  - the columns to provide
1676: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1677:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1678: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

1680:   Level: beginner

1682:   Notes:
1683:   By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

1685:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1686:   options cannot be mixed without intervening calls to the assembly
1687:   routines.

1689:   `MatSetValues()` uses 0-based row and column numbers in Fortran
1690:   as well as in C.

1692:   Negative indices may be passed in `ism` and `isn`, these rows and columns are
1693:   simply ignored. This allows easily inserting element stiffness matrices
1694:   with homogeneous Dirichlet boundary conditions that you don't want represented
1695:   in the matrix.

1697:   Fortran Note:
1698:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1699:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

1701:   Efficiency Alert:
1702:   The routine `MatSetValuesBlocked()` may offer much better efficiency
1703:   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).

1705:   This is currently not optimized for any particular `ISType`

1707: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1708:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1709: @*/
1710: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1711: {
1712:   PetscInt        m, n;
1713:   const PetscInt *rows, *cols;

1715:   PetscFunctionBeginHot;
1717:   PetscCall(ISGetIndices(ism, &rows));
1718:   PetscCall(ISGetIndices(isn, &cols));
1719:   PetscCall(ISGetLocalSize(ism, &m));
1720:   PetscCall(ISGetLocalSize(isn, &n));
1721:   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1722:   PetscCall(ISRestoreIndices(ism, &rows));
1723:   PetscCall(ISRestoreIndices(isn, &cols));
1724:   PetscFunctionReturn(PETSC_SUCCESS);
1725: }

1727: /*@
1728:   MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix

1730:   Not Collective

1732:   Input Parameters:
1733: + mat - the matrix
1734: . row - the row to set
1735: - v   - a one-dimensional array that contains the values

1737:   Level: intermediate

1739:   Notes:
1740:   Currently only supported for `MATAIJ`.

1742:   All the nonzero values in `row` must be provided

1744:   The matrix must have previously had its column indices set, likely by having been assembled.

1746:   `row` must belong to this MPI process

1748: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1749:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1750: @*/
1751: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1752: {
1753:   PetscInt globalrow;

1755:   PetscFunctionBegin;
1758:   PetscAssertPointer(v, 3);
1759:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1760:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1761:   PetscFunctionReturn(PETSC_SUCCESS);
1762: }

1764: /*@
1765:   MatSetValuesRow - Inserts a row of nonzero values into a matrix

1767:   Not Collective

1769:   Input Parameters:
1770: + mat - the matrix
1771: . row - the row to set
1772: - v   - a one dimensional array of values

1774:   Level: advanced

1776:   Notes:
1777:   Currently only supported for `MATAIJ`.

1779:   All the nonzeros in `row` must be provided

1781:   The matrix must have previously had its column indices set, likely by having been assembled.

1783:   `row` must belong to this process

1785: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1786:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MATAIJ`
1787: @*/
1788: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1789: {
1790:   PetscFunctionBeginHot;
1793:   MatCheckPreallocated(mat, 1);
1794:   PetscAssertPointer(v, 3);
1795:   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1796:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1797:   mat->insertmode = INSERT_VALUES;

1799:   if (mat->assembled) {
1800:     mat->was_assembled = PETSC_TRUE;
1801:     mat->assembled     = PETSC_FALSE;
1802:   }
1803:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1804:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1805:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1806:   PetscFunctionReturn(PETSC_SUCCESS);
1807: }

1809: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1810: /*@
1811:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1812:   Using structured grid indexing

1814:   Not Collective

1816:   Input Parameters:
1817: + mat  - the matrix
1818: . m    - number of rows being entered
1819: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1820: . n    - number of columns being entered
1821: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1822: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1823:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1824: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values

1826:   Level: beginner

1828:   Notes:
1829:   By default the values, `v`, are row-oriented. See `MatSetOption()` for other options.

1831:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1832:   options cannot be mixed without intervening calls to the assembly
1833:   routines.

1835:   The grid coordinates are across the entire grid, not just the local portion

1837:   `MatSetValuesStencil()` uses 0-based row and column numbers in Fortran
1838:   as well as in C.

1840:   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine

1842:   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1843:   or call `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.

1845:   The columns and rows in the stencil passed in MUST be contained within the
1846:   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1847:   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1848:   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1849:   first i index you can use in your column and row indices in `MatSetStencil()` is 5.

1851:   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1852:   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1853:   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1854:   `DM_BOUNDARY_PERIODIC` boundary type.

1856:   For indices that don't mean anything for your case (like the k index when working in 2d) or the c index when you have
1857:   a single value per point) you can skip filling those indices.

1859:   Inspired by the structured grid interface to the HYPRE package
1860:   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)

1862:   Fortran Notes:
1863:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1864: .vb
1865:   call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1866: .ve

1868:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1869:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

1871:   Efficiency Alert:
1872:   The routine `MatSetValuesBlockedStencil()` may offer much better efficiency
1873:   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).

1875: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1876:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`
1877: @*/
1878: PetscErrorCode MatSetValuesStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1879: {
1880:   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1881:   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1882:   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1884:   PetscFunctionBegin;
1885:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1888:   PetscAssertPointer(idxm, 3);
1889:   PetscAssertPointer(idxn, 5);

1891:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1892:     jdxm = buf;
1893:     jdxn = buf + m;
1894:   } else {
1895:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1896:     jdxm = bufm;
1897:     jdxn = bufn;
1898:   }
1899:   for (i = 0; i < m; i++) {
1900:     for (j = 0; j < 3 - sdim; j++) dxm++;
1901:     tmp = *dxm++ - starts[0];
1902:     for (j = 0; j < dim - 1; j++) {
1903:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1904:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1905:     }
1906:     if (mat->stencil.noc) dxm++;
1907:     jdxm[i] = tmp;
1908:   }
1909:   for (i = 0; i < n; i++) {
1910:     for (j = 0; j < 3 - sdim; j++) dxn++;
1911:     tmp = *dxn++ - starts[0];
1912:     for (j = 0; j < dim - 1; j++) {
1913:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1914:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1915:     }
1916:     if (mat->stencil.noc) dxn++;
1917:     jdxn[i] = tmp;
1918:   }
1919:   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1920:   PetscCall(PetscFree2(bufm, bufn));
1921:   PetscFunctionReturn(PETSC_SUCCESS);
1922: }

1924: /*@
1925:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1926:   Using structured grid indexing

1928:   Not Collective

1930:   Input Parameters:
1931: + mat  - the matrix
1932: . m    - number of rows being entered
1933: . idxm - grid coordinates for matrix rows being entered
1934: . n    - number of columns being entered
1935: . idxn - grid coordinates for matrix columns being entered
1936: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1937:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1938: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values

1940:   Level: beginner

1942:   Notes:
1943:   By default the values, `v`, are row-oriented and unsorted.
1944:   See `MatSetOption()` for other options.

1946:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1947:   options cannot be mixed without intervening calls to the assembly
1948:   routines.

1950:   The grid coordinates are across the entire grid, not just the local portion

1952:   `MatSetValuesBlockedStencil()` uses 0-based row and column numbers in Fortran
1953:   as well as in C.

1955:   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine

1957:   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1958:   or call `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.

1960:   The columns and rows in the stencil passed in MUST be contained within the
1961:   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1962:   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1963:   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1964:   first i index you can use in your column and row indices in `MatSetStencil()` is 5.

1966:   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1967:   simply ignored. This allows easily inserting element stiffness matrices
1968:   with homogeneous Dirichlet boundary conditions that you don't want represented
1969:   in the matrix.

1971:   Inspired by the structured grid interface to the HYPRE package
1972:   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)

1974:   Fortran Notes:
1975:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1976: .vb
1977:   call MatSetValuesBlockedStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1978: .ve

1980:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1981:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

1983: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1984:           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1985:           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1986: @*/
1987: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1988: {
1989:   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1990:   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1991:   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1993:   PetscFunctionBegin;
1994:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1997:   PetscAssertPointer(idxm, 3);
1998:   PetscAssertPointer(idxn, 5);
1999:   PetscAssertPointer(v, 6);

2001:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2002:     jdxm = buf;
2003:     jdxn = buf + m;
2004:   } else {
2005:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
2006:     jdxm = bufm;
2007:     jdxn = bufn;
2008:   }
2009:   for (i = 0; i < m; i++) {
2010:     for (j = 0; j < 3 - sdim; j++) dxm++;
2011:     tmp = *dxm++ - starts[0];
2012:     for (j = 0; j < sdim - 1; j++) {
2013:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
2014:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
2015:     }
2016:     dxm++;
2017:     jdxm[i] = tmp;
2018:   }
2019:   for (i = 0; i < n; i++) {
2020:     for (j = 0; j < 3 - sdim; j++) dxn++;
2021:     tmp = *dxn++ - starts[0];
2022:     for (j = 0; j < sdim - 1; j++) {
2023:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
2024:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
2025:     }
2026:     dxn++;
2027:     jdxn[i] = tmp;
2028:   }
2029:   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
2030:   PetscCall(PetscFree2(bufm, bufn));
2031:   PetscFunctionReturn(PETSC_SUCCESS);
2032: }

2034: /*@
2035:   MatSetStencil - Sets the grid information for setting values into a matrix via
2036:   `MatSetValuesStencil()`

2038:   Not Collective

2040:   Input Parameters:
2041: + mat    - the matrix
2042: . dim    - dimension of the grid 1, 2, or 3
2043: . dims   - number of grid points in x, y, and z direction, including ghost points on your process
2044: . starts - starting point of ghost nodes on your process in x, y, and z direction
2045: - dof    - number of degrees of freedom per node

2047:   Level: beginner

2049:   Notes:
2050:   Inspired by the structured grid interface to the HYPRE package
2051:   (www.llnl.gov/CASC/hyper)

2053:   For matrices generated with `DMCreateMatrix()` this routine is automatically called and so not needed by the
2054:   user.

2056: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2057:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
2058: @*/
2059: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
2060: {
2061:   PetscFunctionBegin;
2063:   PetscAssertPointer(dims, 3);
2064:   PetscAssertPointer(starts, 4);

2066:   mat->stencil.dim = dim + (dof > 1);
2067:   for (PetscInt i = 0; i < dim; i++) {
2068:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
2069:     mat->stencil.starts[i] = starts[dim - i - 1];
2070:   }
2071:   mat->stencil.dims[dim]   = dof;
2072:   mat->stencil.starts[dim] = 0;
2073:   mat->stencil.noc         = (PetscBool)(dof == 1);
2074:   PetscFunctionReturn(PETSC_SUCCESS);
2075: }

2077: /*@
2078:   MatSetValuesBlocked - Inserts or adds a block of values into a matrix.

2080:   Not Collective

2082:   Input Parameters:
2083: + mat  - the matrix
2084: . m    - the number of block rows
2085: . idxm - the global block indices
2086: . n    - the number of block columns
2087: . idxn - the global block indices
2088: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2089:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2090: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

2092:   Level: intermediate

2094:   Notes:
2095:   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call
2096:   MatXXXXSetPreallocation() or `MatSetUp()` before using this routine.

2098:   The `m` and `n` count the NUMBER of blocks in the row direction and column direction,
2099:   NOT the total number of rows/columns; for example, if the block size is 2 and
2100:   you are passing in values for rows 2,3,4,5  then `m` would be 2 (not 4).
2101:   The values in `idxm` would be 1 2; that is the first index for each block divided by
2102:   the block size.

2104:   You must call `MatSetBlockSize()` when constructing this matrix (before
2105:   preallocating it).

2107:   By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

2109:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2110:   options cannot be mixed without intervening calls to the assembly
2111:   routines.

2113:   `MatSetValuesBlocked()` uses 0-based row and column numbers in Fortran
2114:   as well as in C.

2116:   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
2117:   simply ignored. This allows easily inserting element stiffness matrices
2118:   with homogeneous Dirichlet boundary conditions that you don't want represented
2119:   in the matrix.

2121:   Each time an entry is set within a sparse matrix via `MatSetValues()`,
2122:   internal searching must be done to determine where to place the
2123:   data in the matrix storage space. By instead inserting blocks of
2124:   entries via `MatSetValuesBlocked()`, the overhead of matrix assembly is
2125:   reduced.

2127:   Example:
2128: .vb
2129:    Suppose m=n=2 and block size(bs) = 2 The array is

2131:    1  2  | 3  4
2132:    5  6  | 7  8
2133:    - - - | - - -
2134:    9  10 | 11 12
2135:    13 14 | 15 16

2137:    v[] should be passed in like
2138:    v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

2140:   If you are not using row-oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
2141:    v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
2142: .ve

2144:   Fortran Notes:
2145:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2146: .vb
2147:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2148: .ve

2150:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2151:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

2153: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2154: @*/
2155: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2156: {
2157:   PetscFunctionBeginHot;
2160:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2161:   PetscAssertPointer(idxm, 3);
2162:   PetscAssertPointer(idxn, 5);
2163:   MatCheckPreallocated(mat, 1);
2164:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2165:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2166:   if (PetscDefined(USE_DEBUG)) {
2167:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2168:     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2169:   }
2170:   if (PetscDefined(USE_DEBUG)) {
2171:     PetscInt rbs, cbs, M, N, i;
2172:     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2173:     PetscCall(MatGetSize(mat, &M, &N));
2174:     for (i = 0; i < m; i++) PetscCheck(idxm[i] * rbs < M, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Row block %" PetscInt_FMT " contains an index %" PetscInt_FMT "*%" PetscInt_FMT " greater than row length %" PetscInt_FMT, i, idxm[i], rbs, M);
2175:     for (i = 0; i < n; i++)
2176:       PetscCheck(idxn[i] * cbs < N, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Column block %" PetscInt_FMT " contains an index %" PetscInt_FMT "*%" PetscInt_FMT " greater than column length %" PetscInt_FMT, i, idxn[i], cbs, N);
2177:   }
2178:   if (mat->assembled) {
2179:     mat->was_assembled = PETSC_TRUE;
2180:     mat->assembled     = PETSC_FALSE;
2181:   }
2182:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2183:   if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2184:   else {
2185:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2186:     PetscInt i, j, bs, cbs;

2188:     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2189:     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2190:       iidxm = buf;
2191:       iidxn = buf + m * bs;
2192:     } else {
2193:       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2194:       iidxm = bufr;
2195:       iidxn = bufc;
2196:     }
2197:     for (i = 0; i < m; i++) {
2198:       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2199:     }
2200:     if (m != n || bs != cbs || idxm != idxn) {
2201:       for (i = 0; i < n; i++) {
2202:         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2203:       }
2204:     } else iidxn = iidxm;
2205:     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2206:     PetscCall(PetscFree2(bufr, bufc));
2207:   }
2208:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2209:   PetscFunctionReturn(PETSC_SUCCESS);
2210: }

2212: /*@
2213:   MatGetValues - Gets a block of local values from a matrix.

2215:   Not Collective; can only return values that are owned by the give process

2217:   Input Parameters:
2218: + mat  - the matrix
2219: . v    - a logically two-dimensional array for storing the values
2220: . m    - the number of rows
2221: . idxm - the  global indices of the rows
2222: . n    - the number of columns
2223: - idxn - the global indices of the columns

2225:   Level: advanced

2227:   Notes:
2228:   The user must allocate space (m*n `PetscScalar`s) for the values, `v`.

2230:   The values, `v`, are returned in a row-oriented format, analogous to that used by default in `MatSetValues()`,
2231:   unless `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE)` is called in which case they are returned column oriented.

2233:   `MatGetValues()` uses 0-based row and column numbers in
2234:   Fortran as well as in C.

2236:   For `MATSBAIJ` matrices only the block upper triangular entries will be set.

2238:   `MatGetValues()` requires that the matrix has been assembled
2239:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`. Thus, calls to
2240:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2241:   without intermediate matrix assembly.

2243:   Negative row or column indices will be ignored and those locations in `v` will be
2244:   left unchanged.

2246:   For the standard row-based matrix formats, `idxm` can only contain rows owned by the requesting MPI process.
2247:   That is, rows with global index greater than or equal to `rstart` and less than `rend` where `rstart` and `rend` are obtainable
2248:   from `MatGetOwnershipRange`(mat,&rstart,&rend).

2250: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2251: @*/
2252: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2253: {
2254:   PetscFunctionBegin;
2257:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2258:   PetscAssertPointer(idxm, 3);
2259:   PetscAssertPointer(idxn, 5);
2260:   PetscAssertPointer(v, 6);
2261:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2262:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2263:   MatCheckPreallocated(mat, 1);

2265:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2266:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2267:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2268:   PetscFunctionReturn(PETSC_SUCCESS);
2269: }

2271: /*@
2272:   MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
2273:   defined previously by `MatSetLocalToGlobalMapping()`

2275:   Not Collective

2277:   Input Parameters:
2278: + mat  - the matrix
2279: . nrow - number of rows
2280: . irow - the row local indices
2281: . ncol - number of columns
2282: - icol - the column local indices

2284:   Output Parameter:
2285: . y - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2286:       See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

2288:   Level: advanced

2290:   Notes:
2291:   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine.

2293:   This routine can only return values that are owned by the requesting MPI process. That is, for standard matrix formats, rows that, in the global numbering,
2294:   are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2295:   determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2296:   with `MatSetLocalToGlobalMapping()`.

2298: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2299:           `MatSetValuesLocal()`, `MatGetValues()`
2300: @*/
2301: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2302: {
2303:   PetscFunctionBeginHot;
2306:   MatCheckPreallocated(mat, 1);
2307:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2308:   PetscAssertPointer(irow, 3);
2309:   PetscAssertPointer(icol, 5);
2310:   if (PetscDefined(USE_DEBUG)) {
2311:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2312:     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2313:   }
2314:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2315:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2316:   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2317:   else {
2318:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2319:     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2320:       irowm = buf;
2321:       icolm = buf + nrow;
2322:     } else {
2323:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2324:       irowm = bufr;
2325:       icolm = bufc;
2326:     }
2327:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2328:     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2329:     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2330:     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2331:     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2332:     PetscCall(PetscFree2(bufr, bufc));
2333:   }
2334:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2335:   PetscFunctionReturn(PETSC_SUCCESS);
2336: }

2338: /*@
2339:   MatSetValuesBatch - Adds (`ADD_VALUES`) many blocks of values into a matrix at once. The blocks must all be square and
2340:   the same size. Currently, this can only be called once and creates the given matrix.

2342:   Not Collective

2344:   Input Parameters:
2345: + mat  - the matrix
2346: . nb   - the number of blocks
2347: . bs   - the number of rows (and columns) in each block
2348: . rows - a concatenation of the rows for each block
2349: - v    - a concatenation of logically two-dimensional arrays of values

2351:   Level: advanced

2353:   Notes:
2354:   `MatSetPreallocationCOO()` and `MatSetValuesCOO()` may be a better way to provide the values

2356:   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.

2358: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2359:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2360: @*/
2361: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2362: {
2363:   PetscFunctionBegin;
2366:   PetscAssertPointer(rows, 4);
2367:   PetscAssertPointer(v, 5);
2368:   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

2370:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2371:   for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2372:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2373:   PetscFunctionReturn(PETSC_SUCCESS);
2374: }

2376: /*@
2377:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2378:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2379:   using a local (per-process) numbering.

2381:   Not Collective

2383:   Input Parameters:
2384: + x        - the matrix
2385: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2386: - cmapping - column mapping

2388:   Level: intermediate

2390:   Note:
2391:   If the matrix is obtained with `DMCreateMatrix()` then this may already have been called on the matrix

2393: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2394: @*/
2395: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2396: {
2397:   PetscFunctionBegin;
2402:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2403:   else {
2404:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2405:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2406:   }
2407:   PetscFunctionReturn(PETSC_SUCCESS);
2408: }

2410: /*@
2411:   MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by `MatSetLocalToGlobalMapping()`

2413:   Not Collective

2415:   Input Parameter:
2416: . A - the matrix

2418:   Output Parameters:
2419: + rmapping - row mapping
2420: - cmapping - column mapping

2422:   Level: advanced

2424: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2425: @*/
2426: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2427: {
2428:   PetscFunctionBegin;
2431:   if (rmapping) {
2432:     PetscAssertPointer(rmapping, 2);
2433:     *rmapping = A->rmap->mapping;
2434:   }
2435:   if (cmapping) {
2436:     PetscAssertPointer(cmapping, 3);
2437:     *cmapping = A->cmap->mapping;
2438:   }
2439:   PetscFunctionReturn(PETSC_SUCCESS);
2440: }

2442: /*@
2443:   MatSetLayouts - Sets the `PetscLayout` objects for rows and columns of a matrix

2445:   Logically Collective

2447:   Input Parameters:
2448: + A    - the matrix
2449: . rmap - row layout
2450: - cmap - column layout

2452:   Level: advanced

2454:   Note:
2455:   The `PetscLayout` objects are usually created automatically for the matrix so this routine rarely needs to be called.

2457: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2458: @*/
2459: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2460: {
2461:   PetscFunctionBegin;
2463:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2464:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2465:   PetscFunctionReturn(PETSC_SUCCESS);
2466: }

2468: /*@
2469:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2471:   Not Collective

2473:   Input Parameter:
2474: . A - the matrix

2476:   Output Parameters:
2477: + rmap - row layout
2478: - cmap - column layout

2480:   Level: advanced

2482: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2483: @*/
2484: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2485: {
2486:   PetscFunctionBegin;
2489:   if (rmap) {
2490:     PetscAssertPointer(rmap, 2);
2491:     *rmap = A->rmap;
2492:   }
2493:   if (cmap) {
2494:     PetscAssertPointer(cmap, 3);
2495:     *cmap = A->cmap;
2496:   }
2497:   PetscFunctionReturn(PETSC_SUCCESS);
2498: }

2500: /*@
2501:   MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2502:   using a local numbering of the rows and columns.

2504:   Not Collective

2506:   Input Parameters:
2507: + mat  - the matrix
2508: . nrow - number of rows
2509: . irow - the row local indices
2510: . ncol - number of columns
2511: . icol - the column local indices
2512: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2513:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2514: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2516:   Level: intermediate

2518:   Notes:
2519:   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine

2521:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2522:   options cannot be mixed without intervening calls to the assembly
2523:   routines.

2525:   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2526:   MUST be called after all calls to `MatSetValuesLocal()` have been completed.

2528:   Fortran Notes:
2529:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2530: .vb
2531:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2532: .ve

2534:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2535:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

2537: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2538:           `MatGetValuesLocal()`
2539: @*/
2540: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2541: {
2542:   PetscFunctionBeginHot;
2545:   MatCheckPreallocated(mat, 1);
2546:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2547:   PetscAssertPointer(irow, 3);
2548:   PetscAssertPointer(icol, 5);
2549:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2550:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2551:   if (PetscDefined(USE_DEBUG)) {
2552:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2553:     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2554:   }

2556:   if (mat->assembled) {
2557:     mat->was_assembled = PETSC_TRUE;
2558:     mat->assembled     = PETSC_FALSE;
2559:   }
2560:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2561:   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, v, addv);
2562:   else {
2563:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2564:     const PetscInt *irowm, *icolm;

2566:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2567:       bufr  = buf;
2568:       bufc  = buf + nrow;
2569:       irowm = bufr;
2570:       icolm = bufc;
2571:     } else {
2572:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2573:       irowm = bufr;
2574:       icolm = bufc;
2575:     }
2576:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2577:     else irowm = irow;
2578:     if (mat->cmap->mapping) {
2579:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2580:       else icolm = irowm;
2581:     } else icolm = icol;
2582:     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, v, addv));
2583:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2584:   }
2585:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2586:   PetscFunctionReturn(PETSC_SUCCESS);
2587: }

2589: /*@
2590:   MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2591:   using a local ordering of the nodes a block at a time.

2593:   Not Collective

2595:   Input Parameters:
2596: + mat  - the matrix
2597: . nrow - number of rows
2598: . irow - the row local indices
2599: . ncol - number of columns
2600: . icol - the column local indices
2601: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2602:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2603: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2605:   Level: intermediate

2607:   Notes:
2608:   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetBlockSize()` and `MatSetLocalToGlobalMapping()`
2609:   before using this routineBefore calling `MatSetValuesLocal()`, the user must first set the

2611:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2612:   options cannot be mixed without intervening calls to the assembly
2613:   routines.

2615:   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2616:   MUST be called after all calls to `MatSetValuesBlockedLocal()` have been completed.

2618:   Fortran Notes:
2619:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2620: .vb
2621:   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2622: .ve

2624:   If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2625:   otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.

2627: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2628:           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2629: @*/
2630: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2631: {
2632:   PetscFunctionBeginHot;
2635:   MatCheckPreallocated(mat, 1);
2636:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2637:   PetscAssertPointer(irow, 3);
2638:   PetscAssertPointer(icol, 5);
2639:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2640:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2641:   if (PetscDefined(USE_DEBUG)) {
2642:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2643:     PetscCheck(mat->ops->setvaluesblockedlocal || mat->ops->setvaluesblocked || mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2644:   }

2646:   if (mat->assembled) {
2647:     mat->was_assembled = PETSC_TRUE;
2648:     mat->assembled     = PETSC_FALSE;
2649:   }
2650:   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2651:     PetscInt irbs, rbs;
2652:     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2653:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2654:     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2655:   }
2656:   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2657:     PetscInt icbs, cbs;
2658:     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2659:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2660:     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2661:   }
2662:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2663:   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, v, addv);
2664:   else {
2665:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2666:     const PetscInt *irowm, *icolm;

2668:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2669:       bufr  = buf;
2670:       bufc  = buf + nrow;
2671:       irowm = bufr;
2672:       icolm = bufc;
2673:     } else {
2674:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2675:       irowm = bufr;
2676:       icolm = bufc;
2677:     }
2678:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2679:     else irowm = irow;
2680:     if (mat->cmap->mapping) {
2681:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2682:       else icolm = irowm;
2683:     } else icolm = icol;
2684:     PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, v, addv));
2685:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2686:   }
2687:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2688:   PetscFunctionReturn(PETSC_SUCCESS);
2689: }

2691: /*@
2692:   MatMultDiagonalBlock - Computes the matrix-vector product, $y = Dx$. Where `D` is defined by the inode or block structure of the diagonal

2694:   Collective

2696:   Input Parameters:
2697: + mat - the matrix
2698: - x   - the vector to be multiplied

2700:   Output Parameter:
2701: . y - the result

2703:   Level: developer

2705:   Note:
2706:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2707:   call `MatMultDiagonalBlock`(A,y,y).

2709: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2710: @*/
2711: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2712: {
2713:   PetscFunctionBegin;

2719:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2720:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2721:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2722:   MatCheckPreallocated(mat, 1);

2724:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2725:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2726:   PetscFunctionReturn(PETSC_SUCCESS);
2727: }

2729: /*@
2730:   MatMult - Computes the matrix-vector product, $y = Ax$.

2732:   Neighbor-wise Collective

2734:   Input Parameters:
2735: + mat - the matrix
2736: - x   - the vector to be multiplied

2738:   Output Parameter:
2739: . y - the result

2741:   Level: beginner

2743:   Note:
2744:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2745:   call `MatMult`(A,y,y).

2747: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2748: @*/
2749: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2750: {
2751:   PetscFunctionBegin;
2755:   VecCheckAssembled(x);
2757:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2758:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2759:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2760:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
2761:   PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
2762:   PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
2763:   PetscCheck(mat->rmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, y->map->n);
2764:   PetscCall(VecSetErrorIfLocked(y, 3));
2765:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2766:   MatCheckPreallocated(mat, 1);

2768:   PetscCall(VecLockReadPush(x));
2769:   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2770:   PetscUseTypeMethod(mat, mult, x, y);
2771:   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2772:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2773:   PetscCall(VecLockReadPop(x));
2774:   PetscFunctionReturn(PETSC_SUCCESS);
2775: }

2777: /*@
2778:   MatMultTranspose - Computes matrix transpose times a vector $y = A^T * x$.

2780:   Neighbor-wise Collective

2782:   Input Parameters:
2783: + mat - the matrix
2784: - x   - the vector to be multiplied

2786:   Output Parameter:
2787: . y - the result

2789:   Level: beginner

2791:   Notes:
2792:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2793:   call `MatMultTranspose`(A,y,y).

2795:   For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2796:   use `MatMultHermitianTranspose()`

2798: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2799: @*/
2800: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2801: {
2802:   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;

2804:   PetscFunctionBegin;
2808:   VecCheckAssembled(x);

2811:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2812:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2813:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2814:   PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
2815:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
2816:   PetscCheck(mat->cmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, y->map->n);
2817:   PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
2818:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2819:   MatCheckPreallocated(mat, 1);

2821:   if (!mat->ops->multtranspose) {
2822:     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2823:     PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined", ((PetscObject)mat)->type_name);
2824:   } else op = mat->ops->multtranspose;
2825:   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2826:   PetscCall(VecLockReadPush(x));
2827:   PetscCall((*op)(mat, x, y));
2828:   PetscCall(VecLockReadPop(x));
2829:   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2830:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2831:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2832:   PetscFunctionReturn(PETSC_SUCCESS);
2833: }

2835: /*@
2836:   MatMultHermitianTranspose - Computes matrix Hermitian-transpose times a vector $y = A^H * x$.

2838:   Neighbor-wise Collective

2840:   Input Parameters:
2841: + mat - the matrix
2842: - x   - the vector to be multiplied

2844:   Output Parameter:
2845: . y - the result

2847:   Level: beginner

2849:   Notes:
2850:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2851:   call `MatMultHermitianTranspose`(A,y,y).

2853:   Also called the conjugate transpose, complex conjugate transpose, or adjoint.

2855:   For real numbers `MatMultTranspose()` and `MatMultHermitianTranspose()` are identical.

2857: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2858: @*/
2859: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2860: {
2861:   PetscFunctionBegin;

2867:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2868:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2869:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2870:   PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
2871:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
2872:   PetscCheck(mat->cmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, y->map->n);
2873:   PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
2874:   MatCheckPreallocated(mat, 1);

2876:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2877:   if (PetscDefined(USE_COMPLEX)) {
2878:     if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2879:       PetscCall(VecLockReadPush(x));
2880:       if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2881:       else PetscUseTypeMethod(mat, mult, x, y);
2882:       PetscCall(VecLockReadPop(x));
2883:     } else {
2884:       Vec w;
2885:       PetscCall(VecDuplicate(x, &w));
2886:       PetscCall(VecCopy(x, w));
2887:       PetscCall(VecConjugate(w));
2888:       PetscCall(MatMultTranspose(mat, w, y));
2889:       PetscCall(VecDestroy(&w));
2890:       PetscCall(VecConjugate(y));
2891:     }
2892:     PetscCall(PetscObjectStateIncrease((PetscObject)y));
2893:   } else PetscCall(MatMultTranspose(mat, x, y));
2894:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2895:   PetscFunctionReturn(PETSC_SUCCESS);
2896: }

2898: /*@
2899:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2901:   Neighbor-wise Collective

2903:   Input Parameters:
2904: + mat - the matrix
2905: . v1  - the vector to be multiplied by `mat`
2906: - v2  - the vector to be added to the result

2908:   Output Parameter:
2909: . v3 - the result

2911:   Level: beginner

2913:   Note:
2914:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2915:   call `MatMultAdd`(A,v1,v2,v1).

2917: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2918: @*/
2919: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2920: {
2921:   PetscFunctionBegin;

2928:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2929:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2930:   PetscCheck(mat->cmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v1->map->N);
2931:   /* PetscCheck(mat->rmap->N == v2->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v2->map->N);
2932:      PetscCheck(mat->rmap->N == v3->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v3->map->N); */
2933:   PetscCheck(mat->rmap->n == v3->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v3->map->n);
2934:   PetscCheck(mat->rmap->n == v2->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v2->map->n);
2935:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2936:   MatCheckPreallocated(mat, 1);

2938:   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2939:   PetscCall(VecLockReadPush(v1));
2940:   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2941:   PetscCall(VecLockReadPop(v1));
2942:   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2943:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2944:   PetscFunctionReturn(PETSC_SUCCESS);
2945: }

2947: /*@
2948:   MatMultTransposeAdd - Computes $v3 = v2 + A^T * v1$.

2950:   Neighbor-wise Collective

2952:   Input Parameters:
2953: + mat - the matrix
2954: . v1  - the vector to be multiplied by the transpose of the matrix
2955: - v2  - the vector to be added to the result

2957:   Output Parameter:
2958: . v3 - the result

2960:   Level: beginner

2962:   Note:
2963:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2964:   call `MatMultTransposeAdd`(A,v1,v2,v1).

2966: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2967: @*/
2968: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2969: {
2970:   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;

2972:   PetscFunctionBegin;

2979:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2980:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2981:   PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2982:   PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2983:   PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2984:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2985:   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2986:   MatCheckPreallocated(mat, 1);

2988:   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2989:   PetscCall(VecLockReadPush(v1));
2990:   PetscCall((*op)(mat, v1, v2, v3));
2991:   PetscCall(VecLockReadPop(v1));
2992:   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2993:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2994:   PetscFunctionReturn(PETSC_SUCCESS);
2995: }

2997: /*@
2998:   MatMultHermitianTransposeAdd - Computes $v3 = v2 + A^H * v1$.

3000:   Neighbor-wise Collective

3002:   Input Parameters:
3003: + mat - the matrix
3004: . v1  - the vector to be multiplied by the Hermitian transpose
3005: - v2  - the vector to be added to the result

3007:   Output Parameter:
3008: . v3 - the result

3010:   Level: beginner

3012:   Note:
3013:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
3014:   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).

3016: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
3017: @*/
3018: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
3019: {
3020:   PetscFunctionBegin;

3027:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3028:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3029:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
3030:   PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
3031:   PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
3032:   PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
3033:   MatCheckPreallocated(mat, 1);

3035:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3036:   PetscCall(VecLockReadPush(v1));
3037:   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
3038:   else {
3039:     Vec w, z;
3040:     PetscCall(VecDuplicate(v1, &w));
3041:     PetscCall(VecCopy(v1, w));
3042:     PetscCall(VecConjugate(w));
3043:     PetscCall(VecDuplicate(v3, &z));
3044:     PetscCall(MatMultTranspose(mat, w, z));
3045:     PetscCall(VecDestroy(&w));
3046:     PetscCall(VecConjugate(z));
3047:     if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
3048:     else PetscCall(VecAXPY(v3, 1.0, z));
3049:     PetscCall(VecDestroy(&z));
3050:   }
3051:   PetscCall(VecLockReadPop(v1));
3052:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3053:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3054:   PetscFunctionReturn(PETSC_SUCCESS);
3055: }

3057: static PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
3058: {
3059:   PetscFunctionBegin;
3060:   if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, NULL, &mat->dot_vec));
3061:   PetscCall(MatMult(mat, x, mat->dot_vec));
3062:   PetscCall(VecDot(mat->dot_vec, y, val));
3063:   PetscFunctionReturn(PETSC_SUCCESS);
3064: }

3066: static PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
3067: {
3068:   PetscScalar sval;

3070:   PetscFunctionBegin;
3071:   PetscCall(MatADot(mat, x, x, &sval));
3072:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3073:   PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) <= 100 * PETSC_MACHINE_EPSILON * PetscMax(1.0, PetscAbsScalar(sval)), PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
3074:   *val = PetscSqrtReal(PetscRealPart(sval));
3075:   PetscFunctionReturn(PETSC_SUCCESS);
3076: }

3078: /*@
3079:   MatADot - Computes the inner product with respect to a matrix, i.e., $(x, y)_A = y^H A x$ where $A$ is symmetric (Hermitian when using complex)
3080:   positive definite.

3082:   Collective

3084:   Input Parameters:
3085: + mat - matrix used to define the inner product
3086: . x   - first vector
3087: - y   - second vector

3089:   Output Parameter:
3090: . val - the dot product with respect to `A`

3092:   Level: intermediate

3094:   Note:
3095:   For complex vectors, `MatADot()` computes
3096: $$
3097:   val = (x,y)_A = y^H A x,
3098: $$
3099:   where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3100:   inner product where the SECOND argument gets the complex conjugate.

3102: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3103: @*/
3104: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3105: {
3106:   PetscFunctionBegin;
3110:   VecCheckAssembled(x);
3112:   VecCheckAssembled(y);
3115:   PetscAssertPointer(val, 4);
3116:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3117:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3118:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3119:   PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
3120:   PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
3121:   PetscCheck(mat->rmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, y->map->n);
3122:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3123:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3124:   MatCheckPreallocated(mat, 1);

3126:   PetscCall(VecLockReadPush(x));
3127:   PetscCall(VecLockReadPush(y));
3128:   PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3129:   if (mat->ops->adot) PetscUseTypeMethod(mat, adot, x, y, val);
3130:   else PetscCall(MatADot_Default(mat, x, y, val));
3131:   PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3132:   PetscCall(VecLockReadPop(y));
3133:   PetscCall(VecLockReadPop(x));
3134:   PetscFunctionReturn(PETSC_SUCCESS);
3135: }

3137: /*@
3138:   MatANorm - Computes the norm with respect to a matrix, i.e., $(x, x)_A^{1/2} = (x^H A x)^{1/2}$ where $A$ is symmetric (Hermitian when using complex)
3139:   positive definite.

3141:   Collective

3143:   Input Parameters:
3144: + mat - matrix used to define norm
3145: - x   - the vector to compute the norm of

3147:   Output Parameter:
3148: . val - the norm with respect to `A`

3150:   Level: intermediate

3152:   Note:
3153:   For complex vectors, `MatANorm()` computes
3154: $$
3155:   val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3156: $$
3157:   where $x^H$ denotes the conjugate transpose of `x`.

3159: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3160: @*/
3161: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3162: {
3163:   PetscFunctionBegin;
3167:   VecCheckAssembled(x);
3169:   PetscAssertPointer(val, 3);
3170:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3171:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3172:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3173:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
3174:   PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
3175:   PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
3176:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3177:   MatCheckPreallocated(mat, 1);

3179:   PetscCall(VecLockReadPush(x));
3180:   PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3181:   if (mat->ops->anorm) PetscUseTypeMethod(mat, anorm, x, val);
3182:   else PetscCall(MatANorm_Default(mat, x, val));
3183:   PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3184:   PetscCall(VecLockReadPop(x));
3185:   PetscFunctionReturn(PETSC_SUCCESS);
3186: }

3188: /*@
3189:   MatGetFactorType - gets the type of factorization a matrix is

3191:   Not Collective

3193:   Input Parameter:
3194: . mat - the matrix

3196:   Output Parameter:
3197: . t - the type, one of `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`, `MAT_FACTOR_ICC,MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`

3199:   Level: intermediate

3201: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3202:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3203: @*/
3204: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3205: {
3206:   PetscFunctionBegin;
3209:   PetscAssertPointer(t, 2);
3210:   *t = mat->factortype;
3211:   PetscFunctionReturn(PETSC_SUCCESS);
3212: }

3214: /*@
3215:   MatSetFactorType - sets the type of factorization a matrix is

3217:   Logically Collective

3219:   Input Parameters:
3220: + mat - the matrix
3221: - t   - the type, one of `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`, `MAT_FACTOR_ICC,MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`

3223:   Level: intermediate

3225: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3226:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3227: @*/
3228: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3229: {
3230:   PetscFunctionBegin;
3233:   mat->factortype = t;
3234:   PetscFunctionReturn(PETSC_SUCCESS);
3235: }

3237: /*@
3238:   MatGetInfo - Returns information about matrix storage (number of
3239:   nonzeros, memory, etc.).

3241:   Collective if `MAT_GLOBAL_MAX` or `MAT_GLOBAL_SUM` is used as the flag

3243:   Input Parameters:
3244: + mat  - the matrix
3245: - flag - flag indicating the type of parameters to be returned (`MAT_LOCAL` - local matrix, `MAT_GLOBAL_MAX` - maximum over all processes, `MAT_GLOBAL_SUM` - sum over all processes)

3247:   Output Parameter:
3248: . info - matrix information context

3250:   Options Database Key:
3251: . -mat_view :[filename]:ascii_info - print the matrix information to `filename` or `stdout`, see `MatView()`

3253:   Level: intermediate

3255:   Notes:
3256:   The `MatInfo` context contains a variety of matrix data, including
3257:   number of nonzeros allocated and used, number of mallocs during
3258:   matrix assembly, etc. Additional information for factored matrices
3259:   is provided (such as the fill ratio, number of mallocs during
3260:   factorization, etc.).

3262:   Example:
3263:   See the file `${PETSC_DIR}/include/petscmat.h` for a complete list of
3264:   data within the `MatInfo` context.  For example,
3265: .vb
3266:       MatInfo info;
3267:       Mat     A;
3268:       double  mal, nz_a, nz_u;

3270:       MatGetInfo(A, MAT_LOCAL, &info);
3271:       mal  = info.mallocs;
3272:       nz_a = info.nz_allocated;
3273: .ve

3275: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3276: @*/
3277: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3278: {
3279:   PetscFunctionBegin;
3282:   PetscAssertPointer(info, 3);
3283:   MatCheckPreallocated(mat, 1);
3284:   PetscUseTypeMethod(mat, getinfo, flag, info);
3285:   PetscFunctionReturn(PETSC_SUCCESS);
3286: }

3288: /*
3289:    This is used by external packages where it is not easy to get the info from the actual
3290:    matrix factorization.
3291: */
3292: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3293: {
3294:   PetscFunctionBegin;
3295:   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3296:   PetscFunctionReturn(PETSC_SUCCESS);
3297: }

3299: /*@
3300:   MatLUFactor - Performs in-place LU factorization of matrix.

3302:   Collective

3304:   Input Parameters:
3305: + mat  - the matrix
3306: . row  - row permutation
3307: . col  - column permutation
3308: - info - options for factorization, includes
3309: .vb
3310:           fill - expected fill as ratio of original fill.
3311:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3312:                    Run with the option -info to determine an optimal value to use
3313: .ve

3315:   Level: developer

3317:   Notes:
3318:   Most users should employ the `KSP` interface for linear solvers
3319:   instead of working directly with matrix algebra routines such as this.
3320:   See, e.g., `KSPCreate()`.

3322:   This changes the state of the matrix to a factored matrix; it cannot be used
3323:   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.

3325:   This is really in-place only for dense matrices, the preferred approach is to use `MatGetFactor()`, `MatLUFactorSymbolic()`, and `MatLUFactorNumeric()`
3326:   when not using `KSP`.

3328:   Fortran Note:
3329:   A valid (non-null) `info` argument must be provided

3331: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3332:           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3333: @*/
3334: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3335: {
3336:   MatFactorInfo tinfo;

3338:   PetscFunctionBegin;
3342:   if (info) PetscAssertPointer(info, 4);
3344:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3345:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3346:   MatCheckPreallocated(mat, 1);
3347:   if (!info) {
3348:     PetscCall(MatFactorInfoInitialize(&tinfo));
3349:     info = &tinfo;
3350:   }

3352:   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3353:   PetscUseTypeMethod(mat, lufactor, row, col, info);
3354:   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3355:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3356:   PetscFunctionReturn(PETSC_SUCCESS);
3357: }

3359: /*@
3360:   MatILUFactor - Performs in-place ILU factorization of matrix.

3362:   Collective

3364:   Input Parameters:
3365: + mat  - the matrix
3366: . row  - row permutation
3367: . col  - column permutation
3368: - info - structure containing
3369: .vb
3370:       levels - number of levels of fill.
3371:       expected fill - as ratio of original fill.
3372:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3373:                 missing diagonal entries)
3374: .ve

3376:   Level: developer

3378:   Notes:
3379:   Most users should employ the `KSP` interface for linear solvers
3380:   instead of working directly with matrix algebra routines such as this.
3381:   See, e.g., `KSPCreate()`.

3383:   Probably really in-place only when level of fill is zero, otherwise allocates
3384:   new space to store factored matrix and deletes previous memory. The preferred approach is to use `MatGetFactor()`, `MatILUFactorSymbolic()`, and `MatLUFactorNumeric()`
3385:   when not using `KSP`.

3387:   Fortran Note:
3388:   A valid (non-null) `info` argument must be provided

3390: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3391: @*/
3392: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3393: {
3394:   PetscFunctionBegin;
3398:   PetscAssertPointer(info, 4);
3400:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3401:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3402:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3403:   MatCheckPreallocated(mat, 1);

3405:   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3406:   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3407:   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3408:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3409:   PetscFunctionReturn(PETSC_SUCCESS);
3410: }

3412: /*@
3413:   MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3414:   Call this routine before calling `MatLUFactorNumeric()` and after `MatGetFactor()`.

3416:   Collective

3418:   Input Parameters:
3419: + fact - the factor matrix obtained with `MatGetFactor()`
3420: . mat  - the matrix
3421: . row  - the row permutation
3422: . col  - the column permutation
3423: - info - options for factorization, includes
3424: .vb
3425:           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3426:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3427: .ve

3429:   Level: developer

3431:   Notes:
3432:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

3434:   Most users should employ the simplified `KSP` interface for linear solvers
3435:   instead of working directly with matrix algebra routines such as this.
3436:   See, e.g., `KSPCreate()`.

3438:   Fortran Note:
3439:   A valid (non-null) `info` argument must be provided

3441: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3442: @*/
3443: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3444: {
3445:   MatFactorInfo tinfo;

3447:   PetscFunctionBegin;
3452:   if (info) PetscAssertPointer(info, 5);
3455:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3456:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3457:   MatCheckPreallocated(mat, 2);
3458:   if (!info) {
3459:     PetscCall(MatFactorInfoInitialize(&tinfo));
3460:     info = &tinfo;
3461:   }

3463:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3464:   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3465:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3466:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3467:   PetscFunctionReturn(PETSC_SUCCESS);
3468: }

3470: /*@
3471:   MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3472:   Call this routine after first calling `MatLUFactorSymbolic()` and `MatGetFactor()`.

3474:   Collective

3476:   Input Parameters:
3477: + fact - the factor matrix obtained with `MatGetFactor()`
3478: . mat  - the matrix
3479: - info - options for factorization

3481:   Level: developer

3483:   Notes:
3484:   See `MatLUFactor()` for in-place factorization. See
3485:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

3487:   Most users should employ the `KSP` interface for linear solvers
3488:   instead of working directly with matrix algebra routines such as this.
3489:   See, e.g., `KSPCreate()`.

3491:   Fortran Note:
3492:   A valid (non-null) `info` argument must be provided

3494: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3495: @*/
3496: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3497: {
3498:   MatFactorInfo tinfo;

3500:   PetscFunctionBegin;
3505:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3506:   PetscCheck(mat->rmap->N == (fact)->rmap->N && mat->cmap->N == (fact)->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dimensions are different %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3507:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3509:   MatCheckPreallocated(mat, 2);
3510:   if (!info) {
3511:     PetscCall(MatFactorInfoInitialize(&tinfo));
3512:     info = &tinfo;
3513:   }

3515:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3516:   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3517:   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3518:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3519:   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3520:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3521:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3522:   PetscFunctionReturn(PETSC_SUCCESS);
3523: }

3525: /*@
3526:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3527:   symmetric matrix.

3529:   Collective

3531:   Input Parameters:
3532: + mat  - the matrix
3533: . perm - row and column permutations
3534: - info - expected fill as ratio of original fill

3536:   Level: developer

3538:   Notes:
3539:   See `MatLUFactor()` for the nonsymmetric case. See also `MatGetFactor()`,
3540:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

3542:   Most users should employ the `KSP` interface for linear solvers
3543:   instead of working directly with matrix algebra routines such as this.
3544:   See, e.g., `KSPCreate()`.

3546:   Fortran Note:
3547:   A valid (non-null) `info` argument must be provided

3549: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3550:           `MatGetOrdering()`
3551: @*/
3552: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3553: {
3554:   MatFactorInfo tinfo;

3556:   PetscFunctionBegin;
3559:   if (info) PetscAssertPointer(info, 3);
3561:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3562:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3563:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3564:   MatCheckPreallocated(mat, 1);
3565:   if (!info) {
3566:     PetscCall(MatFactorInfoInitialize(&tinfo));
3567:     info = &tinfo;
3568:   }

3570:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3571:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3572:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3573:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3574:   PetscFunctionReturn(PETSC_SUCCESS);
3575: }

3577: /*@
3578:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3579:   of a symmetric matrix.

3581:   Collective

3583:   Input Parameters:
3584: + fact - the factor matrix obtained with `MatGetFactor()`
3585: . mat  - the matrix
3586: . perm - row and column permutations
3587: - info - options for factorization, includes
3588: .vb
3589:           fill - expected fill as ratio of original fill.
3590:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3591:                    Run with the option -info to determine an optimal value to use
3592: .ve

3594:   Level: developer

3596:   Notes:
3597:   See `MatLUFactorSymbolic()` for the nonsymmetric case. See also
3598:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

3600:   Most users should employ the `KSP` interface for linear solvers
3601:   instead of working directly with matrix algebra routines such as this.
3602:   See, e.g., `KSPCreate()`.

3604:   Fortran Note:
3605:   A valid (non-null) `info` argument must be provided

3607: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3608:           `MatGetOrdering()`
3609: @*/
3610: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3611: {
3612:   MatFactorInfo tinfo;

3614:   PetscFunctionBegin;
3618:   if (info) PetscAssertPointer(info, 4);
3621:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3622:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3623:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3624:   MatCheckPreallocated(mat, 2);
3625:   if (!info) {
3626:     PetscCall(MatFactorInfoInitialize(&tinfo));
3627:     info = &tinfo;
3628:   }

3630:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3631:   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3632:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3633:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3634:   PetscFunctionReturn(PETSC_SUCCESS);
3635: }

3637: /*@
3638:   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3639:   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3640:   `MatCholeskyFactorSymbolic()`.

3642:   Collective

3644:   Input Parameters:
3645: + fact - the factor matrix obtained with `MatGetFactor()`, where the factored values are stored
3646: . mat  - the initial matrix that is to be factored
3647: - info - options for factorization

3649:   Level: developer

3651:   Note:
3652:   Most users should employ the `KSP` interface for linear solvers
3653:   instead of working directly with matrix algebra routines such as this.
3654:   See, e.g., `KSPCreate()`.

3656:   Fortran Note:
3657:   A valid (non-null) `info` argument must be provided

3659: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3660: @*/
3661: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3662: {
3663:   MatFactorInfo tinfo;

3665:   PetscFunctionBegin;
3670:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3671:   PetscCheck(mat->rmap->N == (fact)->rmap->N && mat->cmap->N == (fact)->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dim %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3672:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3673:   MatCheckPreallocated(mat, 2);
3674:   if (!info) {
3675:     PetscCall(MatFactorInfoInitialize(&tinfo));
3676:     info = &tinfo;
3677:   }

3679:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3680:   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3681:   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3682:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3683:   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3684:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3685:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3686:   PetscFunctionReturn(PETSC_SUCCESS);
3687: }

3689: /*@
3690:   MatQRFactor - Performs in-place QR factorization of matrix.

3692:   Collective

3694:   Input Parameters:
3695: + mat  - the matrix
3696: . col  - column permutation
3697: - info - options for factorization, includes
3698: .vb
3699:           fill - expected fill as ratio of original fill.
3700:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3701:                    Run with the option -info to determine an optimal value to use
3702: .ve

3704:   Level: developer

3706:   Notes:
3707:   Most users should employ the `KSP` interface for linear solvers
3708:   instead of working directly with matrix algebra routines such as this.
3709:   See, e.g., `KSPCreate()`.

3711:   This changes the state of the matrix to a factored matrix; it cannot be used
3712:   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.

3714:   Fortran Note:
3715:   A valid (non-null) `info` argument must be provided

3717: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3718:           `MatSetUnfactored()`
3719: @*/
3720: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3721: {
3722:   PetscFunctionBegin;
3725:   if (info) PetscAssertPointer(info, 3);
3727:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3728:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3729:   MatCheckPreallocated(mat, 1);
3730:   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3731:   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3732:   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3733:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3734:   PetscFunctionReturn(PETSC_SUCCESS);
3735: }

3737: /*@
3738:   MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3739:   Call this routine after `MatGetFactor()` but before calling `MatQRFactorNumeric()`.

3741:   Collective

3743:   Input Parameters:
3744: + fact - the factor matrix obtained with `MatGetFactor()`
3745: . mat  - the matrix
3746: . col  - column permutation
3747: - info - options for factorization, includes
3748: .vb
3749:           fill - expected fill as ratio of original fill.
3750:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3751:                    Run with the option -info to determine an optimal value to use
3752: .ve

3754:   Level: developer

3756:   Note:
3757:   Most users should employ the `KSP` interface for linear solvers
3758:   instead of working directly with matrix algebra routines such as this.
3759:   See, e.g., `KSPCreate()`.

3761:   Fortran Note:
3762:   A valid (non-null) `info` argument must be provided

3764: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3765: @*/
3766: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3767: {
3768:   MatFactorInfo tinfo;

3770:   PetscFunctionBegin;
3774:   if (info) PetscAssertPointer(info, 4);
3777:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3778:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3779:   MatCheckPreallocated(mat, 2);
3780:   if (!info) {
3781:     PetscCall(MatFactorInfoInitialize(&tinfo));
3782:     info = &tinfo;
3783:   }

3785:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3786:   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3787:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3788:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3789:   PetscFunctionReturn(PETSC_SUCCESS);
3790: }

3792: /*@
3793:   MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3794:   Call this routine after first calling `MatGetFactor()`, and `MatQRFactorSymbolic()`.

3796:   Collective

3798:   Input Parameters:
3799: + fact - the factor matrix obtained with `MatGetFactor()`
3800: . mat  - the matrix
3801: - info - options for factorization

3803:   Level: developer

3805:   Notes:
3806:   See `MatQRFactor()` for in-place factorization.

3808:   Most users should employ the `KSP` interface for linear solvers
3809:   instead of working directly with matrix algebra routines such as this.
3810:   See, e.g., `KSPCreate()`.

3812:   Fortran Note:
3813:   A valid (non-null) `info` argument must be provided

3815: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3816: @*/
3817: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3818: {
3819:   MatFactorInfo tinfo;

3821:   PetscFunctionBegin;
3826:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3827:   PetscCheck(mat->rmap->N == fact->rmap->N && mat->cmap->N == fact->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dimensions are different %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3828:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3830:   MatCheckPreallocated(mat, 2);
3831:   if (!info) {
3832:     PetscCall(MatFactorInfoInitialize(&tinfo));
3833:     info = &tinfo;
3834:   }

3836:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3837:   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3838:   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3839:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3840:   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3841:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3842:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3843:   PetscFunctionReturn(PETSC_SUCCESS);
3844: }

3846: /*@
3847:   MatSolve - Solves $A x = b$, given a factored matrix.

3849:   Neighbor-wise Collective

3851:   Input Parameters:
3852: + mat - the factored matrix
3853: - b   - the right-hand-side vector

3855:   Output Parameter:
3856: . x - the result vector

3858:   Level: developer

3860:   Notes:
3861:   The vectors `b` and `x` cannot be the same. I.e., one cannot
3862:   call `MatSolve`(A,x,x).

3864:   Most users should employ the `KSP` interface for linear solvers
3865:   instead of working directly with matrix algebra routines such as this.
3866:   See, e.g., `KSPCreate()`.

3868: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3869: @*/
3870: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3871: {
3872:   PetscFunctionBegin;
3877:   PetscCheckSameComm(mat, 1, b, 2);
3878:   PetscCheckSameComm(mat, 1, x, 3);
3879:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3880:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3881:   PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
3882:   PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
3883:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3884:   MatCheckPreallocated(mat, 1);

3886:   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3887:   PetscCall(VecFlag(x, mat->factorerrortype));
3888:   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3889:   else PetscUseTypeMethod(mat, solve, b, x);
3890:   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3891:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3892:   PetscFunctionReturn(PETSC_SUCCESS);
3893: }

3895: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3896: {
3897:   Vec      b, x;
3898:   PetscInt N;
3899:   PetscErrorCode (*f)(Mat, Vec, Vec);
3900:   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;

3902:   PetscFunctionBegin;
3903:   if (A->factorerrortype) {
3904:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3905:     PetscCall(MatSetInf(X));
3906:     PetscFunctionReturn(PETSC_SUCCESS);
3907:   }
3908:   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3909:   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3910:   PetscCall(MatBoundToCPU(A, &Abound));
3911:   if (!Abound) {
3912:     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3913:     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3914:   }
3915: #if PetscDefined(HAVE_CUDA)
3916:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3917:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3918: #elif PetscDefined(HAVE_HIP)
3919:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3920:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3921: #endif
3922:   PetscCall(MatGetSize(B, NULL, &N));
3923:   for (PetscInt i = 0; i < N; i++) {
3924:     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3925:     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3926:     PetscCall((*f)(A, b, x));
3927:     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3928:     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3929:   }
3930:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3931:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3932:   PetscFunctionReturn(PETSC_SUCCESS);
3933: }

3935: /*@
3936:   MatMatSolve - Solves $A X = B$, given a factored matrix.

3938:   Neighbor-wise Collective

3940:   Input Parameters:
3941: + A - the factored matrix
3942: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3944:   Output Parameter:
3945: . X - the result matrix (dense matrix)

3947:   Level: developer

3949:   Note:
3950:   If `B` is a `MATDENSE` matrix then one can call `MatMatSolve`(A,B,B) except with `MATSOLVERMKL_CPARDISO`;
3951:   otherwise, `B` and `X` cannot be the same.

3953: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3954: @*/
3955: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3956: {
3957:   PetscFunctionBegin;
3962:   PetscCheckSameComm(A, 1, B, 2);
3963:   PetscCheckSameComm(A, 1, X, 3);
3964:   PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
3965:   PetscCheck(A->rmap->N == B->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N);
3966:   PetscCheck(X->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as rhs matrix");
3967:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3968:   MatCheckPreallocated(A, 1);

3970:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3971:   if (!A->ops->matsolve) {
3972:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3973:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3974:   } else PetscUseTypeMethod(A, matsolve, B, X);
3975:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3976:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3977:   PetscFunctionReturn(PETSC_SUCCESS);
3978: }

3980: /*@
3981:   MatMatSolveTranspose - Solves $A^T X = B $, given a factored matrix.

3983:   Neighbor-wise Collective

3985:   Input Parameters:
3986: + A - the factored matrix
3987: - B - the right-hand-side matrix  (`MATDENSE` matrix)

3989:   Output Parameter:
3990: . X - the result matrix (dense matrix)

3992:   Level: developer

3994:   Note:
3995:   The matrices `B` and `X` cannot be the same. I.e., one cannot
3996:   call `MatMatSolveTranspose`(A,X,X).

3998: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3999: @*/
4000: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
4001: {
4002:   PetscFunctionBegin;
4007:   PetscCheckSameComm(A, 1, B, 2);
4008:   PetscCheckSameComm(A, 1, X, 3);
4009:   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4010:   PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
4011:   PetscCheck(A->rmap->N == B->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N);
4012:   PetscCheck(A->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat A,Mat B: local dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->n, B->rmap->n);
4013:   PetscCheck(X->cmap->N >= B->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as rhs matrix");
4014:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4015:   MatCheckPreallocated(A, 1);

4017:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
4018:   if (!A->ops->matsolvetranspose) {
4019:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
4020:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
4021:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
4022:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
4023:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4024:   PetscFunctionReturn(PETSC_SUCCESS);
4025: }

4027: /*@
4028:   MatMatTransposeSolve - Solves $A X = B^T$, given a factored matrix.

4030:   Neighbor-wise Collective

4032:   Input Parameters:
4033: + A  - the factored matrix
4034: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

4036:   Output Parameter:
4037: . X - the result matrix (dense matrix)

4039:   Level: developer

4041:   Note:
4042:   For MUMPS, it only supports centralized sparse compressed column format on the host process for right-hand side matrix. User must create `Bt` in sparse compressed row
4043:   format on the host process and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.

4045: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
4046: @*/
4047: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
4048: {
4049:   PetscFunctionBegin;
4054:   PetscCheckSameComm(A, 1, Bt, 2);
4055:   PetscCheckSameComm(A, 1, X, 3);

4057:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4058:   PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
4059:   PetscCheck(A->rmap->N == Bt->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat Bt: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, Bt->cmap->N);
4060:   PetscCheck(X->cmap->N >= Bt->rmap->N, PetscObjectComm((PetscObject)X), PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as row number of the rhs matrix");
4061:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4062:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
4063:   MatCheckPreallocated(A, 1);

4065:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
4066:   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
4067:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
4068:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4069:   PetscFunctionReturn(PETSC_SUCCESS);
4070: }

4072: /*@
4073:   MatForwardSolve - Solves $ L x = b $, given a factored matrix, $A = LU $, or
4074:   $U^T*D^(1/2) x = b$, given a factored symmetric matrix, $A = U^T*D*U$,

4076:   Neighbor-wise Collective

4078:   Input Parameters:
4079: + mat - the factored matrix
4080: - b   - the right-hand-side vector

4082:   Output Parameter:
4083: . x - the result vector

4085:   Level: developer

4087:   Notes:
4088:   `MatSolve()` should be used for most applications, as it performs
4089:   a forward solve followed by a backward solve.

4091:   The vectors `b` and `x` cannot be the same,  i.e., one cannot
4092:   call `MatForwardSolve`(A,x,x).

4094:   For matrix in `MATSEQBAIJ` format with block size larger than 1,
4095:   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
4096:   `MatForwardSolve()` solves $U^T*D y = b$, and
4097:   `MatBackwardSolve()` solves $U x = y$.
4098:   Thus they do not provide a symmetric preconditioner.

4100: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4101: @*/
4102: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4103: {
4104:   PetscFunctionBegin;
4109:   PetscCheckSameComm(mat, 1, b, 2);
4110:   PetscCheckSameComm(mat, 1, x, 3);
4111:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4112:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4113:   PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4114:   PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4115:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4116:   MatCheckPreallocated(mat, 1);

4118:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4119:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4120:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4121:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4122:   PetscFunctionReturn(PETSC_SUCCESS);
4123: }

4125: /*@
4126:   MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
4127:   $D^(1/2) U x = b$, given a factored symmetric matrix, $A = U^T*D*U$,

4129:   Neighbor-wise Collective

4131:   Input Parameters:
4132: + mat - the factored matrix
4133: - b   - the right-hand-side vector

4135:   Output Parameter:
4136: . x - the result vector

4138:   Level: developer

4140:   Notes:
4141:   `MatSolve()` should be used for most applications, as it performs
4142:   a forward solve followed by a backward solve.

4144:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4145:   call `MatBackwardSolve`(A,x,x).

4147:   For matrix in `MATSEQBAIJ` format with block size larger than 1,
4148:   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
4149:   `MatForwardSolve()` solves $U^T*D y = b$, and
4150:   `MatBackwardSolve()` solves $U x = y$.
4151:   Thus they do not provide a symmetric preconditioner.

4153: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4154: @*/
4155: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4156: {
4157:   PetscFunctionBegin;
4162:   PetscCheckSameComm(mat, 1, b, 2);
4163:   PetscCheckSameComm(mat, 1, x, 3);
4164:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4165:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4166:   PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4167:   PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4168:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4169:   MatCheckPreallocated(mat, 1);

4171:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4172:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4173:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4174:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4175:   PetscFunctionReturn(PETSC_SUCCESS);
4176: }

4178: /*@
4179:   MatSolveAdd - Computes $x = y + A^{-1}*b$, given a factored matrix.

4181:   Neighbor-wise Collective

4183:   Input Parameters:
4184: + mat - the factored matrix
4185: . b   - the right-hand-side vector
4186: - y   - the vector to be added to

4188:   Output Parameter:
4189: . x - the result vector

4191:   Level: developer

4193:   Note:
4194:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4195:   call `MatSolveAdd`(A,x,y,x).

4197: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4198: @*/
4199: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4200: {
4201:   PetscScalar one = 1.0;
4202:   Vec         tmp;

4204:   PetscFunctionBegin;
4210:   PetscCheckSameComm(mat, 1, b, 2);
4211:   PetscCheckSameComm(mat, 1, y, 3);
4212:   PetscCheckSameComm(mat, 1, x, 4);
4213:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4214:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4215:   PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4216:   PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
4217:   PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4218:   PetscCheck(x->map->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vec x,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, x->map->n, y->map->n);
4219:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4220:   MatCheckPreallocated(mat, 1);

4222:   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4223:   PetscCall(VecFlag(x, mat->factorerrortype));
4224:   if (mat->factorerrortype) {
4225:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4226:   } else if (mat->ops->solveadd) {
4227:     PetscUseTypeMethod(mat, solveadd, b, y, x);
4228:   } else {
4229:     /* do the solve then the add manually */
4230:     if (x != y) {
4231:       PetscCall(MatSolve(mat, b, x));
4232:       PetscCall(VecAXPY(x, one, y));
4233:     } else {
4234:       PetscCall(VecDuplicate(x, &tmp));
4235:       PetscCall(VecCopy(x, tmp));
4236:       PetscCall(MatSolve(mat, b, x));
4237:       PetscCall(VecAXPY(x, one, tmp));
4238:       PetscCall(VecDestroy(&tmp));
4239:     }
4240:   }
4241:   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4242:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4243:   PetscFunctionReturn(PETSC_SUCCESS);
4244: }

4246: /*@
4247:   MatSolveTranspose - Solves $A^T x = b$, given a factored matrix.

4249:   Neighbor-wise Collective

4251:   Input Parameters:
4252: + mat - the factored matrix
4253: - b   - the right-hand-side vector

4255:   Output Parameter:
4256: . x - the result vector

4258:   Level: developer

4260:   Notes:
4261:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4262:   call `MatSolveTranspose`(A,x,x).

4264:   Most users should employ the `KSP` interface for linear solvers
4265:   instead of working directly with matrix algebra routines such as this.
4266:   See, e.g., `KSPCreate()`.

4268: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4269: @*/
4270: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4271: {
4272:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

4274:   PetscFunctionBegin;
4279:   PetscCheckSameComm(mat, 1, b, 2);
4280:   PetscCheckSameComm(mat, 1, x, 3);
4281:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4282:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
4283:   PetscCheck(mat->cmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, b->map->N);
4284:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4285:   MatCheckPreallocated(mat, 1);
4286:   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4287:   PetscCall(VecFlag(x, mat->factorerrortype));
4288:   if (mat->factorerrortype) {
4289:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4290:   } else {
4291:     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4292:     PetscCall((*f)(mat, b, x));
4293:   }
4294:   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4295:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4296:   PetscFunctionReturn(PETSC_SUCCESS);
4297: }

4299: /*@
4300:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4301:   factored matrix.

4303:   Neighbor-wise Collective

4305:   Input Parameters:
4306: + mat - the factored matrix
4307: . b   - the right-hand-side vector
4308: - y   - the vector to be added to

4310:   Output Parameter:
4311: . x - the result vector

4313:   Level: developer

4315:   Note:
4316:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4317:   call `MatSolveTransposeAdd`(A,x,y,x).

4319: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4320: @*/
4321: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4322: {
4323:   PetscScalar one = 1.0;
4324:   Vec         tmp;
4325:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

4327:   PetscFunctionBegin;
4333:   PetscCheckSameComm(mat, 1, b, 2);
4334:   PetscCheckSameComm(mat, 1, y, 3);
4335:   PetscCheckSameComm(mat, 1, x, 4);
4336:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4337:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
4338:   PetscCheck(mat->cmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, b->map->N);
4339:   PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
4340:   PetscCheck(x->map->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vec x,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, x->map->n, y->map->n);
4341:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4342:   MatCheckPreallocated(mat, 1);

4344:   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4345:   PetscCall(VecFlag(x, mat->factorerrortype));
4346:   if (mat->factorerrortype) {
4347:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4348:   } else if (f) {
4349:     PetscCall((*f)(mat, b, y, x));
4350:   } else {
4351:     /* do the solve then the add manually */
4352:     if (x != y) {
4353:       PetscCall(MatSolveTranspose(mat, b, x));
4354:       PetscCall(VecAXPY(x, one, y));
4355:     } else {
4356:       PetscCall(VecDuplicate(x, &tmp));
4357:       PetscCall(VecCopy(x, tmp));
4358:       PetscCall(MatSolveTranspose(mat, b, x));
4359:       PetscCall(VecAXPY(x, one, tmp));
4360:       PetscCall(VecDestroy(&tmp));
4361:     }
4362:   }
4363:   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4364:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4365:   PetscFunctionReturn(PETSC_SUCCESS);
4366: }

4368: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4369: /*@
4370:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4372:   Neighbor-wise Collective

4374:   Input Parameters:
4375: + mat   - the matrix
4376: . b     - the right-hand side
4377: . omega - the relaxation factor
4378: . flag  - flag indicating the type of SOR (see below)
4379: . shift - diagonal shift
4380: . its   - the number of iterations
4381: - lits  - the number of local iterations

4383:   Output Parameter:
4384: . x - the solution (can contain an initial guess, use option `SOR_ZERO_INITIAL_GUESS` to indicate no guess)

4386:   SOR Flags:
4387: +     `SOR_FORWARD_SWEEP` - forward SOR
4388: .     `SOR_BACKWARD_SWEEP` - backward SOR
4389: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4390: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4391: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4392: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4393: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4394: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4395: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4397:   Level: developer

4399:   Notes:
4400:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4401:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4402:   on each process.

4404:   Application programmers will not generally use `MatSOR()` directly,
4405:   but instead will employ `PCSOR` or `PCEISENSTAT`

4407:   For `MATBAIJ`, `MATSBAIJ`, and `MATAIJ` matrices with inodes, this does a block SOR smoothing, otherwise it does a pointwise smoothing.
4408:   For `MATAIJ` matrices with inodes, the block sizes are determined by the inode sizes, not the block size set with `MatSetBlockSize()`

4410:   Vectors `x` and `b` CANNOT be the same

4412:   The flags are implemented as bitwise inclusive or operations.
4413:   For example, use (`SOR_ZERO_INITIAL_GUESS` | `SOR_SYMMETRIC_SWEEP`)
4414:   to specify a zero initial guess for SSOR.

4416:   Developer Note:
4417:   We should add block SOR support for `MATAIJ` matrices with block size set to greater than one and no inodes

4419: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4420: @*/
4421: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4422: {
4423:   PetscFunctionBegin;
4428:   PetscCheckSameComm(mat, 1, b, 2);
4429:   PetscCheckSameComm(mat, 1, x, 8);
4430:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4431:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4432:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4433:   PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4434:   PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4435:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4436:   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4437:   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");

4439:   MatCheckPreallocated(mat, 1);
4440:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4441:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4442:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4443:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4444:   PetscFunctionReturn(PETSC_SUCCESS);
4445: }

4447: /*
4448:       Default matrix copy routine.
4449: */
4450: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4451: {
4452:   PetscInt           i, rstart = 0, rend = 0, nz;
4453:   const PetscInt    *cwork;
4454:   const PetscScalar *vwork;

4456:   PetscFunctionBegin;
4457:   if (B->assembled) PetscCall(MatZeroEntries(B));
4458:   if (str == SAME_NONZERO_PATTERN) {
4459:     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4460:     for (i = rstart; i < rend; i++) {
4461:       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4462:       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4463:       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4464:     }
4465:   } else {
4466:     PetscCall(MatAYPX(B, 0.0, A, str));
4467:   }
4468:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4469:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4470:   PetscFunctionReturn(PETSC_SUCCESS);
4471: }

4473: /*@
4474:   MatCopy - Copies a matrix to another matrix.

4476:   Collective

4478:   Input Parameters:
4479: + A   - the matrix
4480: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4482:   Output Parameter:
4483: . B - where the copy is put

4485:   Level: intermediate

4487:   Notes:
4488:   If you use `SAME_NONZERO_PATTERN`, then the two matrices must have the same nonzero pattern or the routine will crash.

4490:   `MatCopy()` copies the matrix entries of a matrix to another existing
4491:   matrix (after first zeroing the second matrix). A related routine is
4492:   `MatConvert()`, which first creates a new matrix and then copies the data.

4494: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4495: @*/
4496: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4497: {
4498:   PetscInt i;

4500:   PetscFunctionBegin;
4505:   PetscCheckSameComm(A, 1, B, 2);
4506:   MatCheckPreallocated(B, 2);
4507:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4508:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4509:   PetscCheck(A->rmap->N == B->rmap->N && A->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim (%" PetscInt_FMT ",%" PetscInt_FMT ") (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->N, B->rmap->N,
4510:              A->cmap->N, B->cmap->N);
4511:   MatCheckPreallocated(A, 1);
4512:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4514:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4515:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4516:   else PetscCall(MatCopy_Basic(A, B, str));

4518:   B->stencil.dim = A->stencil.dim;
4519:   B->stencil.noc = A->stencil.noc;
4520:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4521:     B->stencil.dims[i]   = A->stencil.dims[i];
4522:     B->stencil.starts[i] = A->stencil.starts[i];
4523:   }

4525:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4526:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4527:   PetscFunctionReturn(PETSC_SUCCESS);
4528: }

4530: /*@
4531:   MatConvert - Converts a matrix to another matrix, either of the same
4532:   or different type.

4534:   Collective

4536:   Input Parameters:
4537: + mat     - the matrix
4538: . newtype - new matrix type. Use `MATSAME` to create a new matrix of the
4539:             same type as the original matrix.
4540: - reuse   - denotes if the destination matrix is to be created or reused.
4541:             Use `MAT_INPLACE_MATRIX` for inplace conversion (that is when you want the input `Mat` to be changed to contain the matrix in the new format), otherwise use
4542:             `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX` (can only be used after the first call was made with `MAT_INITIAL_MATRIX`, causes the matrix space in M to be reused).

4544:   Output Parameter:
4545: . M - pointer to place new matrix

4547:   Level: intermediate

4549:   Notes:
4550:   `MatConvert()` first creates a new matrix and then copies the data from
4551:   the first matrix. A related routine is `MatCopy()`, which copies the matrix
4552:   entries of one matrix to another already existing matrix context.

4554:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4555:   the MPI communicator of the generated matrix is always the same as the communicator
4556:   of the input matrix.

4558: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4559: @*/
4560: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4561: {
4562:   PetscBool  sametype, issame, flg;
4563:   PetscBool3 issymmetric, ishermitian, isspd;
4564:   char       convname[256], mtype[256];
4565:   Mat        B;

4567:   PetscFunctionBegin;
4570:   PetscAssertPointer(M, 4);
4571:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4572:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4573:   MatCheckPreallocated(mat, 1);

4575:   PetscCall(PetscOptionsGetString(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matconvert_type", mtype, sizeof(mtype), &flg));
4576:   if (flg) newtype = mtype;

4578:   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4579:   PetscCall(PetscStrcmp(newtype, "same", &issame));
4580:   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4581:   if (reuse == MAT_REUSE_MATRIX) {
4583:     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4584:   }

4586:   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4587:     PetscCall(PetscInfo(mat, "Early return for inplace %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4588:     PetscFunctionReturn(PETSC_SUCCESS);
4589:   }

4591:   /* Cache Mat options because some converters use MatHeaderReplace() */
4592:   issymmetric = mat->symmetric;
4593:   ishermitian = mat->hermitian;
4594:   isspd       = mat->spd;

4596:   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4597:     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4598:     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4599:   } else {
4600:     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4601:     const char *prefix[3]                                 = {"seq", "mpi", ""};
4602:     PetscInt    i;
4603:     /*
4604:        Order of precedence:
4605:        0) See if newtype is a superclass of the current matrix.
4606:        1) See if a specialized converter is known to the current matrix.
4607:        2) See if a specialized converter is known to the desired matrix class.
4608:        3) See if a good general converter is registered for the desired class
4609:           (as of 6/27/03 only MATMPIADJ falls into this category).
4610:        4) See if a good general converter is known for the current matrix.
4611:        5) Use a really basic converter.
4612:     */

4614:     /* 0) See if newtype is a superclass of the current matrix.
4615:           i.e mat is mpiaij and newtype is aij */
4616:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4617:       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4618:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4619:       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4620:       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4621:       if (flg) {
4622:         if (reuse == MAT_INPLACE_MATRIX) {
4623:           PetscCall(PetscInfo(mat, "Early return\n"));
4624:           PetscFunctionReturn(PETSC_SUCCESS);
4625:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4626:           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4627:           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4628:           PetscFunctionReturn(PETSC_SUCCESS);
4629:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4630:           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4631:           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4632:           PetscFunctionReturn(PETSC_SUCCESS);
4633:         }
4634:       }
4635:     }
4636:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4637:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4638:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4639:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4640:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4641:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4642:       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4643:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4644:       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4645:       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4646:       if (conv) goto foundconv;
4647:     }

4649:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4650:     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4651:     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4652:     PetscCall(MatSetType(B, newtype));
4653:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4654:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4655:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4656:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4657:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4658:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4659:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4660:       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4661:       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4662:       if (conv) {
4663:         PetscCall(MatDestroy(&B));
4664:         goto foundconv;
4665:       }
4666:     }

4668:     /* 3) See if a good general converter is registered for the desired class */
4669:     conv = B->ops->convertfrom;
4670:     PetscCall(PetscInfo(mat, "Check convertfrom (%s) -> %d\n", ((PetscObject)B)->type_name, !!conv));
4671:     PetscCall(MatDestroy(&B));
4672:     if (conv) goto foundconv;

4674:     /* 4) See if a good general converter is known for the current matrix */
4675:     if (mat->ops->convert) conv = mat->ops->convert;
4676:     PetscCall(PetscInfo(mat, "Check general convert (%s) -> %d\n", ((PetscObject)mat)->type_name, !!conv));
4677:     if (conv) goto foundconv;

4679:     /* 5) Use a really basic converter. */
4680:     PetscCall(PetscInfo(mat, "Using MatConvert_Basic\n"));
4681:     conv = MatConvert_Basic;

4683:   foundconv:
4684:     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4685:     PetscCall((*conv)(mat, newtype, reuse, M));
4686:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4687:       /* the block sizes must be same if the mappings are copied over */
4688:       (*M)->rmap->bs = mat->rmap->bs;
4689:       (*M)->cmap->bs = mat->cmap->bs;
4690:       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4691:       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4692:       (*M)->rmap->mapping = mat->rmap->mapping;
4693:       (*M)->cmap->mapping = mat->cmap->mapping;
4694:     }
4695:     (*M)->stencil.dim = mat->stencil.dim;
4696:     (*M)->stencil.noc = mat->stencil.noc;
4697:     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4698:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4699:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4700:     }
4701:     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4702:   }
4703:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));

4705:   /* Reset Mat options */
4706:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4707:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4708:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4709:   PetscFunctionReturn(PETSC_SUCCESS);
4710: }

4712: /*@
4713:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4715:   Not Collective

4717:   Input Parameter:
4718: . mat - the matrix, must be a factored matrix

4720:   Output Parameter:
4721: . type - the string name of the package (do not free this string)

4723:   Level: intermediate

4725: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4726: @*/
4727: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4728: {
4729:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4731:   PetscFunctionBegin;
4734:   PetscAssertPointer(type, 2);
4735:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4736:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4737:   if (conv) PetscCall((*conv)(mat, type));
4738:   else *type = MATSOLVERPETSC;
4739:   PetscFunctionReturn(PETSC_SUCCESS);
4740: }

4742: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4743: struct _MatSolverTypeForSpecifcType {
4744:   MatType mtype;
4745:   /* no entry for MAT_FACTOR_NONE */
4746:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4747:   MatSolverTypeForSpecifcType next;
4748: };

4750: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4751: struct _MatSolverTypeHolder {
4752:   char                       *name;
4753:   MatSolverTypeForSpecifcType handlers;
4754:   MatSolverTypeHolder         next;
4755: };

4757: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4759: /*@
4760:   MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type

4762:   Logically Collective, No Fortran Support

4764:   Input Parameters:
4765: + package      - name of the package, for example `petsc` or `superlu`
4766: . mtype        - the matrix type that works with this package
4767: . ftype        - the type of factorization supported by the package
4768: - createfactor - routine that will create the factored matrix ready to be used

4770:   Level: developer

4772: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4773:   `MatGetFactor()`
4774: @*/
4775: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4776: {
4777:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4778:   PetscBool                   flg;
4779:   MatSolverTypeForSpecifcType inext, iprev = NULL;

4781:   PetscFunctionBegin;
4782:   PetscCall(MatInitializePackage());
4783:   if (!next) {
4784:     PetscCall(PetscNew(&MatSolverTypeHolders));
4785:     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4786:     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4787:     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4788:     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4789:     PetscFunctionReturn(PETSC_SUCCESS);
4790:   }
4791:   while (next) {
4792:     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4793:     if (flg) {
4794:       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4795:       inext = next->handlers;
4796:       while (inext) {
4797:         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4798:         if (flg) {
4799:           inext->createfactor[(int)ftype - 1] = createfactor;
4800:           PetscFunctionReturn(PETSC_SUCCESS);
4801:         }
4802:         iprev = inext;
4803:         inext = inext->next;
4804:       }
4805:       PetscCall(PetscNew(&iprev->next));
4806:       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4807:       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4808:       PetscFunctionReturn(PETSC_SUCCESS);
4809:     }
4810:     prev = next;
4811:     next = next->next;
4812:   }
4813:   PetscCall(PetscNew(&prev->next));
4814:   PetscCall(PetscStrallocpy(package, &prev->next->name));
4815:   PetscCall(PetscNew(&prev->next->handlers));
4816:   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4817:   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4818:   PetscFunctionReturn(PETSC_SUCCESS);
4819: }

4821: /*@
4822:   MatSolverTypeGet - Gets the function that creates the factor matrix if it exist

4824:   Input Parameters:
4825: + type  - name of the package, for example `petsc` or `superlu`, if this is `NULL`, then the first result that satisfies the other criteria is returned
4826: . ftype - the type of factorization supported by the type
4827: - mtype - the matrix type that works with this type

4829:   Output Parameters:
4830: + foundtype    - `PETSC_TRUE` if the type was registered
4831: . foundmtype   - `PETSC_TRUE` if the type supports the requested mtype
4832: - createfactor - routine that will create the factored matrix ready to be used or `NULL` if not found

4834:   Calling sequence of `createfactor`:
4835: + A     - the matrix providing the factor matrix
4836: . ftype - the `MatFactorType` of the factor requested
4837: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4839:   Level: developer

4841:   Note:
4842:   When `type` is `NULL` the available functions are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4843:   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4844:   For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.

4846: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4847:           `MatInitializePackage()`
4848: @*/
4849: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4850: {
4851:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4852:   PetscBool                   flg;
4853:   MatSolverTypeForSpecifcType inext;

4855:   PetscFunctionBegin;
4856:   if (foundtype) *foundtype = PETSC_FALSE;
4857:   if (foundmtype) *foundmtype = PETSC_FALSE;
4858:   if (createfactor) *createfactor = NULL;

4860:   if (type) {
4861:     while (next) {
4862:       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4863:       if (flg) {
4864:         if (foundtype) *foundtype = PETSC_TRUE;
4865:         inext = next->handlers;
4866:         while (inext) {
4867:           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4868:           if (flg) {
4869:             if (foundmtype) *foundmtype = PETSC_TRUE;
4870:             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4871:             PetscFunctionReturn(PETSC_SUCCESS);
4872:           }
4873:           inext = inext->next;
4874:         }
4875:       }
4876:       next = next->next;
4877:     }
4878:   } else {
4879:     while (next) {
4880:       inext = next->handlers;
4881:       while (inext) {
4882:         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4883:         if (flg && inext->createfactor[(int)ftype - 1]) {
4884:           if (foundtype) *foundtype = PETSC_TRUE;
4885:           if (foundmtype) *foundmtype = PETSC_TRUE;
4886:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4887:           PetscFunctionReturn(PETSC_SUCCESS);
4888:         }
4889:         inext = inext->next;
4890:       }
4891:       next = next->next;
4892:     }
4893:     /* try with base classes inext->mtype */
4894:     next = MatSolverTypeHolders;
4895:     while (next) {
4896:       inext = next->handlers;
4897:       while (inext) {
4898:         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4899:         if (flg && inext->createfactor[(int)ftype - 1]) {
4900:           if (foundtype) *foundtype = PETSC_TRUE;
4901:           if (foundmtype) *foundmtype = PETSC_TRUE;
4902:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4903:           PetscFunctionReturn(PETSC_SUCCESS);
4904:         }
4905:         inext = inext->next;
4906:       }
4907:       next = next->next;
4908:     }
4909:   }
4910:   PetscFunctionReturn(PETSC_SUCCESS);
4911: }

4913: PetscErrorCode MatSolverTypeDestroy(void)
4914: {
4915:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4916:   MatSolverTypeForSpecifcType inext, iprev;

4918:   PetscFunctionBegin;
4919:   while (next) {
4920:     PetscCall(PetscFree(next->name));
4921:     inext = next->handlers;
4922:     while (inext) {
4923:       PetscCall(PetscFree(inext->mtype));
4924:       iprev = inext;
4925:       inext = inext->next;
4926:       PetscCall(PetscFree(iprev));
4927:     }
4928:     prev = next;
4929:     next = next->next;
4930:     PetscCall(PetscFree(prev));
4931:   }
4932:   MatSolverTypeHolders = NULL;
4933:   PetscFunctionReturn(PETSC_SUCCESS);
4934: }

4936: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4937: {
4938:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4939:   MatSolverTypeForSpecifcType inext;
4940:   PetscBool                   flg, same;

4942:   PetscFunctionBegin;
4943:   *found = PETSC_FALSE;
4944:   *f     = NULL;
4945:   /* When no solver type is requested, MatGetFactor() must honor registration order, but a registered
4946:      MatSolverType may only be able to reject a particular MatType at runtime by returning NULL in *f.
4947:      Keep walking the registry until a matching backend actually creates a factor. */
4948:   while (next) {
4949:     inext = next->handlers;
4950:     while (inext) {
4951:       PetscCall(PetscStrcmp(((PetscObject)mat)->type_name, inext->mtype, &same));
4952:       if (exact) flg = same;
4953:       else {
4954:         /* Do the base-type pass separately from the exact pass so exact registrations for the MatType
4955:            are all tried before broader registrations such as implementation base classes. */
4956:         PetscCall(PetscStrbeginswith(((PetscObject)mat)->type_name, inext->mtype, &flg));
4957:         flg = (PetscBool)(flg && !same);
4958:       }
4959:       if (flg && inext->createfactor[(int)ftype - 1]) {
4960:         *found = PETSC_TRUE;
4961:         PetscCall((*inext->createfactor[(int)ftype - 1])(mat, ftype, f));
4962:         if (*f) PetscFunctionReturn(PETSC_SUCCESS);
4963:       }
4964:       inext = inext->next;
4965:     }
4966:     next = next->next;
4967:   }
4968:   PetscFunctionReturn(PETSC_SUCCESS);
4969: }

4971: /*@
4972:   MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`

4974:   Logically Collective

4976:   Input Parameter:
4977: . mat - the matrix

4979:   Output Parameter:
4980: . flg - `PETSC_TRUE` if uses the ordering

4982:   Level: developer

4984:   Note:
4985:   Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4986:   packages do not, thus we want to skip generating the ordering when it is not needed or used.

4988: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4989: @*/
4990: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4991: {
4992:   PetscFunctionBegin;
4993:   *flg = mat->canuseordering;
4994:   PetscFunctionReturn(PETSC_SUCCESS);
4995: }

4997: /*@
4998:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

5000:   Logically Collective

5002:   Input Parameters:
5003: + mat   - the matrix obtained with `MatGetFactor()`
5004: - ftype - the factorization type to be used

5006:   Output Parameter:
5007: . otype - the preferred ordering type

5009:   Level: developer

5011: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
5012: @*/
5013: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
5014: {
5015:   PetscFunctionBegin;
5016:   *otype = mat->preferredordering[ftype];
5017:   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
5018:   PetscFunctionReturn(PETSC_SUCCESS);
5019: }

5021: /*@
5022:   MatGetFactor - Returns a matrix suitable to calls to routines such as `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5023:   `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, and `MatCholeskyFactorNumeric()`

5025:   Collective

5027:   Input Parameters:
5028: + mat   - the matrix
5029: . type  - name of solver type, for example, `superlu_dist`, `petsc` (to use PETSc's solver if it is available), if this is `NULL`, then the first result that satisfies
5030:           the other criteria is returned
5031: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

5033:   Output Parameter:
5034: . f - the factor matrix used with MatXXFactorSymbolic,Numeric() calls. Can be `NULL` in some cases, see notes below.

5036:   Options Database Keys:
5037: + -pc_factor_mat_solver_type type            - choose the type at run time. When using `KSP` solvers
5038: . -pc_factor_mat_factor_on_host (true|false) - do matrix factorization on host (with device matrices). Default is doing it on device
5039: - -pc_factor_mat_solve_on_host (true|false)  - do matrix solve on host (with device matrices). Default is doing it on device

5041:   Level: intermediate

5043:   Notes:
5044:   Some of the packages, such as MUMPS, have options for controlling the factorization, these are in the form `-prefix_mat_packagename_packageoption`
5045:   (for example, `-mat_mumps_icntl_6 1`)  where `prefix` is normally set automatically from the calling `KSP`/`PC`. If `MatGetFactor()` is called directly,
5046:   without using a `PC`, one can set the prefix by
5047:   calling `MatSetOptionsPrefixFactor()` on the originating matrix or  `MatSetOptionsPrefix()` on the resulting factor matrix.

5049:   Some PETSc matrix formats have alternative solvers available that are provided by alternative packages
5050:   such as PaStiX, SuperLU_DIST, MUMPS etc. PETSc must have been configured to use the external solver,
5051:   using the corresponding `./configure` option such as `--download-package` or `--with-package-dir`.

5053:   When `type` is `NULL` the available results are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
5054:   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
5055:   For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.

5057:   The return matrix can be `NULL` if the requested factorization is not available, since some combinations of matrix types and factorization
5058:   types registered with `MatSolverTypeRegister()` cannot be fully tested if not at runtime.

5060:   Developer Note:
5061:   This should actually be called `MatCreateFactor()` since it creates a new factor object

5063:   The `MatGetFactor()` implementations should not be accessing the PETSc options database or making other decisions about solver options,
5064:   that should be delayed until the later operations. This is to ensure the correct options prefix has been set in the factor matrix.

5066: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
5067:           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
5068:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
5069:           `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5070:           `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
5071: @*/
5072: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
5073: {
5074:   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
5075:   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);

5077:   PetscFunctionBegin;

5081:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5082:   MatCheckPreallocated(mat, 1);

5084:   PetscCall(MatIsShell(mat, &shell));
5085:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
5086:   if (hasop) {
5087:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
5088:     PetscFunctionReturn(PETSC_SUCCESS);
5089:   }

5091:   if (!type) {
5092:     PetscBool foundbase;

5094:     /* First try exact MatType registrations in solver registration order. If all matching backends
5095:        decline this matrix instance by returning NULL, then try base-type registrations. */
5096:     PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
5097:     if (!*f) {
5098:       PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
5099:       foundtype = (PetscBool)(foundtype || foundbase);
5100:     }
5101:     PetscCheck(foundtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate a solver type for factorization type %s and matrix type %s.", MatFactorTypes[ftype], ((PetscObject)mat)->type_name);
5102:     if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5103:     PetscFunctionReturn(PETSC_SUCCESS);
5104:   }

5106:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
5107:   PetscCheck(foundtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate%s solver type%s%s for factorization type %s and matrix type %s.%s%s", !type ? " a" : "", type ? " " : "", type ? type : "", MatFactorTypes[ftype],
5108:              ((PetscObject)mat)->type_name, type ? " Perhaps you must ./configure with --download-" : "", type ? type : "");
5109:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
5110:   PetscCheck(conv, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support factorization type %s for matrix type %s", type, MatFactorTypes[ftype], ((PetscObject)mat)->type_name);

5112:   PetscCall((*conv)(mat, ftype, f));
5113:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5114:   PetscFunctionReturn(PETSC_SUCCESS);
5115: }

5117: /*@
5118:   MatGetFactorAvailable - Returns a flag if matrix supports particular type and factor type

5120:   Not Collective

5122:   Input Parameters:
5123: + mat   - the matrix
5124: . type  - name of solver type, for example, `superlu`, `petsc` (to use PETSc's default)
5125: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

5127:   Output Parameter:
5128: . flg - `PETSC_TRUE` if the factorization is available

5130:   Level: intermediate

5132:   Notes:
5133:   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
5134:   such as `pastix`, `superlu`, `mumps`, etc.

5136:   PETSc must have been configured with `./configure` to use the external solver using the option `--download-package` where package is the name of the package

5138:   Developer Note:
5139:   This should actually be called `MatCreateFactorAvailable()` since `MatGetFactor()` creates a new factor object

5141: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5142:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5143: @*/
5144: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5145: {
5146:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5148:   PetscFunctionBegin;
5150:   PetscAssertPointer(flg, 4);

5152:   *flg = PETSC_FALSE;
5153:   if (!((PetscObject)mat)->type_name) PetscFunctionReturn(PETSC_SUCCESS);

5155:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5156:   MatCheckPreallocated(mat, 1);

5158:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5159:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5160:   PetscFunctionReturn(PETSC_SUCCESS);
5161: }

5163: /*@
5164:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5166:   Collective

5168:   Input Parameters:
5169: + mat - the matrix
5170: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5171:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5173:   Output Parameter:
5174: . M - pointer to place new matrix

5176:   Level: intermediate

5178:   Notes:
5179:   You cannot change the nonzero pattern for the parent or child matrix later if you use `MAT_SHARE_NONZERO_PATTERN`.

5181:   If `op` is not `MAT_COPY_VALUES` the numerical values in the new matrix are zeroed.

5183:   May be called with an unassembled input `Mat` if `MAT_DO_NOT_COPY_VALUES` is used, in which case the output `Mat` is unassembled as well.

5185:   When original mat is a product of matrix operation, e.g., an output of `MatMatMult()` or `MatCreateSubMatrix()`, only the matrix data structure of `mat`
5186:   is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated.
5187:   User should not use `MatDuplicate()` to create new matrix `M` if `M` is intended to be reused as the product of matrix operation.

5189: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5190: @*/
5191: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5192: {
5193:   Mat               B;
5194:   VecType           vtype;
5195:   PetscInt          i;
5196:   PetscObject       dm, container_h, container_d;
5197:   PetscErrorCodeFn *viewf;

5199:   PetscFunctionBegin;
5202:   PetscAssertPointer(M, 3);
5203:   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5204:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5205:   MatCheckPreallocated(mat, 1);

5207:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5208:   PetscUseTypeMethod(mat, duplicate, op, M);
5209:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5210:   B = *M;

5212:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5213:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5214:   PetscCall(MatGetVecType(mat, &vtype));
5215:   PetscCall(MatSetVecType(B, vtype));

5217:   B->stencil.dim = mat->stencil.dim;
5218:   B->stencil.noc = mat->stencil.noc;
5219:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5220:     B->stencil.dims[i]   = mat->stencil.dims[i];
5221:     B->stencil.starts[i] = mat->stencil.starts[i];
5222:   }

5224:   B->nooffproczerorows = mat->nooffproczerorows;
5225:   B->nooffprocentries  = mat->nooffprocentries;

5227:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5228:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5229:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5230:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5231:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5232:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5233:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5234:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5235:   PetscFunctionReturn(PETSC_SUCCESS);
5236: }

5238: /*@
5239:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5241:   Logically Collective

5243:   Input Parameter:
5244: . mat - the matrix

5246:   Output Parameter:
5247: . v - the diagonal of the matrix

5249:   Level: intermediate

5251:   Note:
5252:   If `mat` has local sizes `n` x `m`, this routine fills the first `ndiag = min(n, m)` entries
5253:   of `v` with the diagonal values. Thus `v` must have local size of at least `ndiag`. If `v`
5254:   is larger than `ndiag`, the values of the remaining entries are unspecified.

5256:   Currently only correct in parallel for square matrices.

5258: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5259: @*/
5260: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5261: {
5262:   PetscFunctionBegin;
5266:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5267:   MatCheckPreallocated(mat, 1);
5268:   if (PetscDefined(USE_DEBUG)) {
5269:     PetscInt nv, row, col, ndiag;

5271:     PetscCall(VecGetLocalSize(v, &nv));
5272:     PetscCall(MatGetLocalSize(mat, &row, &col));
5273:     ndiag = PetscMin(row, col);
5274:     PetscCheck(nv >= ndiag, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming Mat and Vec. Vec local size %" PetscInt_FMT " < Mat local diagonal length %" PetscInt_FMT, nv, ndiag);
5275:   }

5277:   PetscUseTypeMethod(mat, getdiagonal, v);
5278:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5279:   PetscFunctionReturn(PETSC_SUCCESS);
5280: }

5282: /*@
5283:   MatGetRowMin - Gets the minimum value (of the real part) of each
5284:   row of the matrix

5286:   Logically Collective

5288:   Input Parameter:
5289: . mat - the matrix

5291:   Output Parameters:
5292: + v   - the vector for storing the maximums
5293: - idx - the indices of the column found for each row (optional, pass `NULL` if not needed)

5295:   Level: intermediate

5297:   Note:
5298:   The result of this call are the same as if one converted the matrix to dense format
5299:   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).

5301:   This code is only implemented for a couple of matrix formats.

5303: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5304:           `MatGetRowMax()`
5305: @*/
5306: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5307: {
5308:   PetscFunctionBegin;
5312:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5314:   if (!mat->cmap->N) {
5315:     PetscCall(VecSet(v, PETSC_MAX_REAL));
5316:     if (idx) {
5317:       PetscInt i, m = mat->rmap->n;
5318:       for (i = 0; i < m; i++) idx[i] = -1;
5319:     }
5320:   } else {
5321:     MatCheckPreallocated(mat, 1);
5322:   }
5323:   PetscUseTypeMethod(mat, getrowmin, v, idx);
5324:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5325:   PetscFunctionReturn(PETSC_SUCCESS);
5326: }

5328: /*@
5329:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5330:   row of the matrix

5332:   Logically Collective

5334:   Input Parameter:
5335: . mat - the matrix

5337:   Output Parameters:
5338: + v   - the vector for storing the minimums
5339: - idx - the indices of the column found for each row (or `NULL` if not needed)

5341:   Level: intermediate

5343:   Notes:
5344:   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5345:   row is 0 (the first column).

5347:   This code is only implemented for a couple of matrix formats.

5349: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5350: @*/
5351: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5352: {
5353:   PetscFunctionBegin;
5357:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5358:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

5360:   if (!mat->cmap->N) {
5361:     PetscCall(VecSet(v, 0.0));
5362:     if (idx) {
5363:       PetscInt i, m = mat->rmap->n;
5364:       for (i = 0; i < m; i++) idx[i] = -1;
5365:     }
5366:   } else {
5367:     MatCheckPreallocated(mat, 1);
5368:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5369:     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5370:   }
5371:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5372:   PetscFunctionReturn(PETSC_SUCCESS);
5373: }

5375: /*@
5376:   MatGetRowMax - Gets the maximum value (of the real part) of each
5377:   row of the matrix

5379:   Logically Collective

5381:   Input Parameter:
5382: . mat - the matrix

5384:   Output Parameters:
5385: + v   - the vector for storing the maximums
5386: - idx - the indices of the column found for each row (optional, otherwise pass `NULL`)

5388:   Level: intermediate

5390:   Notes:
5391:   The result of this call are the same as if one converted the matrix to dense format
5392:   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).

5394:   This code is only implemented for a couple of matrix formats.

5396: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5397: @*/
5398: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5399: {
5400:   PetscFunctionBegin;
5404:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5406:   if (!mat->cmap->N) {
5407:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5408:     if (idx) {
5409:       PetscInt i, m = mat->rmap->n;
5410:       for (i = 0; i < m; i++) idx[i] = -1;
5411:     }
5412:   } else {
5413:     MatCheckPreallocated(mat, 1);
5414:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5415:   }
5416:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5417:   PetscFunctionReturn(PETSC_SUCCESS);
5418: }

5420: /*@
5421:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5422:   row of the matrix

5424:   Logically Collective

5426:   Input Parameter:
5427: . mat - the matrix

5429:   Output Parameters:
5430: + v   - the vector for storing the maximums
5431: - idx - the indices of the column found for each row (or `NULL` if not needed)

5433:   Level: intermediate

5435:   Notes:
5436:   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5437:   row is 0 (the first column).

5439:   This code is only implemented for a couple of matrix formats.

5441: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5442: @*/
5443: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5444: {
5445:   PetscFunctionBegin;
5449:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5451:   if (!mat->cmap->N) {
5452:     PetscCall(VecSet(v, 0.0));
5453:     if (idx) {
5454:       PetscInt i, m = mat->rmap->n;
5455:       for (i = 0; i < m; i++) idx[i] = -1;
5456:     }
5457:   } else {
5458:     MatCheckPreallocated(mat, 1);
5459:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5460:     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5461:   }
5462:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5463:   PetscFunctionReturn(PETSC_SUCCESS);
5464: }

5466: /*@
5467:   MatGetRowSumAbs - Gets the sum value (in absolute value) of each row of the matrix

5469:   Logically Collective

5471:   Input Parameter:
5472: . mat - the matrix

5474:   Output Parameter:
5475: . v - the vector for storing the sum

5477:   Level: intermediate

5479:   This code is only implemented for a couple of matrix formats.

5481: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5482: @*/
5483: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5484: {
5485:   PetscFunctionBegin;
5489:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5491:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5492:   else {
5493:     MatCheckPreallocated(mat, 1);
5494:     PetscUseTypeMethod(mat, getrowsumabs, v);
5495:   }
5496:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5497:   PetscFunctionReturn(PETSC_SUCCESS);
5498: }

5500: /*@
5501:   MatGetRowSum - Gets the sum of each row of the matrix

5503:   Logically or Neighborhood Collective

5505:   Input Parameter:
5506: . mat - the matrix

5508:   Output Parameter:
5509: . v - the vector for storing the sum of rows

5511:   Level: intermediate

5513:   Note:
5514:   This code is slow since it is not currently specialized for different formats

5516: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5517: @*/
5518: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5519: {
5520:   Vec ones;

5522:   PetscFunctionBegin;
5526:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5527:   MatCheckPreallocated(mat, 1);
5528:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5529:   PetscCall(VecSet(ones, 1.));
5530:   PetscCall(MatMult(mat, ones, v));
5531:   PetscCall(VecDestroy(&ones));
5532:   PetscFunctionReturn(PETSC_SUCCESS);
5533: }

5535: /*@
5536:   MatTransposeSetPrecursor - Set the matrix from which the second matrix will receive numerical transpose data with a call to `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B)
5537:   when B was not obtained with `MatTranspose`(A,`MAT_INITIAL_MATRIX`,&B)

5539:   Collective

5541:   Input Parameter:
5542: . mat - the matrix to provide the transpose

5544:   Output Parameter:
5545: . B - the matrix to contain the transpose; it MUST have the nonzero structure of the transpose of A or the code will crash or generate incorrect results

5547:   Level: advanced

5549:   Note:
5550:   Normally the use of `MatTranspose`(A, `MAT_REUSE_MATRIX`, &B) requires that `B` was obtained with a call to `MatTranspose`(A, `MAT_INITIAL_MATRIX`, &B). This
5551:   routine allows bypassing that call.

5553: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5554: @*/
5555: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5556: {
5557:   MatState *rb = NULL;

5559:   PetscFunctionBegin;
5560:   PetscCall(PetscNew(&rb));
5561:   rb->id    = ((PetscObject)mat)->id;
5562:   rb->state = 0;
5563:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5564:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5565:   PetscFunctionReturn(PETSC_SUCCESS);
5566: }

5568: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5569: {
5570:   PetscContainer rB                         = NULL;
5571:   MatState      *rb                         = NULL;
5572:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

5574:   PetscFunctionBegin;
5577:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5578:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5579:   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5580:   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5581:   MatCheckPreallocated(mat, 1);
5582:   if (reuse == MAT_REUSE_MATRIX) {
5583:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5584:     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5585:     PetscCall(PetscContainerGetPointer(rB, &rb));
5586:     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5587:     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5588:   }

5590:   if (conjugate) {
5591:     f = mat->ops->hermitiantranspose;
5592:     if (f) PetscCall((*f)(mat, reuse, B));
5593:   }
5594:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5595:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5596:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5597:       PetscUseTypeMethod(mat, transpose, reuse, B);
5598:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5599:     }
5600:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5601:     if (conjugate) PetscCall(MatConjugate(*B));
5602:   }

5604:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5605:   if (reuse != MAT_INPLACE_MATRIX) {
5606:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5607:     PetscCall(PetscContainerGetPointer(rB, &rb));
5608:     rb->state        = ((PetscObject)mat)->state;
5609:     rb->nonzerostate = mat->nonzerostate;
5610:   }
5611:   PetscFunctionReturn(PETSC_SUCCESS);
5612: }

5614: /*@
5615:   MatTranspose - Computes the transpose of a matrix, either in-place or out-of-place.

5617:   Collective

5619:   Input Parameters:
5620: + mat   - the matrix to transpose
5621: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5623:   Output Parameter:
5624: . B - the transpose of the matrix

5626:   Level: intermediate

5628:   Notes:
5629:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

5631:   `MAT_REUSE_MATRIX` uses the `B` matrix obtained from a previous call to this function with `MAT_INITIAL_MATRIX` to store the transpose. If you already have a matrix to contain the
5632:   transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.

5634:   If the nonzero structure of `mat` changed from the previous call to this function with the same matrices an error will be generated for some matrix types.

5636:   Consider using `MatCreateTranspose()` instead if you only need a matrix that behaves like the transpose but don't need the storage to be changed.
5637:   For example, the result of `MatCreateTranspose()` will compute the transpose of the given matrix times a vector for matrix-vector products computed with `MatMult()`.

5639:   If `mat` is unchanged from the last call this function returns immediately without recomputing the result

5641:   If you only need the symbolic transpose of a matrix, and not the numerical values, use `MatTransposeSymbolic()`

5643: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5644:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5645: @*/
5646: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5647: {
5648:   PetscFunctionBegin;
5649:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5650:   PetscFunctionReturn(PETSC_SUCCESS);
5651: }

5653: /*@
5654:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5656:   Collective

5658:   Input Parameter:
5659: . A - the matrix to transpose

5661:   Output Parameter:
5662: . B - the transpose. This is a complete matrix but the numerical portion is invalid. One can call `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B) to compute the
5663:       numerical portion.

5665:   Level: intermediate

5667:   Note:
5668:   This is not supported for many matrix types, use `MatTranspose()` in those cases

5670: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5671: @*/
5672: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5673: {
5674:   PetscFunctionBegin;
5677:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5678:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5679:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5680:   PetscUseTypeMethod(A, transposesymbolic, B);
5681:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5683:   PetscCall(MatTransposeSetPrecursor(A, *B));
5684:   PetscFunctionReturn(PETSC_SUCCESS);
5685: }

5687: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5688: {
5689:   PetscContainer rB;
5690:   MatState      *rb;

5692:   PetscFunctionBegin;
5695:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5696:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5697:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5698:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5699:   PetscCall(PetscContainerGetPointer(rB, &rb));
5700:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5701:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5702:   PetscFunctionReturn(PETSC_SUCCESS);
5703: }

5705: /*@
5706:   MatIsTranspose - Test whether a matrix is another one's transpose,
5707:   or its own, in which case it tests symmetry.

5709:   Collective

5711:   Input Parameters:
5712: + A   - the matrix to test
5713: . B   - the matrix to test against, this can equal the first parameter
5714: - tol - tolerance, differences between entries smaller than this are counted as zero

5716:   Output Parameter:
5717: . flg - the result

5719:   Level: intermediate

5721:   Notes:
5722:   The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5723:   test involves parallel copies of the block off-diagonal parts of the matrix.

5725: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5726: @*/
5727: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5728: {
5729:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5731:   PetscFunctionBegin;
5734:   PetscAssertPointer(flg, 4);
5735:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5736:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5737:   *flg = PETSC_FALSE;
5738:   if (f && g) {
5739:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5740:     PetscCall((*f)(A, B, tol, flg));
5741:   } else {
5742:     MatType mattype;

5744:     PetscCall(MatGetType(f ? B : A, &mattype));
5745:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5746:   }
5747:   PetscFunctionReturn(PETSC_SUCCESS);
5748: }

5750: /*@
5751:   MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.

5753:   Collective

5755:   Input Parameters:
5756: + mat   - the matrix to transpose and complex conjugate
5757: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5759:   Output Parameter:
5760: . B - the Hermitian transpose

5762:   Level: intermediate

5764: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5765: @*/
5766: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5767: {
5768:   PetscFunctionBegin;
5769:   PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5770:   PetscFunctionReturn(PETSC_SUCCESS);
5771: }

5773: /*@
5774:   MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,

5776:   Collective

5778:   Input Parameters:
5779: + A   - the matrix to test
5780: . B   - the matrix to test against, this can equal the first parameter
5781: - tol - tolerance, differences between entries smaller than this are counted as zero

5783:   Output Parameter:
5784: . flg - the result

5786:   Level: intermediate

5788:   Notes:
5789:   Only available for `MATAIJ` matrices.

5791:   The sequential algorithm
5792:   has a running time of the order of the number of nonzeros; the parallel
5793:   test involves parallel copies of the block off-diagonal parts of the matrix.

5795: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5796: @*/
5797: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5798: {
5799:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5801:   PetscFunctionBegin;
5804:   PetscAssertPointer(flg, 4);
5805:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5806:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5807:   if (f && g) {
5808:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5809:     PetscCall((*f)(A, B, tol, flg));
5810:   } else {
5811:     MatType mattype;

5813:     PetscCall(MatGetType(f ? B : A, &mattype));
5814:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5815:   }
5816:   PetscFunctionReturn(PETSC_SUCCESS);
5817: }

5819: /*@
5820:   MatPermute - Creates a new matrix with rows and columns permuted from the
5821:   original.

5823:   Collective

5825:   Input Parameters:
5826: + mat - the matrix to permute
5827: . row - row permutation, each process supplies only the permutation for its rows
5828: - col - column permutation, each process supplies only the permutation for its columns

5830:   Output Parameter:
5831: . B - the permuted matrix

5833:   Level: advanced

5835:   Note:
5836:   The index sets map from `row`/`col` of permuted matrix to `row`/`col` of original matrix.
5837:   The index sets should be on the same communicator as mat and have the same local sizes.
5838:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the permutation does not preserve symmetry.

5840:   Developer Note:
5841:   If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5842:   exploit the fact that `row` and `col` are permutations, consider implementing the
5843:   more general `MatCreateSubMatrix()` instead.

5845: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5846: @*/
5847: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5848: {
5849:   PetscFunctionBegin;
5854:   PetscAssertPointer(B, 4);
5855:   PetscCheckSameComm(mat, 1, row, 2);
5856:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5857:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5858:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5859:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5860:   MatCheckPreallocated(mat, 1);

5862:   if (mat->ops->permute) {
5863:     PetscUseTypeMethod(mat, permute, row, col, B);
5864:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5865:   } else {
5866:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5867:   }
5868:   PetscFunctionReturn(PETSC_SUCCESS);
5869: }

5871: /*@
5872:   MatEqual - Compares two matrices.

5874:   Collective

5876:   Input Parameters:
5877: + A - the first matrix
5878: - B - the second matrix

5880:   Output Parameter:
5881: . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.

5883:   Level: intermediate

5885:   Note:
5886:   If either of the matrix is "matrix-free", meaning the matrix entries are not stored explicitly then equality is determined by comparing
5887:   the results of several matrix-vector product using randomly created vectors, see `MatMultEqual()`.

5889: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5890: @*/
5891: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5892: {
5893:   PetscFunctionBegin;
5898:   PetscAssertPointer(flg, 3);
5899:   PetscCheckSameComm(A, 1, B, 2);
5900:   MatCheckPreallocated(A, 1);
5901:   MatCheckPreallocated(B, 2);
5902:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5903:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5904:   PetscCheck(A->rmap->N == B->rmap->N && A->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N, A->cmap->N,
5905:              B->cmap->N);
5906:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5907:   else PetscCall(MatMultEqual(A, B, 10, flg));
5908:   PetscFunctionReturn(PETSC_SUCCESS);
5909: }

5911: /*@
5912:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5913:   matrices that are stored as vectors. Either of the two scaling
5914:   matrices can be `NULL`.

5916:   Collective

5918:   Input Parameters:
5919: + mat - the matrix to be scaled
5920: . l   - the left scaling vector (or `NULL`)
5921: - r   - the right scaling vector (or `NULL`)

5923:   Level: intermediate

5925:   Note:
5926:   `MatDiagonalScale()` computes $A = LAR$, where
5927:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5928:   The L scales the rows of the matrix, the R scales the columns of the matrix.
5929:   For `MATSEQSBAIJ`, if `l` and `r` are different `Vec` objects, `mat` changes to type `MATSEQBAIJ` because the result is not necessarily symmetric.

5931: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5932: @*/
5933: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5934: {
5935:   PetscBool flg = PETSC_FALSE;

5937:   PetscFunctionBegin;
5940:   if (l) {
5942:     PetscCheckSameComm(mat, 1, l, 2);
5943:   }
5944:   if (r) {
5946:     PetscCheckSameComm(mat, 1, r, 3);
5947:   }
5948:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5949:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5950:   MatCheckPreallocated(mat, 1);
5951:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5953:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5954:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5955:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5956:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5957:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5958:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5959:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5960:       if (!flg) {
5961:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5962:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For MATMPISBAIJ, left and right scaling vectors must be the same");
5963:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5964:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5965:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5966:       }
5967:     }
5968:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5969:       flg = PETSC_FALSE;
5970:       if (l && r) {
5971:         Vec conjugate;

5973:         PetscCall(VecDuplicate(l, &conjugate));
5974:         PetscCall(VecCopy(l, conjugate));
5975:         PetscCall(VecConjugate(conjugate));
5976:         PetscCall(VecEqual(conjugate, r, &flg));
5977:         PetscCall(VecDestroy(&conjugate));
5978:       }
5979:       if (!flg) {
5980:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5981:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For Hermitian MATMPISBAIJ, left and right scaling vectors must be conjugate one of the other");
5982:         mat->hermitian = PETSC_BOOL3_FALSE;
5983:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5984:       }
5985:     }
5986:   }
5987:   PetscFunctionReturn(PETSC_SUCCESS);
5988: }

5990: /*@
5991:   MatScale - Scales all elements of a matrix by a given number.

5993:   Logically Collective

5995:   Input Parameters:
5996: + mat - the matrix to be scaled
5997: - a   - the scaling value

5999:   Level: intermediate

6001: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
6002: @*/
6003: PetscErrorCode MatScale(Mat mat, PetscScalar a)
6004: {
6005:   PetscFunctionBegin;
6008:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6009:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6011:   MatCheckPreallocated(mat, 1);

6013:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6014:   if (a != (PetscScalar)1.0) {
6015:     PetscUseTypeMethod(mat, scale, a);
6016:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6017:   }
6018:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6019:   PetscFunctionReturn(PETSC_SUCCESS);
6020: }

6022: /*@
6023:   MatNorm - Calculates various norms of a matrix.

6025:   Collective

6027:   Input Parameters:
6028: + mat  - the matrix
6029: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

6031:   Output Parameter:
6032: . nrm - the resulting norm

6034:   Level: intermediate

6036: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
6037: @*/
6038: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
6039: {
6040:   PetscFunctionBegin;
6044:   PetscAssertPointer(nrm, 3);

6046:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6047:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6048:   MatCheckPreallocated(mat, 1);

6050:   PetscUseTypeMethod(mat, norm, type, nrm);
6051:   PetscFunctionReturn(PETSC_SUCCESS);
6052: }

6054: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6055: {
6056:   PetscScalar *ax, nm1;
6057:   PetscInt     st, en, n;

6059:   PetscFunctionBegin;
6060:   PetscCall(VecGetSize(x, &n));
6061:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6062:   nm1 = n - 1;
6063:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6064:   PetscCall(VecGetArrayWrite(x, &ax));
6065:   for (PetscInt i = st; i < en; i++) {
6066:     const PetscInt    ii = i - st;
6067:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6069:     ax[ii] = s * (1.0 + i / nm1);
6070:   }
6071:   PetscCall(VecRestoreArrayWrite(x, &ax));
6072:   PetscFunctionReturn(PETSC_SUCCESS);
6073: }

6075: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6076: {
6077:   Vec         x, y;
6078:   PetscReal   normx, normy;
6079:   PetscInt    i, N;
6080:   PetscRandom rnd;

6082:   PetscFunctionBegin;
6083:   if (maxit < 0) maxit = 1;
6084:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6085:   PetscCall(PetscRandomSetFromOptions(rnd));
6086:   PetscCall(MatCreateVecs(A, &x, &y));
6087:   PetscCall(VecBindToCPU(x, boundtocpu));
6088:   PetscCall(VecBindToCPU(y, boundtocpu));
6089:   PetscCall(VecGetSize(x, &N));
6090:   *n = 0.0;
6091:   for (i = 0; i < maxit; i++) {
6092:     PetscCall(VecSetRandom(x, rnd));
6093:     switch (normtype) {
6094:     case NORM_1:
6095:       PetscCall(VecNorm(x, NORM_1, &normx));
6096:       if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6097:       break;
6098:     case NORM_INFINITY:
6099:       PetscCall(VecShift(x, -0.5));
6100:       PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6101:       break;
6102:     case NORM_2:
6103:       PetscCall(VecNormalize(x, NULL));
6104:       break;
6105:     default:
6106:       PetscUnreachable();
6107:     }
6108:     PetscCall(MatMult(A, x, y));
6109:     PetscCall(VecNorm(y, normtype, &normy));
6110:     *n = PetscMax(*n, normy);
6111:     PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6112:   }
6113:   PetscCall(VecDestroy(&x));
6114:   PetscCall(VecDestroy(&y));
6115:   PetscCall(PetscRandomDestroy(&rnd));
6116:   PetscFunctionReturn(PETSC_SUCCESS);
6117: }

6119: /*@
6120:   MatNormApproximate - Approximate the norm of a matrix.

6122:   Collective

6124:   Input Parameters:
6125: + A        - the matrix
6126: . normtype - the `NormType`
6127: - maxit    - maximum number of iterations to use

6129:   Output Parameter:
6130: . n - the norm estimate

6132:   Level: intermediate

6134:   Notes:
6135:   Does not need access to the matrix entries; it just performs matrix-vector and transposed matrix-vector products {cite}`Higham1992`, {cite}`doi:10.1137/S0895479899356080`.

6137:   If `maxit` is negative, a default number of iterations (10 for `NORM_1` and `NORM_INFINITY` and 20 for `NORM_2`) is performed.

6139: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6140: @*/
6141: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6142: {
6143:   Vec         x, y, w, z;
6144:   PetscReal   normz, adot;
6145:   PetscScalar dot;
6146:   PetscInt    i, j, N, jold = -1;
6147:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

6149:   PetscFunctionBegin;
6154:   PetscAssertPointer(n, 4);
6155: #if PetscDefined(HAVE_DEVICE)
6156:   boundtocpu = A->boundtocpu;
6157: #endif
6158:   PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6159:   switch (normtype) {
6160:   case NORM_INFINITY:
6161:   case NORM_1:
6162:     if (!hasop) {
6163:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6164:       i = maxit;
6165:       break;
6166:     } else {
6167:       PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6168:       if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6169:       else {
6170:         Mat B;

6172:         PetscCall(MatCreateHermitianTranspose(A, &B));
6173:         A = B;
6174:       }
6175:     }
6176:     if (maxit < 0) maxit = 10; /* pure guess */
6177:     PetscCall(MatCreateVecs(A, &x, &y));
6178:     PetscCall(MatCreateVecs(A, &z, &w));
6179:     PetscCall(VecBindToCPU(x, boundtocpu));
6180:     PetscCall(VecBindToCPU(y, boundtocpu));
6181:     PetscCall(VecBindToCPU(z, boundtocpu));
6182:     PetscCall(VecBindToCPU(w, boundtocpu));
6183:     PetscCall(VecGetSize(x, &N));
6184:     PetscCall(VecSet(x, 1. / N));
6185:     *n = 0.0;
6186:     for (i = 0; i < maxit; i++) {
6187:       PetscCall(MatMult(A, x, y));
6188:       PetscCall(VecNorm(y, NORM_1, n));
6189:       if (PetscDefined(USE_COMPLEX)) {
6190:         PetscCall(VecCopy(y, w));
6191:         PetscCall(VecAbs(w));
6192:         PetscCall(VecPointwiseDivide(w, y, w));
6193:       } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6194:       PetscCall(MatMultHermitianTranspose(A, w, z));
6195:       PetscCall(VecRealPart(z));
6196:       PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6197:       PetscCall(VecDot(x, z, &dot));
6198:       adot = PetscAbsScalar(dot);
6199:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6200:       if (normz <= adot && i > 0) {
6201:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6202:         break;
6203:       }
6204:       PetscCall(VecAbs(z));
6205:       PetscCall(VecMax(z, &j, &normz));
6206:       if (j == jold) {
6207:         PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6208:         break;
6209:       }
6210:       jold = j;
6211:       if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6212:     }
6213:     /* last check */
6214:     if (N > 1) {
6215:       PetscReal ny;

6217:       PetscCall(VecSetFinalNormApp_Private(x));
6218:       PetscCall(MatMult(A, x, y));
6219:       PetscCall(VecNorm(y, NORM_1, &ny));
6220:       ny = 2 * ny / (3 * N);
6221:       PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6222:       *n = PetscMax(*n, ny);
6223:     }
6224:     PetscCall(MatDestroy(&A));
6225:     PetscCall(VecDestroy(&x));
6226:     PetscCall(VecDestroy(&w));
6227:     PetscCall(VecDestroy(&y));
6228:     PetscCall(VecDestroy(&z));
6229:     break;
6230:   case NORM_2:
6231:     if (!hasop) {
6232:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6233:       i = maxit;
6234:       break;
6235:     }
6236:     if (maxit < 0) maxit = 20; /* pure guess */
6237:     PetscCall(MatCreateVecs(A, &x, &y));
6238:     PetscCall(MatCreateVecs(A, &z, NULL));
6239:     PetscCall(VecBindToCPU(x, boundtocpu));
6240:     PetscCall(VecBindToCPU(y, boundtocpu));
6241:     PetscCall(VecBindToCPU(z, boundtocpu));
6242:     PetscCall(VecSetRandom(x, NULL));
6243:     PetscCall(VecNormalize(x, NULL));
6244:     *n = 0.0;
6245:     for (i = 0; i < maxit; i++) {
6246:       PetscCall(MatMult(A, x, y));
6247:       PetscCall(VecNormalize(y, n));
6248:       PetscCall(MatMultHermitianTranspose(A, y, z));
6249:       PetscCall(VecNorm(z, NORM_2, &normz));
6250:       PetscCall(VecDot(x, z, &dot));
6251:       adot = PetscAbsScalar(dot);
6252:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6253:       if (normz <= adot) {
6254:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6255:         break;
6256:       }
6257:       if (i < maxit - 1) {
6258:         Vec t;

6260:         PetscCall(VecNormalize(z, NULL));
6261:         t = x;
6262:         x = z;
6263:         z = t;
6264:       }
6265:     }
6266:     PetscCall(VecDestroy(&x));
6267:     PetscCall(VecDestroy(&y));
6268:     PetscCall(VecDestroy(&z));
6269:     break;
6270:   default:
6271:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6272:   }
6273:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6274:   PetscFunctionReturn(PETSC_SUCCESS);
6275: }

6277: /*
6278:      This variable is used to prevent counting of MatAssemblyBegin() that
6279:    are called from within a MatAssemblyEnd().
6280: */
6281: static PetscInt MatAssemblyEnd_InUse = 0;
6282: /*@
6283:   MatAssemblyBegin - Begins assembling the matrix. This routine should
6284:   be called after completing all calls to `MatSetValues()`.

6286:   Collective

6288:   Input Parameters:
6289: + mat  - the matrix
6290: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6292:   Level: beginner

6294:   Notes:
6295:   `MatSetValues()` generally caches the values that belong to other MPI processes. The matrix is ready to
6296:   use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.

6298:   Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
6299:   in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
6300:   using the matrix.

6302:   ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
6303:   same flag of `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY` for all processes. Thus you CANNOT locally change from `ADD_VALUES` to `INSERT_VALUES`, that is
6304:   a global collective operation requiring all processes that share the matrix.

6306:   Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
6307:   out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
6308:   before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.

6310: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6311: @*/
6312: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6313: {
6314:   PetscFunctionBegin;
6317:   MatCheckPreallocated(mat, 1);
6318:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6319:   if (mat->assembled) {
6320:     mat->was_assembled = PETSC_TRUE;
6321:     mat->assembled     = PETSC_FALSE;
6322:   }

6324:   if (!MatAssemblyEnd_InUse) {
6325:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6326:     PetscTryTypeMethod(mat, assemblybegin, type);
6327:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6328:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6329:   PetscFunctionReturn(PETSC_SUCCESS);
6330: }

6332: /*@
6333:   MatAssembled - Indicates if a matrix has been assembled and is ready for
6334:   use; for example, in matrix-vector product.

6336:   Not Collective

6338:   Input Parameter:
6339: . mat - the matrix

6341:   Output Parameter:
6342: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6344:   Level: advanced

6346: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6347: @*/
6348: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6349: {
6350:   PetscFunctionBegin;
6352:   PetscAssertPointer(assembled, 2);
6353:   *assembled = mat->assembled;
6354:   PetscFunctionReturn(PETSC_SUCCESS);
6355: }

6357: /*@
6358:   MatAssemblyEnd - Completes assembling the matrix. This routine should
6359:   be called after `MatAssemblyBegin()`.

6361:   Collective

6363:   Input Parameters:
6364: + mat  - the matrix
6365: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6367:   Options Database Key:
6368: . -mat_view viewer_specification - Displays the matrix during this function call. See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

6370:   Level: beginner

6372: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6373:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`, `PetscOptionsCreateViewer()`
6374: @*/
6375: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6376: {
6377:   static PetscInt inassm = 0;
6378:   PetscBool       flg    = PETSC_FALSE;

6380:   PetscFunctionBegin;

6384:   inassm++;
6385:   MatAssemblyEnd_InUse++;
6386:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6387:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6388:     PetscTryTypeMethod(mat, assemblyend, type);
6389:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6390:   } else PetscTryTypeMethod(mat, assemblyend, type);

6392:   /* Flush assembly is not a true assembly */
6393:   if (type != MAT_FLUSH_ASSEMBLY) {
6394:     if (mat->num_ass) {
6395:       if (!mat->symmetry_eternal) {
6396:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6397:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6398:       }
6399:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6400:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6401:     }
6402:     mat->num_ass++;
6403:     mat->assembled        = PETSC_TRUE;
6404:     mat->ass_nonzerostate = mat->nonzerostate;
6405:   }

6407:   mat->insertmode = NOT_SET_VALUES;
6408:   MatAssemblyEnd_InUse--;
6409:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6410:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6411:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6413:     if (mat->checksymmetryonassembly) {
6414:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6415:       if (flg) {
6416:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6417:       } else {
6418:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6419:       }
6420:     }
6421:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6422:   }
6423:   inassm--;
6424:   PetscFunctionReturn(PETSC_SUCCESS);
6425: }

6427: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6428: /*@
6429:   MatSetOption - Sets a parameter option for a matrix. Some options
6430:   may be specific to certain storage formats. Some options
6431:   determine how values will be inserted (or added). Sorted,
6432:   row-oriented input will generally assemble the fastest. The default
6433:   is row-oriented.

6435:   Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`

6437:   Input Parameters:
6438: + mat - the matrix
6439: . op  - the option, one of those listed below (and possibly others),
6440: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6442:   Options Describing Matrix Structure:
6443: + `MAT_SPD`                         - symmetric positive definite
6444: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6445: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6446: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6447: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6448: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6449: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

6451:    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6452:    do not need to be computed (usually at a high cost)

6454:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6455:    Insert a logically dense subblock, which can be
6456: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6458:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6459:    nothing to do with how the data is stored internally in the matrix
6460:    data structure.

6462:    When (re)assembling a matrix, we can restrict the input for
6463:    efficiency/debugging purposes. These options include
6464: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6465: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6466: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-process entries
6467: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6468: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6469: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6470:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6471:                                       performance for very large process counts.
6472: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6473:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6474:                                       functions, instead sending only neighbor messages.

6476:   Level: intermediate

6478:   Notes:
6479:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6481:   Some options are relevant only for particular matrix types and
6482:   are thus ignored by others. Other options are not supported by
6483:   certain matrix types and will generate an error message if set.

6485:   If using Fortran to compute a matrix, one may need to
6486:   use the column-oriented option (or convert to the row-oriented
6487:   format).

6489:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6490:   that would generate a new entry in the nonzero structure is instead
6491:   ignored. Thus, if memory has not already been allocated for this particular
6492:   data, then the insertion is ignored. For dense matrices, in which
6493:   the entire array is allocated, no entries are ever ignored.
6494:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6496:   `MAT_NEW_NONZERO_LOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6497:   that would generate a new entry in the nonzero structure instead produces
6498:   an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats only.) If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6500:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6501:   that would generate a new entry that has not been preallocated will
6502:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6503:   only.) This is a useful flag when debugging matrix memory preallocation.
6504:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6506:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6507:   other processes should be dropped, rather than stashed.
6508:   This is useful if you know that the "owning" process is also
6509:   always generating the correct matrix entries, so that PETSc need
6510:   not transfer duplicate entries generated on another process.

6512:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6513:   searches during matrix assembly. When this flag is set, the hash table
6514:   is created during the first matrix assembly. This hash table is
6515:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6516:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6517:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6518:   supported by `MATMPIBAIJ` format only.

6520:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6521:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6523:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6524:   a zero location in the matrix

6526:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6528:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6529:   zero row routines and thus improves performance for very large process counts.

6531:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6532:   part of the matrix (since they should match the upper triangular part).

6534:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6535:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6536:   with finite difference schemes with non-periodic boundary conditions.

6538:   Developer Note:
6539:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6540:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6541:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6542:   not changed.

6544: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6545: @*/
6546: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6547: {
6548:   PetscFunctionBegin;
6550:   if (op > 0) {
6553:   }

6555:   PetscCheck(((int)op) > MAT_OPTION_MIN && ((int)op) < MAT_OPTION_MAX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Options %d is out of range", (int)op);

6557:   switch (op) {
6558:   case MAT_FORCE_DIAGONAL_ENTRIES:
6559:     mat->force_diagonals = flg;
6560:     PetscFunctionReturn(PETSC_SUCCESS);
6561:   case MAT_NO_OFF_PROC_ENTRIES:
6562:     mat->nooffprocentries = flg;
6563:     PetscFunctionReturn(PETSC_SUCCESS);
6564:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6565:     mat->assembly_subset = flg;
6566:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6567: #if !PetscDefined(HAVE_MPIUNI)
6568:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6569: #endif
6570:       mat->stash.first_assembly_done = PETSC_FALSE;
6571:     }
6572:     PetscFunctionReturn(PETSC_SUCCESS);
6573:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6574:     mat->nooffproczerorows = flg;
6575:     PetscFunctionReturn(PETSC_SUCCESS);
6576:   case MAT_SPD:
6577:     if (flg) {
6578:       mat->spd                    = PETSC_BOOL3_TRUE;
6579:       mat->symmetric              = PETSC_BOOL3_TRUE;
6580:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6581: #if !PetscDefined(USE_COMPLEX)
6582:       mat->hermitian = PETSC_BOOL3_TRUE;
6583: #endif
6584:     } else {
6585:       mat->spd = PETSC_BOOL3_FALSE;
6586:     }
6587:     break;
6588:   case MAT_SYMMETRIC:
6589:     mat->symmetric = PetscBoolToBool3(flg);
6590:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6591: #if !PetscDefined(USE_COMPLEX)
6592:     mat->hermitian = PetscBoolToBool3(flg);
6593: #endif
6594:     break;
6595:   case MAT_HERMITIAN:
6596:     mat->hermitian = PetscBoolToBool3(flg);
6597:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6598: #if !PetscDefined(USE_COMPLEX)
6599:     mat->symmetric = PetscBoolToBool3(flg);
6600: #endif
6601:     break;
6602:   case MAT_STRUCTURALLY_SYMMETRIC:
6603:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6604:     break;
6605:   case MAT_SYMMETRY_ETERNAL:
6606:     PetscCheck(mat->symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SYMMETRY_ETERNAL without first setting MAT_SYMMETRIC to true or false");
6607:     mat->symmetry_eternal = flg;
6608:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6609:     break;
6610:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6611:     PetscCheck(mat->structurally_symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_STRUCTURAL_SYMMETRY_ETERNAL without first setting MAT_STRUCTURALLY_SYMMETRIC to true or false");
6612:     mat->structural_symmetry_eternal = flg;
6613:     break;
6614:   case MAT_SPD_ETERNAL:
6615:     PetscCheck(mat->spd != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SPD_ETERNAL without first setting MAT_SPD to true or false");
6616:     mat->spd_eternal = flg;
6617:     if (flg) {
6618:       mat->structural_symmetry_eternal = PETSC_TRUE;
6619:       mat->symmetry_eternal            = PETSC_TRUE;
6620:     }
6621:     break;
6622:   case MAT_STRUCTURE_ONLY:
6623:     mat->structure_only = flg;
6624:     break;
6625:   case MAT_SORTED_FULL:
6626:     mat->sortedfull = flg;
6627:     break;
6628:   default:
6629:     break;
6630:   }
6631:   PetscCheck((op != MAT_ROW_ORIENTED) || ((PetscObject)mat)->type_name, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "The matrix type must be set (MatSetType()) before setting this option");
6632:   PetscTryTypeMethod(mat, setoption, op, flg);
6633:   PetscFunctionReturn(PETSC_SUCCESS);
6634: }

6636: /*@
6637:   MatGetOption - Gets a parameter option that has been set for a matrix.

6639:   Logically Collective

6641:   Input Parameters:
6642: + mat - the matrix
6643: - op  - the option, this only responds to certain options, check the code for which ones

6645:   Output Parameter:
6646: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6648:   Level: intermediate

6650:   Notes:
6651:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6653:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6654:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6656: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6657:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6658: @*/
6659: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6660: {
6661:   PetscFunctionBegin;

6665:   PetscCheck(((int)op) > MAT_OPTION_MIN && ((int)op) < MAT_OPTION_MAX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Options %d is out of range", (int)op);
6666:   PetscCheck(((PetscObject)mat)->type_name, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_TYPENOTSET, "Cannot get options until type and size have been set, see MatSetType() and MatSetSizes()");

6668:   switch (op) {
6669:   case MAT_NO_OFF_PROC_ENTRIES:
6670:     *flg = mat->nooffprocentries;
6671:     break;
6672:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6673:     *flg = mat->nooffproczerorows;
6674:     break;
6675:   case MAT_SYMMETRIC:
6676:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6677:     break;
6678:   case MAT_HERMITIAN:
6679:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6680:     break;
6681:   case MAT_STRUCTURALLY_SYMMETRIC:
6682:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6683:     break;
6684:   case MAT_SPD:
6685:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6686:     break;
6687:   case MAT_SYMMETRY_ETERNAL:
6688:     *flg = mat->symmetry_eternal;
6689:     break;
6690:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6691:     *flg = mat->symmetry_eternal;
6692:     break;
6693:   default:
6694:     break;
6695:   }
6696:   PetscFunctionReturn(PETSC_SUCCESS);
6697: }

6699: /*@
6700:   MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6701:   this routine retains the old nonzero structure.

6703:   Logically Collective

6705:   Input Parameter:
6706: . mat - the matrix

6708:   Level: intermediate

6710:   Note:
6711:   If the matrix was not preallocated then a default, likely poor preallocation will be set in the matrix, so this should be called after the preallocation phase.
6712:   See the Performance chapter of the users manual for information on preallocating matrices.

6714: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6715: @*/
6716: PetscErrorCode MatZeroEntries(Mat mat)
6717: {
6718:   PetscFunctionBegin;
6721:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6722:   PetscCheck(mat->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for matrices where you have set values but not yet assembled");
6723:   MatCheckPreallocated(mat, 1);

6725:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6726:   PetscUseTypeMethod(mat, zeroentries);
6727:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6728:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6729:   PetscFunctionReturn(PETSC_SUCCESS);
6730: }

6732: /*@
6733:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6734:   of a set of rows and columns of a matrix.

6736:   Collective

6738:   Input Parameters:
6739: + mat     - the matrix
6740: . numRows - the number of rows/columns to zero
6741: . rows    - the global row indices
6742: . diag    - value put in the diagonal of the eliminated rows
6743: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6744: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6746:   Level: intermediate

6748:   Notes:
6749:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6751:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6752:   The other entries of `b` will be adjusted by the known values of `x` times the corresponding matrix entries in the columns that are being eliminated

6754:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6755:   Krylov method to take advantage of the known solution on the zeroed rows.

6757:   For the parallel case, all processes that share the matrix (i.e.,
6758:   those in the communicator used for matrix creation) MUST call this
6759:   routine, regardless of whether any rows being zeroed are owned by
6760:   them.

6762:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6763:   removes them from the nonzero pattern. The nonzero pattern of the matrix can still change if a nonzero needs to be inserted on a diagonal entry that was previously
6764:   missing.

6766:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6767:   list only rows local to itself).

6769:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6771: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6772:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6773: @*/
6774: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6775: {
6776:   PetscFunctionBegin;
6779:   if (numRows) PetscAssertPointer(rows, 3);
6780:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6781:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6782:   MatCheckPreallocated(mat, 1);

6784:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6785:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6786:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6787:   PetscFunctionReturn(PETSC_SUCCESS);
6788: }

6790: /*@
6791:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6792:   of a set of rows and columns of a matrix.

6794:   Collective

6796:   Input Parameters:
6797: + mat  - the matrix
6798: . is   - the rows to zero
6799: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6800: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6801: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6803:   Level: intermediate

6805:   Note:
6806:   See `MatZeroRowsColumns()` for details on how this routine operates.

6808: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6809:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6810: @*/
6811: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6812: {
6813:   PetscInt        numRows;
6814:   const PetscInt *rows;

6816:   PetscFunctionBegin;
6821:   PetscCall(ISGetLocalSize(is, &numRows));
6822:   PetscCall(ISGetIndices(is, &rows));
6823:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6824:   PetscCall(ISRestoreIndices(is, &rows));
6825:   PetscFunctionReturn(PETSC_SUCCESS);
6826: }

6828: /*@
6829:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6830:   of a set of rows of a matrix.

6832:   Collective

6834:   Input Parameters:
6835: + mat     - the matrix
6836: . numRows - the number of rows to zero
6837: . rows    - the global row indices
6838: . diag    - value put in the diagonal of the zeroed rows
6839: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6840: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6842:   Level: intermediate

6844:   Notes:
6845:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6847:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6849:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6850:   Krylov method to take advantage of the known solution on the zeroed rows.

6852:   May be followed by using a `PC` of type `PCREDISTRIBUTE` to solve the reduced problem (`PCDISTRIBUTE` completely eliminates the zeroed rows and their corresponding columns)
6853:   from the matrix.

6855:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6856:   but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6857:   formats this does not alter the nonzero structure.

6859:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6860:   of the matrix is not changed the values are
6861:   merely zeroed.

6863:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6864:   formats can optionally remove the main diagonal entry from the
6865:   nonzero structure as well, by passing 0.0 as the final argument).

6867:   For the parallel case, all processes that share the matrix (i.e.,
6868:   those in the communicator used for matrix creation) MUST call this
6869:   routine, regardless of whether any rows being zeroed are owned by
6870:   them.

6872:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6873:   list only rows local to itself).

6875:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6876:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6878: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6879:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6880: @*/
6881: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6882: {
6883:   PetscFunctionBegin;
6886:   if (numRows) PetscAssertPointer(rows, 3);
6887:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6888:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6889:   MatCheckPreallocated(mat, 1);

6891:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6892:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6893:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6894:   PetscFunctionReturn(PETSC_SUCCESS);
6895: }

6897: /*@
6898:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6899:   of a set of rows of a matrix indicated by an `IS`

6901:   Collective

6903:   Input Parameters:
6904: + mat  - the matrix
6905: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6906: . diag - value put in all diagonals of eliminated rows
6907: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6908: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6910:   Level: intermediate

6912:   Note:
6913:   See `MatZeroRows()` for details on how this routine operates.

6915: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6916:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6917: @*/
6918: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6919: {
6920:   PetscInt        numRows = 0;
6921:   const PetscInt *rows    = NULL;

6923:   PetscFunctionBegin;
6926:   if (is) {
6928:     PetscCall(ISGetLocalSize(is, &numRows));
6929:     PetscCall(ISGetIndices(is, &rows));
6930:   }
6931:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6932:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6933:   PetscFunctionReturn(PETSC_SUCCESS);
6934: }

6936: /*@
6937:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6938:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6940:   Collective

6942:   Input Parameters:
6943: + mat     - the matrix
6944: . numRows - the number of rows to remove
6945: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6946: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6947: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6948: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6950:   Level: intermediate

6952:   Notes:
6953:   See `MatZeroRows()` for details on how this routine operates.

6955:   The grid coordinates are across the entire grid, not just the local portion

6957:   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6958:   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6959:   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6960:   `DM_BOUNDARY_PERIODIC` boundary type.

6962:   For indices that don't mean anything for your case (like the `k` index when working in 2d) or the `c` index when you have
6963:   a single value per point) you can skip filling those indices.

6965:   Fortran Note:
6966:   `idxm` and `idxn` should be declared as
6967: .vb
6968:     MatStencil idxm(4, m)
6969: .ve
6970:   and the values inserted using
6971: .vb
6972:     idxm(MatStencil_i, 1) = i
6973:     idxm(MatStencil_j, 1) = j
6974:     idxm(MatStencil_k, 1) = k
6975:     idxm(MatStencil_c, 1) = c
6976:    etc
6977: .ve

6979: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6980:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6981: @*/
6982: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6983: {
6984:   PetscInt  dim    = mat->stencil.dim;
6985:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6986:   PetscInt *dims   = mat->stencil.dims + 1;
6987:   PetscInt *starts = mat->stencil.starts;
6988:   PetscInt *dxm    = (PetscInt *)rows;
6989:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6991:   PetscFunctionBegin;
6994:   if (numRows) PetscAssertPointer(rows, 3);

6996:   PetscCall(PetscMalloc1(numRows, &jdxm));
6997:   for (i = 0; i < numRows; ++i) {
6998:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6999:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7000:     /* Local index in X dir */
7001:     tmp = *dxm++ - starts[0];
7002:     /* Loop over remaining dimensions */
7003:     for (j = 0; j < dim - 1; ++j) {
7004:       /* If nonlocal, set index to be negative */
7005:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7006:       /* Update local index */
7007:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7008:     }
7009:     /* Skip component slot if necessary */
7010:     if (mat->stencil.noc) dxm++;
7011:     /* Local row number */
7012:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7013:   }
7014:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
7015:   PetscCall(PetscFree(jdxm));
7016:   PetscFunctionReturn(PETSC_SUCCESS);
7017: }

7019: /*@
7020:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
7021:   of a set of rows and columns of a matrix.

7023:   Collective

7025:   Input Parameters:
7026: + mat     - the matrix
7027: . numRows - the number of rows/columns to remove
7028: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
7029: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
7030: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7031: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7033:   Level: intermediate

7035:   Notes:
7036:   See `MatZeroRowsColumns()` for details on how this routine operates.

7038:   The grid coordinates are across the entire grid, not just the local portion

7040:   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
7041:   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
7042:   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
7043:   `DM_BOUNDARY_PERIODIC` boundary type.

7045:   For indices that don't mean anything for your case (like the `k` index when working in 2d) or the `c` index when you have
7046:   a single value per point) you can skip filling those indices.

7048:   Fortran Note:
7049:   `idxm` and `idxn` should be declared as
7050: .vb
7051:     MatStencil idxm(4, m)
7052: .ve
7053:   and the values inserted using
7054: .vb
7055:     idxm(MatStencil_i, 1) = i
7056:     idxm(MatStencil_j, 1) = j
7057:     idxm(MatStencil_k, 1) = k
7058:     idxm(MatStencil_c, 1) = c
7059:     etc
7060: .ve

7062: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7063:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7064: @*/
7065: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7066: {
7067:   PetscInt  dim    = mat->stencil.dim;
7068:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7069:   PetscInt *dims   = mat->stencil.dims + 1;
7070:   PetscInt *starts = mat->stencil.starts;
7071:   PetscInt *dxm    = (PetscInt *)rows;
7072:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7074:   PetscFunctionBegin;
7077:   if (numRows) PetscAssertPointer(rows, 3);

7079:   PetscCall(PetscMalloc1(numRows, &jdxm));
7080:   for (i = 0; i < numRows; ++i) {
7081:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7082:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7083:     /* Local index in X dir */
7084:     tmp = *dxm++ - starts[0];
7085:     /* Loop over remaining dimensions */
7086:     for (j = 0; j < dim - 1; ++j) {
7087:       /* If nonlocal, set index to be negative */
7088:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7089:       /* Update local index */
7090:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7091:     }
7092:     /* Skip component slot if necessary */
7093:     if (mat->stencil.noc) dxm++;
7094:     /* Local row number */
7095:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7096:   }
7097:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7098:   PetscCall(PetscFree(jdxm));
7099:   PetscFunctionReturn(PETSC_SUCCESS);
7100: }

7102: /*@
7103:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7104:   of a set of rows of a matrix; using local numbering of rows.

7106:   Collective

7108:   Input Parameters:
7109: + mat     - the matrix
7110: . numRows - the number of rows to remove
7111: . rows    - the local row indices
7112: . diag    - value put in all diagonals of eliminated rows
7113: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7114: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7116:   Level: intermediate

7118:   Notes:
7119:   Before calling `MatZeroRowsLocal()`, the user must first set the
7120:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7122:   See `MatZeroRows()` for details on how this routine operates.

7124: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7125:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7126: @*/
7127: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7128: {
7129:   PetscFunctionBegin;
7132:   if (numRows) PetscAssertPointer(rows, 3);
7133:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7134:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7135:   MatCheckPreallocated(mat, 1);

7137:   if (mat->ops->zerorowslocal) {
7138:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7139:   } else {
7140:     IS        is, newis;
7141:     PetscInt *newRows, nl = 0;

7143:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7144:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7145:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7146:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7147:     for (PetscInt i = 0; i < numRows; i++)
7148:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7149:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7150:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7151:     PetscCall(ISDestroy(&newis));
7152:     PetscCall(ISDestroy(&is));
7153:   }
7154:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7155:   PetscFunctionReturn(PETSC_SUCCESS);
7156: }

7158: /*@
7159:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7160:   of a set of rows of a matrix; using local numbering of rows.

7162:   Collective

7164:   Input Parameters:
7165: + mat  - the matrix
7166: . is   - index set of rows to remove
7167: . diag - value put in all diagonals of eliminated rows
7168: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7169: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7171:   Level: intermediate

7173:   Notes:
7174:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7175:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7177:   See `MatZeroRows()` for details on how this routine operates.

7179: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7180:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7181: @*/
7182: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7183: {
7184:   PetscInt        numRows;
7185:   const PetscInt *rows;

7187:   PetscFunctionBegin;
7191:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7192:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7193:   MatCheckPreallocated(mat, 1);

7195:   PetscCall(ISGetLocalSize(is, &numRows));
7196:   PetscCall(ISGetIndices(is, &rows));
7197:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7198:   PetscCall(ISRestoreIndices(is, &rows));
7199:   PetscFunctionReturn(PETSC_SUCCESS);
7200: }

7202: /*@
7203:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7204:   of a set of rows and columns of a matrix; using local numbering of rows.

7206:   Collective

7208:   Input Parameters:
7209: + mat     - the matrix
7210: . numRows - the number of rows to remove
7211: . rows    - the global row indices
7212: . diag    - value put in all diagonals of eliminated rows
7213: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7214: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7216:   Level: intermediate

7218:   Notes:
7219:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7220:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7222:   See `MatZeroRowsColumns()` for details on how this routine operates.

7224: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7225:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7226: @*/
7227: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7228: {
7229:   PetscFunctionBegin;
7232:   if (numRows) PetscAssertPointer(rows, 3);
7233:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7234:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7235:   MatCheckPreallocated(mat, 1);

7237:   if (mat->ops->zerorowscolumnslocal) {
7238:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7239:   } else {
7240:     IS        is, newis;
7241:     PetscInt *newRows, nl = 0;

7243:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7244:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7245:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7246:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7247:     for (PetscInt i = 0; i < numRows; i++)
7248:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7249:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7250:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7251:     PetscCall(ISDestroy(&newis));
7252:     PetscCall(ISDestroy(&is));
7253:   }
7254:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7255:   PetscFunctionReturn(PETSC_SUCCESS);
7256: }

7258: /*@
7259:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7260:   of a set of rows and columns of a matrix; using local numbering of rows.

7262:   Collective

7264:   Input Parameters:
7265: + mat  - the matrix
7266: . is   - index set of rows to remove
7267: . diag - value put in all diagonals of eliminated rows
7268: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7269: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7271:   Level: intermediate

7273:   Notes:
7274:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7275:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7277:   See `MatZeroRowsColumns()` for details on how this routine operates.

7279: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7280:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7281: @*/
7282: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7283: {
7284:   PetscInt        numRows;
7285:   const PetscInt *rows;

7287:   PetscFunctionBegin;
7291:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7292:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7293:   MatCheckPreallocated(mat, 1);

7295:   PetscCall(ISGetLocalSize(is, &numRows));
7296:   PetscCall(ISGetIndices(is, &rows));
7297:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7298:   PetscCall(ISRestoreIndices(is, &rows));
7299:   PetscFunctionReturn(PETSC_SUCCESS);
7300: }

7302: /*@
7303:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7305:   Not Collective

7307:   Input Parameter:
7308: . mat - the matrix

7310:   Output Parameters:
7311: + m - the number of global rows
7312: - n - the number of global columns

7314:   Level: beginner

7316:   Note:
7317:   Both output parameters can be `NULL` on input.

7319: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7320: @*/
7321: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7322: {
7323:   PetscFunctionBegin;
7325:   if (m) *m = mat->rmap->N;
7326:   if (n) *n = mat->cmap->N;
7327:   PetscFunctionReturn(PETSC_SUCCESS);
7328: }

7330: /*@
7331:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7332:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7334:   Not Collective

7336:   Input Parameter:
7337: . mat - the matrix

7339:   Output Parameters:
7340: + m - the number of local rows, use `NULL` to not obtain this value
7341: - n - the number of local columns, use `NULL` to not obtain this value

7343:   Level: beginner

7345: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7346: @*/
7347: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7348: {
7349:   PetscFunctionBegin;
7351:   if (m) PetscAssertPointer(m, 2);
7352:   if (n) PetscAssertPointer(n, 3);
7353:   if (m) *m = mat->rmap->n;
7354:   if (n) *n = mat->cmap->n;
7355:   PetscFunctionReturn(PETSC_SUCCESS);
7356: }

7358: /*@
7359:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7360:   vector one multiplies this matrix by that are owned by this process.

7362:   Not Collective, unless matrix has not been allocated, then collective

7364:   Input Parameter:
7365: . mat - the matrix

7367:   Output Parameters:
7368: + m - the global index of the first local column, use `NULL` to not obtain this value
7369: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7371:   Level: developer

7373:   Notes:
7374:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7376:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7377:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7382:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7383:   Layouts](sec_matlayout) for details on matrix layouts.

7385: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7386:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7387: @*/
7388: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7389: {
7390:   PetscFunctionBegin;
7393:   if (m) PetscAssertPointer(m, 2);
7394:   if (n) PetscAssertPointer(n, 3);
7395:   MatCheckPreallocated(mat, 1);
7396:   if (m) *m = mat->cmap->rstart;
7397:   if (n) *n = mat->cmap->rend;
7398:   PetscFunctionReturn(PETSC_SUCCESS);
7399: }

7401: /*@
7402:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7403:   this MPI process.

7405:   Not Collective

7407:   Input Parameter:
7408: . mat - the matrix

7410:   Output Parameters:
7411: + m - the global index of the first local row, use `NULL` to not obtain this value
7412: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7414:   Level: beginner

7416:   Notes:
7417:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7419:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7420:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

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

7427:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7428:   would contain the result of a matrix vector product with this matrix. See [Matrix
7429:   Layouts](sec_matlayout) for details on matrix layouts.

7431: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7432:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7433: @*/
7434: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7435: {
7436:   PetscFunctionBegin;
7439:   if (m) PetscAssertPointer(m, 2);
7440:   if (n) PetscAssertPointer(n, 3);
7441:   MatCheckPreallocated(mat, 1);
7442:   if (m) *m = mat->rmap->rstart;
7443:   if (n) *n = mat->rmap->rend;
7444:   PetscFunctionReturn(PETSC_SUCCESS);
7445: }

7447: /*@
7448:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7449:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7451:   Not Collective, unless matrix has not been allocated

7453:   Input Parameter:
7454: . mat - the matrix

7456:   Output Parameter:
7457: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7458:            where `size` is the number of MPI processes used by `mat`

7460:   Level: beginner

7462:   Notes:
7463:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7465:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7466:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7471:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7472:   would contain the result of a matrix vector product with this matrix. See [Matrix
7473:   Layouts](sec_matlayout) for details on matrix layouts.

7475: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7476:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7477:           `DMDAGetGhostCorners()`, `DM`
7478: @*/
7479: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7480: {
7481:   PetscFunctionBegin;
7484:   MatCheckPreallocated(mat, 1);
7485:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7486:   PetscFunctionReturn(PETSC_SUCCESS);
7487: }

7489: /*@
7490:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7491:   vector one multiplies this vector by that are owned by each process.

7493:   Not Collective, unless matrix has not been allocated

7495:   Input Parameter:
7496: . mat - the matrix

7498:   Output Parameter:
7499: . ranges - start of each process's portion plus one more than the total length at the end

7501:   Level: beginner

7503:   Notes:
7504:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7506:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7507:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7512:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7513:   Layouts](sec_matlayout) for details on matrix layouts.

7515: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7516:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7517:           `DMDAGetGhostCorners()`, `DM`
7518: @*/
7519: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7520: {
7521:   PetscFunctionBegin;
7524:   MatCheckPreallocated(mat, 1);
7525:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7526:   PetscFunctionReturn(PETSC_SUCCESS);
7527: }

7529: /*@
7530:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7532:   Not Collective

7534:   Input Parameter:
7535: . A - matrix

7537:   Output Parameters:
7538: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7539: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7541:   Level: intermediate

7543:   Note:
7544:   You should call `ISDestroy()` on the returned `IS`

7546:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7547:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7548:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7549:   details on matrix layouts.

7551: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7552: @*/
7553: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7554: {
7555:   PetscErrorCode (*f)(Mat, IS *, IS *);

7557:   PetscFunctionBegin;
7560:   MatCheckPreallocated(A, 1);
7561:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7562:   if (f) {
7563:     PetscCall((*f)(A, rows, cols));
7564:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7565:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7566:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7567:   }
7568:   PetscFunctionReturn(PETSC_SUCCESS);
7569: }

7571: /*@
7572:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7573:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7574:   to complete the factorization.

7576:   Collective

7578:   Input Parameters:
7579: + fact - the factorized matrix obtained with `MatGetFactor()`
7580: . mat  - the matrix
7581: . row  - row permutation
7582: . col  - column permutation
7583: - info - structure containing
7584: .vb
7585:       levels - number of levels of fill.
7586:       expected fill - as ratio of original fill.
7587:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7588:                 missing diagonal entries)
7589: .ve

7591:   Level: developer

7593:   Notes:
7594:   See [Matrix Factorization](sec_matfactor) for additional information.

7596:   Most users should employ the `KSP` interface for linear solvers
7597:   instead of working directly with matrix algebra routines such as this.
7598:   See, e.g., `KSPCreate()`.

7600:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

7602:   Fortran Note:
7603:   A valid (non-null) `info` argument must be provided

7605: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7606:           `MatGetOrdering()`, `MatFactorInfo`
7607: @*/
7608: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7609: {
7610:   PetscFunctionBegin;
7615:   PetscAssertPointer(info, 5);
7616:   PetscAssertPointer(fact, 1);
7617:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7618:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7619:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7620:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7621:   MatCheckPreallocated(mat, 2);

7623:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7624:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7625:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7626:   PetscFunctionReturn(PETSC_SUCCESS);
7627: }

7629: /*@
7630:   MatICCFactorSymbolic - Performs symbolic incomplete
7631:   Cholesky factorization for a symmetric matrix. Use
7632:   `MatCholeskyFactorNumeric()` to complete the factorization.

7634:   Collective

7636:   Input Parameters:
7637: + fact - the factorized matrix obtained with `MatGetFactor()`
7638: . mat  - the matrix to be factored
7639: . perm - row and column permutation
7640: - info - structure containing
7641: .vb
7642:       levels - number of levels of fill.
7643:       expected fill - as ratio of original fill.
7644: .ve

7646:   Level: developer

7648:   Notes:
7649:   Most users should employ the `KSP` interface for linear solvers
7650:   instead of working directly with matrix algebra routines such as this.
7651:   See, e.g., `KSPCreate()`.

7653:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

7655:   Fortran Note:
7656:   A valid (non-null) `info` argument must be provided

7658: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7659: @*/
7660: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7661: {
7662:   PetscFunctionBegin;
7666:   PetscAssertPointer(info, 4);
7667:   PetscAssertPointer(fact, 1);
7668:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7669:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7670:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7671:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7672:   MatCheckPreallocated(mat, 2);

7674:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7675:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7676:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7677:   PetscFunctionReturn(PETSC_SUCCESS);
7678: }

7680: /*@
7681:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7682:   points to an array of valid matrices, they may be reused to store the new
7683:   submatrices.

7685:   Collective

7687:   Input Parameters:
7688: + mat   - the matrix
7689: . n     - the number of submatrixes to be extracted (on this process, may be zero)
7690: . irow  - index set of rows to extract
7691: . icol  - index set of columns to extract
7692: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7694:   Output Parameter:
7695: . submat - the array of submatrices

7697:   Level: advanced

7699:   Notes:
7700:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7701:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7702:   to extract a parallel submatrix.

7704:   Some matrix types place restrictions on the row and column
7705:   indices, such as that they be sorted or that they be equal to each other.
7706:   `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.

7708:   The index sets may not have duplicate entries.

7710:   When extracting submatrices from a parallel matrix, each process can
7711:   form a different submatrix by setting the rows and columns of its
7712:   individual index sets according to the local submatrix desired.

7714:   When finished using the submatrices, the user should destroy
7715:   them with `MatDestroySubMatrices()`.

7717:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7718:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7720:   This routine creates the matrices in submat; you should NOT create them before
7721:   calling it. It also allocates the array of matrix pointers submat.

7723:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7724:   request one row/column in a block, they must request all rows/columns that are in
7725:   that block. For example, if the block size is 2 you cannot request just row 0 and
7726:   column 0.

7728:   Fortran Note:
7729: .vb
7730:   Mat, pointer :: submat(:)
7731: .ve

7733: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7734: @*/
7735: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7736: {
7737:   PetscInt  i;
7738:   PetscBool eq;

7740:   PetscFunctionBegin;
7743:   if (n) {
7744:     PetscAssertPointer(irow, 3);
7746:     PetscAssertPointer(icol, 4);
7748:   }
7749:   PetscAssertPointer(submat, 6);
7750:   if (n && scall == MAT_REUSE_MATRIX) {
7751:     PetscAssertPointer(*submat, 6);
7753:   }
7754:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7755:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7756:   MatCheckPreallocated(mat, 1);
7757:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7758:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7759:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7760:   for (i = 0; i < n; i++) {
7761:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7762:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7763:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7764: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7765:     if (mat->boundtocpu && mat->bindingpropagates) {
7766:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7767:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7768:     }
7769: #endif
7770:   }
7771:   PetscFunctionReturn(PETSC_SUCCESS);
7772: }

7774: /*@
7775:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7777:   Collective

7779:   Input Parameters:
7780: + mat   - the matrix
7781: . n     - the number of submatrixes to be extracted
7782: . irow  - index set of rows to extract
7783: . icol  - index set of columns to extract
7784: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7786:   Output Parameter:
7787: . submat - the array of submatrices

7789:   Level: advanced

7791:   Note:
7792:   This is used by `PCGASM`

7794: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7795: @*/
7796: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7797: {
7798:   PetscInt  i;
7799:   PetscBool eq;

7801:   PetscFunctionBegin;
7804:   if (n) {
7805:     PetscAssertPointer(irow, 3);
7807:     PetscAssertPointer(icol, 4);
7809:   }
7810:   PetscAssertPointer(submat, 6);
7811:   if (n && scall == MAT_REUSE_MATRIX) {
7812:     PetscAssertPointer(*submat, 6);
7814:   }
7815:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7816:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7817:   MatCheckPreallocated(mat, 1);

7819:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7820:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7821:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7822:   for (i = 0; i < n; i++) {
7823:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7824:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7825:   }
7826:   PetscFunctionReturn(PETSC_SUCCESS);
7827: }

7829: /*@
7830:   MatDestroyMatrices - Destroys an array of matrices

7832:   Collective

7834:   Input Parameters:
7835: + n   - the number of local matrices
7836: - mat - the matrices (this is a pointer to the array of matrices)

7838:   Level: advanced

7840:   Notes:
7841:   Frees not only the matrices, but also the array that contains the matrices

7843:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7845: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7846: @*/
7847: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7848: {
7849:   PetscInt i;

7851:   PetscFunctionBegin;
7852:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7853:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7854:   PetscAssertPointer(mat, 2);

7856:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7858:   /* memory is allocated even if n = 0 */
7859:   PetscCall(PetscFree(*mat));
7860:   PetscFunctionReturn(PETSC_SUCCESS);
7861: }

7863: /*@
7864:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7866:   Collective

7868:   Input Parameters:
7869: + n   - the number of local matrices
7870: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7872:   Level: advanced

7874:   Note:
7875:   Frees not only the matrices, but also the array that contains the matrices

7877: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7878: @*/
7879: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7880: {
7881:   Mat mat0;

7883:   PetscFunctionBegin;
7884:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7885:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7886:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7887:   PetscAssertPointer(mat, 2);

7889:   mat0 = (*mat)[0];
7890:   if (mat0 && mat0->ops->destroysubmatrices) {
7891:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7892:   } else {
7893:     PetscCall(MatDestroyMatrices(n, mat));
7894:   }
7895:   PetscFunctionReturn(PETSC_SUCCESS);
7896: }

7898: /*@
7899:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7901:   Collective

7903:   Input Parameter:
7904: . mat - the matrix

7906:   Output Parameter:
7907: . matstruct - the sequential matrix with the nonzero structure of `mat`

7909:   Level: developer

7911: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7912: @*/
7913: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7914: {
7915:   PetscFunctionBegin;
7917:   PetscAssertPointer(matstruct, 2);

7920:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7921:   MatCheckPreallocated(mat, 1);

7923:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7924:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7925:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7926:   PetscFunctionReturn(PETSC_SUCCESS);
7927: }

7929: /*@
7930:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7932:   Collective

7934:   Input Parameter:
7935: . mat - the matrix

7937:   Level: advanced

7939:   Note:
7940:   This is not needed, one can just call `MatDestroy()`

7942: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7943: @*/
7944: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7945: {
7946:   PetscFunctionBegin;
7947:   PetscAssertPointer(mat, 1);
7948:   PetscCall(MatDestroy(mat));
7949:   PetscFunctionReturn(PETSC_SUCCESS);
7950: }

7952: /*@
7953:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7954:   replaces the index sets by larger ones that represent submatrices with
7955:   additional overlap.

7957:   Collective

7959:   Input Parameters:
7960: + mat - the matrix
7961: . n   - the number of index sets
7962: . is  - the array of index sets (these index sets will changed during the call)
7963: - ov  - the additional overlap requested

7965:   Options Database Key:
7966: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7968:   Level: developer

7970:   Note:
7971:   The computed overlap preserves the matrix block sizes when the blocks are square.
7972:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7973:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

7975: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7976: @*/
7977: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7978: {
7979:   PetscInt i, bs, cbs;

7981:   PetscFunctionBegin;
7985:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7986:   if (n) {
7987:     PetscAssertPointer(is, 3);
7989:   }
7990:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7991:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7992:   MatCheckPreallocated(mat, 1);

7994:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7995:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7996:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7997:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7998:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7999:   if (bs == cbs) {
8000:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
8001:   }
8002:   PetscFunctionReturn(PETSC_SUCCESS);
8003: }

8005: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

8007: /*@
8008:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
8009:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
8010:   additional overlap.

8012:   Collective

8014:   Input Parameters:
8015: + mat - the matrix
8016: . n   - the number of index sets
8017: . is  - the array of index sets (these index sets will changed during the call)
8018: - ov  - the additional overlap requested

8020:   `   Options Database Key:
8021: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

8023:   Level: developer

8025: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
8026: @*/
8027: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
8028: {
8029:   PetscInt i;

8031:   PetscFunctionBegin;
8034:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8035:   if (n) {
8036:     PetscAssertPointer(is, 3);
8038:   }
8039:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8040:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8041:   MatCheckPreallocated(mat, 1);
8042:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
8043:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8044:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
8045:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8046:   PetscFunctionReturn(PETSC_SUCCESS);
8047: }

8049: /*@
8050:   MatGetBlockSize - Returns the matrix block size.

8052:   Not Collective

8054:   Input Parameter:
8055: . mat - the matrix

8057:   Output Parameter:
8058: . bs - block size

8060:   Level: intermediate

8062:   Notes:
8063:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8065:   If the block size has not been set yet this routine returns 1.

8067: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8068: @*/
8069: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8070: {
8071:   PetscFunctionBegin;
8073:   PetscAssertPointer(bs, 2);
8074:   *bs = mat->rmap->bs;
8075:   PetscFunctionReturn(PETSC_SUCCESS);
8076: }

8078: /*@
8079:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8081:   Not Collective

8083:   Input Parameter:
8084: . mat - the matrix

8086:   Output Parameters:
8087: + rbs - row block size
8088: - cbs - column block size

8090:   Level: intermediate

8092:   Notes:
8093:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8094:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8096:   If a block size has not been set yet this routine returns 1.

8098: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8099: @*/
8100: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8101: {
8102:   PetscFunctionBegin;
8104:   if (rbs) PetscAssertPointer(rbs, 2);
8105:   if (cbs) PetscAssertPointer(cbs, 3);
8106:   if (rbs) *rbs = mat->rmap->bs;
8107:   if (cbs) *cbs = mat->cmap->bs;
8108:   PetscFunctionReturn(PETSC_SUCCESS);
8109: }

8111: /*@
8112:   MatSetBlockSize - Sets the matrix block size.

8114:   Logically Collective

8116:   Input Parameters:
8117: + mat - the matrix
8118: - bs  - block size

8120:   Level: intermediate

8122:   Notes:
8123:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8124:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8126:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8127:   is compatible with the matrix local sizes.

8129: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8130: @*/
8131: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8132: {
8133:   PetscFunctionBegin;
8136:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8137:   PetscFunctionReturn(PETSC_SUCCESS);
8138: }

8140: typedef struct {
8141:   PetscInt         n;
8142:   IS              *is;
8143:   Mat             *mat;
8144:   PetscObjectState nonzerostate;
8145:   Mat              C;
8146: } EnvelopeData;

8148: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8149: {
8150:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8152:   PetscFunctionBegin;
8153:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8154:   PetscCall(PetscFree(edata->is));
8155:   PetscCall(PetscFree(edata));
8156:   PetscFunctionReturn(PETSC_SUCCESS);
8157: }

8159: /*@
8160:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8161:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8163:   Collective

8165:   Input Parameter:
8166: . mat - the matrix

8168:   Level: intermediate

8170:   Notes:
8171:   There can be zeros within the blocks

8173:   The blocks can overlap between processes, including laying on more than two processes

8175: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8176: @*/
8177: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8178: {
8179:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8180:   PetscInt          *diag, *odiag, sc;
8181:   VecScatter         scatter;
8182:   PetscScalar       *seqv;
8183:   const PetscScalar *parv;
8184:   const PetscInt    *ia, *ja;
8185:   PetscBool          set, flag, done;
8186:   Mat                AA = mat, A;
8187:   MPI_Comm           comm;
8188:   PetscMPIInt        rank, size, tag;
8189:   MPI_Status         status;
8190:   PetscContainer     container;
8191:   EnvelopeData      *edata;
8192:   Vec                seq, par;
8193:   IS                 isglobal;

8195:   PetscFunctionBegin;
8197:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8198:   if (!set || !flag) {
8199:     /* TODO: only needs nonzero structure of transpose */
8200:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8201:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8202:   }
8203:   PetscCall(MatAIJGetLocalMat(AA, &A));
8204:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8205:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8207:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8208:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8209:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8210:   PetscCallMPI(MPI_Comm_size(comm, &size));
8211:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8213:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8215:   if (rank > 0) {
8216:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8217:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8218:   }
8219:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8220:   for (i = 0; i < n; i++) {
8221:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8222:     II  = rstart + i;
8223:     if (env == II) {
8224:       starts[lblocks]  = tbs;
8225:       sizes[lblocks++] = 1 + II - tbs;
8226:       tbs              = 1 + II;
8227:     }
8228:   }
8229:   if (rank < size - 1) {
8230:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8231:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8232:   }

8234:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8235:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8236:   PetscCall(MatDestroy(&A));

8238:   PetscCall(PetscNew(&edata));
8239:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8240:   edata->n = lblocks;
8241:   /* create IS needed for extracting blocks from the original matrix */
8242:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8243:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8245:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8246:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8247:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8248:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8249:   PetscCall(MatSetType(edata->C, MATAIJ));

8251:   /* Communicate the start and end of each row, from each block to the correct rank */
8252:   /* TODO: Use PetscSF instead of VecScatter */
8253:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8254:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8255:   PetscCall(VecGetArrayWrite(seq, &seqv));
8256:   for (PetscInt i = 0; i < lblocks; i++) {
8257:     for (PetscInt j = 0; j < sizes[i]; j++) {
8258:       seqv[cnt]     = starts[i];
8259:       seqv[cnt + 1] = starts[i] + sizes[i];
8260:       cnt += 2;
8261:     }
8262:   }
8263:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
8264:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8265:   sc -= cnt;
8266:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8267:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8268:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8269:   PetscCall(ISDestroy(&isglobal));
8270:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8271:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8272:   PetscCall(VecScatterDestroy(&scatter));
8273:   PetscCall(VecDestroy(&seq));
8274:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8275:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8276:   PetscCall(VecGetArrayRead(par, &parv));
8277:   cnt = 0;
8278:   PetscCall(MatGetSize(mat, NULL, &n));
8279:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8280:     PetscInt start, end, d = 0, od = 0;

8282:     start = (PetscInt)PetscRealPart(parv[cnt]);
8283:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
8284:     cnt += 2;

8286:     if (start < cstart) {
8287:       od += cstart - start + n - cend;
8288:       d += cend - cstart;
8289:     } else if (start < cend) {
8290:       od += n - cend;
8291:       d += cend - start;
8292:     } else od += n - start;
8293:     if (end <= cstart) {
8294:       od -= cstart - end + n - cend;
8295:       d -= cend - cstart;
8296:     } else if (end < cend) {
8297:       od -= n - cend;
8298:       d -= cend - end;
8299:     } else od -= n - end;

8301:     odiag[i] = od;
8302:     diag[i]  = d;
8303:   }
8304:   PetscCall(VecRestoreArrayRead(par, &parv));
8305:   PetscCall(VecDestroy(&par));
8306:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8307:   PetscCall(PetscFree2(diag, odiag));
8308:   PetscCall(PetscFree2(sizes, starts));

8310:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8311:   PetscCall(PetscContainerSetPointer(container, edata));
8312:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8313:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8314:   PetscCall(PetscObjectDereference((PetscObject)container));
8315:   PetscFunctionReturn(PETSC_SUCCESS);
8316: }

8318: /*@
8319:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8321:   Collective

8323:   Input Parameters:
8324: + A     - the matrix
8325: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8327:   Output Parameter:
8328: . C - matrix with inverted block diagonal of `A`

8330:   Level: advanced

8332:   Note:
8333:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8335: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8336: @*/
8337: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8338: {
8339:   PetscContainer   container;
8340:   EnvelopeData    *edata;
8341:   PetscObjectState nonzerostate;

8343:   PetscFunctionBegin;
8344:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8345:   if (!container) {
8346:     PetscCall(MatComputeVariableBlockEnvelope(A));
8347:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8348:   }
8349:   PetscCall(PetscContainerGetPointer(container, &edata));
8350:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8351:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8352:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8354:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8355:   *C = edata->C;

8357:   for (PetscInt i = 0; i < edata->n; i++) {
8358:     Mat          D;
8359:     PetscScalar *dvalues;

8361:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8362:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8363:     PetscCall(MatSeqDenseInvert(D));
8364:     PetscCall(MatDenseGetArray(D, &dvalues));
8365:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8366:     PetscCall(MatDestroy(&D));
8367:   }
8368:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8369:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8370:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8371:   PetscFunctionReturn(PETSC_SUCCESS);
8372: }

8374: /*@
8375:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8377:   Not Collective

8379:   Input Parameters:
8380: + mat     - the matrix
8381: . nblocks - the number of blocks on this process, each block can only exist on a single MPI process
8382: - bsizes  - the block sizes

8384:   Level: intermediate

8386:   Note:
8387:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8389: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8390:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8391: @*/
8392: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8393: {
8394:   PetscInt ncnt = 0, nlocal;

8396:   PetscFunctionBegin;
8398:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8399:   PetscCheck(nblocks >= 0 && nblocks <= nlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of local blocks %" PetscInt_FMT " is not in [0, %" PetscInt_FMT "]", nblocks, nlocal);
8400:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8401:   PetscCheck(ncnt == nlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Sum of local block sizes %" PetscInt_FMT " does not equal local size of matrix %" PetscInt_FMT, ncnt, nlocal);
8402:   PetscCall(PetscFree(mat->bsizes));
8403:   mat->nblocks = nblocks;
8404:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8405:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8406:   PetscFunctionReturn(PETSC_SUCCESS);
8407: }

8409: /*@
8410:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8412:   Not Collective; No Fortran Support

8414:   Input Parameter:
8415: . mat - the matrix

8417:   Output Parameters:
8418: + nblocks - the number of blocks on this process
8419: - bsizes  - the block sizes

8421:   Level: intermediate

8423: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8424: @*/
8425: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8426: {
8427:   PetscFunctionBegin;
8429:   if (nblocks) *nblocks = mat->nblocks;
8430:   if (bsizes) *bsizes = mat->bsizes;
8431:   PetscFunctionReturn(PETSC_SUCCESS);
8432: }

8434: /*@
8435:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8437:   Not Collective

8439:   Input Parameters:
8440: + subA  - the submatrix
8441: . A     - the original matrix
8442: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8444:   Level: developer

8446:   Note:
8447:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8449: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8450: @*/
8451: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8452: {
8453:   const PetscInt *rows;
8454:   PetscInt        n, rStart, rEnd, Nb = 0;
8455:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8457:   PetscFunctionBegin;
8458:   // The code for block size extraction does not support an unsorted IS
8459:   if (flg) PetscCall(ISSorted(isrow, &flg));
8460:   // We don't support originally off-diagonal blocks
8461:   if (flg) {
8462:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8463:     PetscCall(ISGetLocalSize(isrow, &n));
8464:     PetscCall(ISGetIndices(isrow, &rows));
8465:     for (PetscInt i = 0; i < n && flg; ++i) {
8466:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8467:     }
8468:     PetscCall(ISRestoreIndices(isrow, &rows));
8469:   }
8470:   // quiet return if we can't extract block size
8471:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8472:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8474:   // extract block sizes
8475:   PetscCall(ISGetIndices(isrow, &rows));
8476:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8477:     PetscBool occupied = PETSC_FALSE;

8479:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8480:       const PetscInt row = gr + br;

8482:       if (i == n) break;
8483:       if (rows[i] == row) {
8484:         occupied = PETSC_TRUE;
8485:         ++i;
8486:       }
8487:       while (i < n && rows[i] < row) ++i;
8488:     }
8489:     gr += A->bsizes[b];
8490:     if (occupied) ++Nb;
8491:   }
8492:   subA->nblocks = Nb;
8493:   PetscCall(PetscFree(subA->bsizes));
8494:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8495:   PetscInt sb = 0;
8496:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8497:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8498:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8499:       const PetscInt row = gr + br;

8501:       if (i == n) break;
8502:       if (rows[i] == row) {
8503:         ++subA->bsizes[sb];
8504:         ++i;
8505:       }
8506:       while (i < n && rows[i] < row) ++i;
8507:     }
8508:     gr += A->bsizes[b];
8509:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8510:   }
8511:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8512:   PetscInt nlocal, ncnt = 0;
8513:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8514:   PetscCheck(subA->nblocks >= 0 && subA->nblocks <= nlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of local blocks %" PetscInt_FMT " is not in [0, %" PetscInt_FMT "]", subA->nblocks, nlocal);
8515:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8516:   PetscCheck(ncnt == nlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Sum of local block sizes %" PetscInt_FMT " does not equal local size of matrix %" PetscInt_FMT, ncnt, nlocal);
8517:   PetscCall(ISRestoreIndices(isrow, &rows));
8518:   PetscFunctionReturn(PETSC_SUCCESS);
8519: }

8521: /*@
8522:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8524:   Logically Collective

8526:   Input Parameters:
8527: + mat - the matrix
8528: . rbs - row block size
8529: - cbs - column block size

8531:   Level: intermediate

8533:   Notes:
8534:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8535:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8536:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8538:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8539:   are compatible with the matrix local sizes.

8541:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8543: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8544: @*/
8545: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8546: {
8547:   PetscFunctionBegin;
8551:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8552:   if (mat->rmap->refcnt) {
8553:     ISLocalToGlobalMapping l2g  = NULL;
8554:     PetscLayout            nmap = NULL;

8556:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8557:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8558:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8559:     mat->rmap          = nmap;
8560:     mat->rmap->mapping = l2g;
8561:   }
8562:   if (mat->cmap->refcnt) {
8563:     ISLocalToGlobalMapping l2g  = NULL;
8564:     PetscLayout            nmap = NULL;

8566:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8567:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8568:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8569:     mat->cmap          = nmap;
8570:     mat->cmap->mapping = l2g;
8571:   }
8572:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8573:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8574:   PetscFunctionReturn(PETSC_SUCCESS);
8575: }

8577: /*@
8578:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8580:   Logically Collective

8582:   Input Parameters:
8583: + mat     - the matrix
8584: . fromRow - matrix from which to copy row block size
8585: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8587:   Level: developer

8589: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8590: @*/
8591: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8592: {
8593:   PetscFunctionBegin;
8597:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8598:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8599:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8600:   PetscFunctionReturn(PETSC_SUCCESS);
8601: }

8603: /*@
8604:   MatResidual - Default routine to calculate the residual $r = b - Ax$

8606:   Collective

8608:   Input Parameters:
8609: + mat - the matrix
8610: . b   - the right-hand-side
8611: - x   - the approximate solution

8613:   Output Parameter:
8614: . r - location to store the residual

8616:   Level: developer

8618: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8619: @*/
8620: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8621: {
8622:   PetscFunctionBegin;
8628:   MatCheckPreallocated(mat, 1);
8629:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8630:   if (!mat->ops->residual) {
8631:     PetscCall(MatMult(mat, x, r));
8632:     PetscCall(VecAYPX(r, -1.0, b));
8633:   } else {
8634:     PetscUseTypeMethod(mat, residual, b, x, r);
8635:   }
8636:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8637:   PetscFunctionReturn(PETSC_SUCCESS);
8638: }

8640: /*@
8641:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8643:   Collective

8645:   Input Parameters:
8646: + mat             - the matrix
8647: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8648: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8649: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8650:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8651:                     always used.

8653:   Output Parameters:
8654: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8655: . ia   - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix, use `NULL` if not needed
8656: . ja   - the column indices, use `NULL` if not needed
8657: - done - indicates if the routine actually worked and returned appropriate `ia` and `ja` arrays; callers
8658:          are responsible for handling the case when done is `PETSC_FALSE` and `ia` and `ja` are not provided

8660:   Level: developer

8662:   Notes:
8663:   You CANNOT change any of the `ia` or `ja` values.

8665:   Use `MatRestoreRowIJ()` when you are finished accessing the `ia` and `ja` values.

8667:   Fortran Notes:
8668:   Use
8669: .vb
8670:     PetscInt, pointer :: ia(:),ja(:)
8671:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8672:     ! Access the ith and jth entries via ia(i) and ja(j)
8673: .ve

8675: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8676: @*/
8677: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8678: {
8679:   PetscFunctionBegin;
8682:   if (n) PetscAssertPointer(n, 5);
8683:   if (ia) PetscAssertPointer(ia, 6);
8684:   if (ja) PetscAssertPointer(ja, 7);
8685:   if (done) PetscAssertPointer(done, 8);
8686:   MatCheckPreallocated(mat, 1);
8687:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8688:   else {
8689:     if (done) *done = PETSC_TRUE;
8690:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8691:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8692:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8693:   }
8694:   PetscFunctionReturn(PETSC_SUCCESS);
8695: }

8697: /*@
8698:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8700:   Collective

8702:   Input Parameters:
8703: + mat             - the matrix
8704: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8705: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8706:                     symmetrized
8707: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8708:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8709:                     always used.

8711:   Output Parameters:
8712: + n    - number of columns in the (possibly compressed) matrix
8713: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8714: . ja   - the row indices
8715: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8717:   Level: developer

8719: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8720: @*/
8721: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8722: {
8723:   PetscFunctionBegin;
8726:   PetscAssertPointer(n, 5);
8727:   if (ia) PetscAssertPointer(ia, 6);
8728:   if (ja) PetscAssertPointer(ja, 7);
8729:   PetscAssertPointer(done, 8);
8730:   MatCheckPreallocated(mat, 1);
8731:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8732:   else {
8733:     *done = PETSC_TRUE;
8734:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8735:   }
8736:   PetscFunctionReturn(PETSC_SUCCESS);
8737: }

8739: /*@
8740:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8742:   Collective

8744:   Input Parameters:
8745: + mat             - the matrix
8746: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8747: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8748: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8749:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8750:                     always used.
8751: . n               - size of (possibly compressed) matrix, or `NULL`
8752: . ia              - the row pointers, or `NULL`
8753: - ja              - the column indices, or `NULL`

8755:   Output Parameter:
8756: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8758:   Level: developer

8760:   Note:
8761:   This routine zeros out `n`, `ia`, and `ja` if they are provided. Use of `ia` or `ja` after `MatRestoreRowIJ()` is always invalid.

8763: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8764: @*/
8765: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8766: {
8767:   PetscFunctionBegin;
8770:   if (ia) PetscAssertPointer(ia, 6);
8771:   if (ja) PetscAssertPointer(ja, 7);
8772:   if (done) PetscAssertPointer(done, 8);
8773:   MatCheckPreallocated(mat, 1);

8775:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8776:   else {
8777:     if (done) *done = PETSC_TRUE;
8778:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8779:     if (n) *n = 0;
8780:     if (ia) *ia = NULL;
8781:     if (ja) *ja = NULL;
8782:   }
8783:   PetscFunctionReturn(PETSC_SUCCESS);
8784: }

8786: /*@
8787:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8789:   Collective

8791:   Input Parameters:
8792: + mat             - the matrix
8793: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8794: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8795: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8796:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8797:                     always used.

8799:   Output Parameters:
8800: + n    - size of (possibly compressed) matrix
8801: . ia   - the column pointers
8802: . ja   - the row indices
8803: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8805:   Level: developer

8807: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8808: @*/
8809: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8810: {
8811:   PetscFunctionBegin;
8814:   if (ia) PetscAssertPointer(ia, 6);
8815:   if (ja) PetscAssertPointer(ja, 7);
8816:   PetscAssertPointer(done, 8);
8817:   MatCheckPreallocated(mat, 1);

8819:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8820:   else {
8821:     *done = PETSC_TRUE;
8822:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8823:     if (n) *n = 0;
8824:     if (ia) *ia = NULL;
8825:     if (ja) *ja = NULL;
8826:   }
8827:   PetscFunctionReturn(PETSC_SUCCESS);
8828: }

8830: /*@
8831:   MatColoringPatch - Utility routine used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8832:   `MatGetColumnIJ()`.

8834:   Collective

8836:   Input Parameters:
8837: + mat        - the matrix
8838: . ncolors    - maximum color value
8839: . n          - number of entries in `colorarray`
8840: - colorarray - array indicating color for each column

8842:   Output Parameter:
8843: . iscoloring - coloring generated using `colorarray` information

8845:   Level: developer

8847: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8848: @*/
8849: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8850: {
8851:   PetscFunctionBegin;
8854:   PetscAssertPointer(colorarray, 4);
8855:   PetscAssertPointer(iscoloring, 5);
8856:   MatCheckPreallocated(mat, 1);

8858:   if (!mat->ops->coloringpatch) {
8859:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8860:   } else {
8861:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8862:   }
8863:   PetscFunctionReturn(PETSC_SUCCESS);
8864: }

8866: /*@
8867:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8869:   Logically Collective

8871:   Input Parameter:
8872: . mat - the factored matrix to be reset

8874:   Level: developer

8876:   Notes:
8877:   This routine should be used only with factored matrices formed by in-place
8878:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8879:   format). This option can save memory, for example, when solving nonlinear
8880:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8881:   ILU(0) preconditioner.

8883:   One can specify in-place ILU(0) factorization by calling
8884: .vb
8885:      PCType(pc,PCILU);
8886:      PCFactorSeUseInPlace(pc);
8887: .ve
8888:   or by using the options -pc_type ilu -pc_factor_in_place

8890:   In-place factorization ILU(0) can also be used as a local
8891:   solver for the blocks within the block Jacobi or additive Schwarz
8892:   methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8893:   for details on setting local solver options.

8895:   Most users should employ the `KSP` interface for linear solvers
8896:   instead of working directly with matrix algebra routines such as this.
8897:   See, e.g., `KSPCreate()`.

8899: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8900: @*/
8901: PetscErrorCode MatSetUnfactored(Mat mat)
8902: {
8903:   PetscFunctionBegin;
8906:   MatCheckPreallocated(mat, 1);
8907:   mat->factortype = MAT_FACTOR_NONE;
8908:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8909:   PetscUseTypeMethod(mat, setunfactored);
8910:   PetscFunctionReturn(PETSC_SUCCESS);
8911: }

8913: /*@
8914:   MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8915:   as the original matrix.

8917:   Collective

8919:   Input Parameters:
8920: + mat   - the original matrix
8921: . isrow - parallel `IS` containing the rows this process should obtain
8922: . iscol - parallel `IS` containing all columns you wish to keep. Each process should list the columns that will be in IT's "diagonal part" in the new matrix.
8923: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8925:   Output Parameter:
8926: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)

8928:   Level: advanced

8930:   Notes:
8931:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8933:   Some matrix types place restrictions on the row and column indices, such
8934:   as that they be sorted or that they be equal to each other. For `MATBAIJ` and `MATSBAIJ` matrices the indices must include all rows/columns of a block;
8935:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8936:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.

8938:   The index sets may not have duplicate entries.

8940:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8941:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8942:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8943:   will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8944:   you are finished using it.

8946:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8947:   the input matrix.

8949:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8951:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8952:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8954:   Example usage:
8955:   Consider the following 8x8 matrix with 34 non-zero values, that is
8956:   assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8957:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8958:   as follows
8959: .vb
8960:             1  2  0  |  0  3  0  |  0  4
8961:     Proc0   0  5  6  |  7  0  0  |  8  0
8962:             9  0 10  | 11  0  0  | 12  0
8963:     -------------------------------------
8964:            13  0 14  | 15 16 17  |  0  0
8965:     Proc1   0 18  0  | 19 20 21  |  0  0
8966:             0  0  0  | 22 23  0  | 24  0
8967:     -------------------------------------
8968:     Proc2  25 26 27  |  0  0 28  | 29  0
8969:            30  0  0  | 31 32 33  |  0 34
8970: .ve

8972:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is

8974: .vb
8975:             2  0  |  0  3  0  |  0
8976:     Proc0   5  6  |  7  0  0  |  8
8977:     -------------------------------
8978:     Proc1  18  0  | 19 20 21  |  0
8979:     -------------------------------
8980:     Proc2  26 27  |  0  0 28  | 29
8981:             0  0  | 31 32 33  |  0
8982: .ve

8984: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8985: @*/
8986: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8987: {
8988:   PetscMPIInt size;
8989:   Mat        *local;
8990:   IS          iscoltmp;
8991:   PetscBool   flg;

8993:   PetscFunctionBegin;
8997:   PetscAssertPointer(newmat, 5);
9000:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9001:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
9002:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

9004:   MatCheckPreallocated(mat, 1);
9005:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

9007:   if (!iscol || isrow == iscol) {
9008:     PetscBool   stride;
9009:     PetscMPIInt grab = 0;
9010:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
9011:     if (stride) {
9012:       PetscInt first, step, n, rstart, rend;
9013:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
9014:       if (step == 1) {
9015:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
9016:         if (rstart == first) {
9017:           PetscCall(ISGetLocalSize(isrow, &n));
9018:           if (n == rend - rstart) grab = 1;
9019:         }
9020:       }
9021:     }
9022:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
9023:     if (grab) {
9024:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
9025:       if (cll == MAT_INITIAL_MATRIX) {
9026:         *newmat = mat;
9027:         PetscCall(PetscObjectReference((PetscObject)mat));
9028:       }
9029:       PetscFunctionReturn(PETSC_SUCCESS);
9030:     }
9031:   }

9033:   if (!iscol) {
9034:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
9035:   } else {
9036:     iscoltmp = iscol;
9037:   }

9039:   /* if original matrix is on just one process then use submatrix generated */
9040:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
9041:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
9042:     goto setproperties;
9043:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
9044:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
9045:     *newmat = *local;
9046:     PetscCall(PetscFree(local));
9047:     goto setproperties;
9048:   } else if (!mat->ops->createsubmatrix) {
9049:     /* Create a new matrix type that implements the operation using the full matrix */
9050:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9051:     switch (cll) {
9052:     case MAT_INITIAL_MATRIX:
9053:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9054:       break;
9055:     case MAT_REUSE_MATRIX:
9056:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9057:       break;
9058:     default:
9059:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9060:     }
9061:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9062:     goto setproperties;
9063:   }

9065:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9066:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9067:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9069: setproperties:
9070:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9071:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9072:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9073:   }
9074:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9075:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9076:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9077:   PetscFunctionReturn(PETSC_SUCCESS);
9078: }

9080: /*@
9081:   MatPropagateSymmetryOptions - Propagates symmetry properties set on a matrix to another matrix

9083:   Not Collective

9085:   Input Parameters:
9086: + A - the matrix we wish to propagate properties from
9087: - B - the matrix we wish to propagate properties to

9089:   Level: beginner

9091:   Note:
9092:   Propagates the properties associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9094: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9095: @*/
9096: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9097: {
9098:   PetscFunctionBegin;
9101:   B->symmetry_eternal            = A->symmetry_eternal;
9102:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9103:   B->symmetric                   = A->symmetric;
9104:   B->structurally_symmetric      = A->structurally_symmetric;
9105:   B->spd                         = A->spd;
9106:   B->hermitian                   = A->hermitian;
9107:   PetscFunctionReturn(PETSC_SUCCESS);
9108: }

9110: /*@
9111:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9112:   used during the assembly process to store values that belong to
9113:   other processes.

9115:   Not Collective

9117:   Input Parameters:
9118: + mat   - the matrix
9119: . size  - the initial size of the stash.
9120: - bsize - the initial size of the block-stash(if used).

9122:   Options Database Key:
9123: . -matstash_initial_size (size|size0,size1,...,sizep-1) - set initial size of stash for all or each of the MPI processes, sets both block and non-block stash sizes

9125:   Level: intermediate

9127:   Notes:
9128:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9129:   the stash is used for values set with `MatSetValues()`

9131:   Run with the option `-info` and look for output of the form
9132:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9133:   to determine the appropriate value, MM, to use for size and
9134:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9135:   to determine the value, BMM to use for bsize

9137: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9138: @*/
9139: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9140: {
9141:   PetscFunctionBegin;
9144:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9145:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9146:   PetscFunctionReturn(PETSC_SUCCESS);
9147: }

9149: /*@
9150:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9151:   the matrix

9153:   Neighbor-wise Collective

9155:   Input Parameters:
9156: + A - the matrix
9157: . x - the vector to be multiplied by the interpolation operator
9158: - y - the vector to be added to the result

9160:   Output Parameter:
9161: . w - the resulting vector

9163:   Level: intermediate

9165:   Notes:
9166:   `w` may be the same vector as `y`.

9168:   This allows one to use either the restriction or interpolation (its transpose)
9169:   matrix to do the interpolation

9171: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9172: @*/
9173: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9174: {
9175:   PetscInt M, N, Ny;

9177:   PetscFunctionBegin;
9182:   PetscCall(MatGetSize(A, &M, &N));
9183:   PetscCall(VecGetSize(y, &Ny));
9184:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9185:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9186:   PetscFunctionReturn(PETSC_SUCCESS);
9187: }

9189: /*@
9190:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9191:   the matrix

9193:   Neighbor-wise Collective

9195:   Input Parameters:
9196: + A - the matrix
9197: - x - the vector to be interpolated

9199:   Output Parameter:
9200: . y - the resulting vector

9202:   Level: intermediate

9204:   Note:
9205:   This allows one to use either the restriction or interpolation (its transpose)
9206:   matrix to do the interpolation

9208: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9209: @*/
9210: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9211: {
9212:   PetscInt M, N, Ny;

9214:   PetscFunctionBegin;
9218:   PetscCall(MatGetSize(A, &M, &N));
9219:   PetscCall(VecGetSize(y, &Ny));
9220:   if (M == Ny) PetscCall(MatMult(A, x, y));
9221:   else PetscCall(MatMultTranspose(A, x, y));
9222:   PetscFunctionReturn(PETSC_SUCCESS);
9223: }

9225: /*@
9226:   MatRestrict - $y = A*x$ or $A^T*x$

9228:   Neighbor-wise Collective

9230:   Input Parameters:
9231: + A - the matrix
9232: - x - the vector to be restricted

9234:   Output Parameter:
9235: . y - the resulting vector

9237:   Level: intermediate

9239:   Note:
9240:   This allows one to use either the restriction or interpolation (its transpose)
9241:   matrix to do the restriction

9243: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9244: @*/
9245: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9246: {
9247:   PetscInt M, N, Nx;

9249:   PetscFunctionBegin;
9253:   PetscCall(MatGetSize(A, &M, &N));
9254:   PetscCall(VecGetSize(x, &Nx));
9255:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9256:   else PetscCall(MatMult(A, x, y));
9257:   PetscFunctionReturn(PETSC_SUCCESS);
9258: }

9260: /*@
9261:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

9263:   Neighbor-wise Collective

9265:   Input Parameters:
9266: + A - the matrix
9267: . x - the input dense matrix to be multiplied
9268: - w - the input dense matrix to be added to the result

9270:   Output Parameter:
9271: . y - the output dense matrix

9273:   Level: intermediate

9275:   Note:
9276:   This allows one to use either the restriction or interpolation (its transpose)
9277:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9278:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9280: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9281: @*/
9282: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9283: {
9284:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9285:   PetscBool trans = PETSC_TRUE;
9286:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9288:   PetscFunctionBegin;
9294:   PetscCall(MatGetSize(A, &M, &N));
9295:   PetscCall(MatGetSize(x, &Mx, &Nx));
9296:   if (N == Mx) trans = PETSC_FALSE;
9297:   else PetscCheck(M == Mx, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Size mismatch: A %" PetscInt_FMT "x%" PetscInt_FMT ", X %" PetscInt_FMT "x%" PetscInt_FMT, M, N, Mx, Nx);
9298:   Mo = trans ? N : M;
9299:   if (*y) {
9300:     PetscCall(MatGetSize(*y, &My, &Ny));
9301:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9302:     else {
9303:       PetscCheck(w || *y != w, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot reuse y and w, size mismatch: A %" PetscInt_FMT "x%" PetscInt_FMT ", X %" PetscInt_FMT "x%" PetscInt_FMT ", Y %" PetscInt_FMT "x%" PetscInt_FMT, M, N, Mx, Nx, My, Ny);
9304:       PetscCall(MatDestroy(y));
9305:     }
9306:   }

9308:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9309:     PetscBool flg;

9311:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9312:     if (w) {
9313:       PetscInt My, Ny, Mw, Nw;

9315:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9316:       PetscCall(MatGetSize(*y, &My, &Ny));
9317:       PetscCall(MatGetSize(w, &Mw, &Nw));
9318:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9319:     }
9320:     if (!w) {
9321:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9322:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9323:       PetscCall(PetscObjectDereference((PetscObject)w));
9324:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9325:   }
9326:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9327:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9328:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9329:   PetscFunctionReturn(PETSC_SUCCESS);
9330: }

9332: /*@
9333:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9335:   Neighbor-wise Collective

9337:   Input Parameters:
9338: + A - the matrix
9339: - x - the input dense matrix

9341:   Output Parameter:
9342: . y - the output dense matrix

9344:   Level: intermediate

9346:   Note:
9347:   This allows one to use either the restriction or interpolation (its transpose)
9348:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9349:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9351: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9352: @*/
9353: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9354: {
9355:   PetscFunctionBegin;
9356:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9357:   PetscFunctionReturn(PETSC_SUCCESS);
9358: }

9360: /*@
9361:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9363:   Neighbor-wise Collective

9365:   Input Parameters:
9366: + A - the matrix
9367: - x - the input dense matrix

9369:   Output Parameter:
9370: . y - the output dense matrix

9372:   Level: intermediate

9374:   Note:
9375:   This allows one to use either the restriction or interpolation (its transpose)
9376:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9377:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9379: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9380: @*/
9381: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9382: {
9383:   PetscFunctionBegin;
9384:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9385:   PetscFunctionReturn(PETSC_SUCCESS);
9386: }

9388: /*@
9389:   MatGetNullSpace - retrieves the null space of a matrix that was provided with `MatSetNullSpace()`

9391:   Logically Collective

9393:   Input Parameters:
9394: + mat    - the matrix
9395: - nullsp - the null space object

9397:   Level: developer

9399: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9400: @*/
9401: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9402: {
9403:   PetscFunctionBegin;
9405:   PetscAssertPointer(nullsp, 2);
9406:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9407:   PetscFunctionReturn(PETSC_SUCCESS);
9408: }

9410: /*@
9411:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices that were supplied with `MatSetNullSpace()`,
9412:   `MatSetTransposeNullSpace()`, and `MatSetNearNullSpace()`

9414:   Logically Collective

9416:   Input Parameters:
9417: + n   - the number of matrices
9418: - mat - the array of matrices

9420:   Output Parameters:
9421: . nullsp - an array of null spaces, `NULL` will be inserted for each matrix that does not have a null space, length 3 * `n`

9423:   Level: developer

9425:   Note:
9426:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9428: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9429:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`, `MatNullSpace`
9430: @*/
9431: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9432: {
9433:   PetscFunctionBegin;
9434:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9435:   PetscAssertPointer(mat, 2);
9436:   PetscAssertPointer(nullsp, 3);

9438:   PetscCall(PetscCalloc1(3 * n, nullsp));
9439:   for (PetscInt i = 0; i < n; i++) {
9441:     (*nullsp)[i] = mat[i]->nullsp;
9442:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9443:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9444:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9445:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9446:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9447:   }
9448:   PetscFunctionReturn(PETSC_SUCCESS);
9449: }

9451: /*@
9452:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9454:   Logically Collective

9456:   Input Parameters:
9457: + n      - the number of matrices
9458: . mat    - the array of matrices
9459: - nullsp - an array of null spaces, of length  3 * `n`

9461:   Level: developer

9463:   Notes:
9464:   Call `MatGetNullSpaces()` to create `nullsp`.

9466:   Frees `nullsp`.

9468:   Developer Note:
9469:   The name of this function is confusing. Traditionally in PETSc, a restore operation undoes something that was previously done on an object (or objects) with a get operation.
9470:   This restore routine does something to a new set of objects using the results of a get operation on a previous set of objects. Perhaps this routine
9471:   should have simply been called `MatSetNullSpaces()`

9473: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9474:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`, `MatNullSpace`
9475: @*/
9476: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9477: {
9478:   PetscFunctionBegin;
9479:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9480:   PetscAssertPointer(mat, 2);
9481:   PetscAssertPointer(nullsp, 3);
9482:   PetscAssertPointer(*nullsp, 3);

9484:   for (PetscInt i = 0; i < n; i++) {
9486:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9487:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9488:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9489:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9490:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9491:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9492:   }
9493:   PetscCall(PetscFree(*nullsp));
9494:   PetscFunctionReturn(PETSC_SUCCESS);
9495: }

9497: /*@
9498:   MatSetNullSpace - attaches a null space to a matrix.

9500:   Logically Collective

9502:   Input Parameters:
9503: + mat    - the matrix
9504: - nullsp - the null space object

9506:   Level: advanced

9508:   Notes:
9509:   This null space is used by the `KSP` linear solvers to solve singular systems.

9511:   Overwrites any previous null space that may have been attached. You can remove the null space from the matrix object by calling this routine with an nullsp of `NULL`

9513:   For inconsistent singular systems (linear systems where the right-hand side is not in the range of the operator) the `KSP` residuals will not converge
9514:   to zero but the linear system will still be solved in a least squares sense.

9516:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9517:   the domain of a matrix $A$ (from $R^n$ to $R^m$ ($m$ rows, $n$ columns) $R^n$ = the direct sum of the null space of $A$, $n(A)$, plus the range of $A^T$, $R(A^T)$.
9518:   Similarly $R^m$ = direct sum $n(A^T) + R(A)$. Hence the linear system $A x = b$ has a solution only if $b$ in $R(A)$ (or correspondingly $b$ is orthogonal to
9519:   $n(A^T))$ and if $x$ is a solution then $x + \alpha n(A)$ is a solution for any $\alpha$. The minimum norm solution is orthogonal to $n(A)$. For problems without a solution
9520:   the solution that minimizes the norm of the residual (the least squares solution) can be obtained by solving $A x = \hat{b}$ where $\hat{b}$ is $b$ orthogonalized to the $n(A^T)$.
9521:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9523:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9524:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9525:   routine also automatically calls `MatSetTransposeNullSpace()`.

9527:   The user should call `MatNullSpaceDestroy()`.

9529: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9530:           `KSPSetPCSide()`, `MatNullSpace`
9531: @*/
9532: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9533: {
9534:   PetscFunctionBegin;
9537:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9538:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9539:   mat->nullsp = nullsp;
9540:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9541:   PetscFunctionReturn(PETSC_SUCCESS);
9542: }

9544: /*@
9545:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix that was set with `MatSetTransposeNullSpace()`

9547:   Logically Collective

9549:   Input Parameters:
9550: + mat    - the matrix
9551: - nullsp - the null space object

9553:   Level: developer

9555: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9556: @*/
9557: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9558: {
9559:   PetscFunctionBegin;
9562:   PetscAssertPointer(nullsp, 2);
9563:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9564:   PetscFunctionReturn(PETSC_SUCCESS);
9565: }

9567: /*@
9568:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9570:   Logically Collective

9572:   Input Parameters:
9573: + mat    - the matrix
9574: - nullsp - the null space object

9576:   Level: advanced

9578:   Notes:
9579:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9581:   See `MatSetNullSpace()`

9583: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9584: @*/
9585: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9586: {
9587:   PetscFunctionBegin;
9590:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9591:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9592:   mat->transnullsp = nullsp;
9593:   PetscFunctionReturn(PETSC_SUCCESS);
9594: }

9596: /*@
9597:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9598:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9600:   Logically Collective

9602:   Input Parameters:
9603: + mat    - the matrix
9604: - nullsp - the null space object

9606:   Level: advanced

9608:   Notes:
9609:   Overwrites any previous near null space that may have been attached

9611:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9613: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9614: @*/
9615: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9616: {
9617:   PetscFunctionBegin;
9621:   MatCheckPreallocated(mat, 1);
9622:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9623:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9624:   mat->nearnullsp = nullsp;
9625:   PetscFunctionReturn(PETSC_SUCCESS);
9626: }

9628: /*@
9629:   MatGetNearNullSpace - Get null space from a matrix that was attached with `MatSetNearNullSpace()`

9631:   Not Collective

9633:   Input Parameter:
9634: . mat - the matrix

9636:   Output Parameter:
9637: . nullsp - the null space object, `NULL` if not set

9639:   Level: advanced

9641: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9642: @*/
9643: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9644: {
9645:   PetscFunctionBegin;
9648:   PetscAssertPointer(nullsp, 2);
9649:   MatCheckPreallocated(mat, 1);
9650:   *nullsp = mat->nearnullsp;
9651:   PetscFunctionReturn(PETSC_SUCCESS);
9652: }

9654: /*@
9655:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9657:   Collective

9659:   Input Parameters:
9660: + mat  - the matrix
9661: . row  - row/column permutation
9662: - info - information on desired factorization process

9664:   Level: developer

9666:   Notes:
9667:   Probably really in-place only when level of fill is zero, otherwise allocates
9668:   new space to store factored matrix and deletes previous memory.

9670:   Most users should employ the `KSP` interface for linear solvers
9671:   instead of working directly with matrix algebra routines such as this.
9672:   See, e.g., `KSPCreate()`.

9674:   Fortran Note:
9675:   A valid (non-null) `info` argument must be provided

9677: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9678: @*/
9679: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9680: {
9681:   PetscFunctionBegin;
9685:   PetscAssertPointer(info, 3);
9686:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9687:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9688:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9689:   MatCheckPreallocated(mat, 1);
9690:   PetscUseTypeMethod(mat, iccfactor, row, info);
9691:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9692:   PetscFunctionReturn(PETSC_SUCCESS);
9693: }

9695: /*@
9696:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9697:   ghosted ones.

9699:   Not Collective

9701:   Input Parameters:
9702: + mat  - the matrix
9703: - diag - the diagonal values, including ghost ones

9705:   Level: developer

9707:   Notes:
9708:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9710:   `diag` is a sequential vector that has a length which is the same as the local (ghosted) length of the vector associated with
9711:   the matrix's `ISLocalToGlobalMapping` set with `MatSetLocalToGlobalMapping()`.

9713:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`.

9715: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`, `MatSetLocalToGlobalMapping()`, `ISLocalToGlobalMapping`
9716: @*/
9717: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9718: {
9719:   PetscMPIInt size;

9721:   PetscFunctionBegin;

9726:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9727:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9728:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9729:   if (size == 1) {
9730:     PetscInt n, m;
9731:     PetscCall(VecGetSize(diag, &n));
9732:     PetscCall(MatGetSize(mat, NULL, &m));
9733:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9734:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9735:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9736:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9737:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9738:   PetscFunctionReturn(PETSC_SUCCESS);
9739: }

9741: /*@
9742:   MatGetInertia - Gets the inertia from a factored matrix

9744:   Collective

9746:   Input Parameter:
9747: . mat - the matrix

9749:   Output Parameters:
9750: + nneg  - number of negative eigenvalues
9751: . nzero - number of zero eigenvalues
9752: - npos  - number of positive eigenvalues

9754:   Level: advanced

9756:   Note:
9757:   Matrix must have been factored by `MatCholeskyFactor()`

9759: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9760: @*/
9761: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9762: {
9763:   PetscFunctionBegin;
9766:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9767:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9768:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9769:   PetscFunctionReturn(PETSC_SUCCESS);
9770: }

9772: /*@
9773:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9775:   Neighbor-wise Collective

9777:   Input Parameters:
9778: + mat - the factored matrix obtained with `MatGetFactor()`
9779: - b   - the right-hand-side vectors

9781:   Output Parameter:
9782: . x - the result vectors

9784:   Level: developer

9786:   Note:
9787:   The vectors `b` and `x` cannot be the same. I.e., one cannot
9788:   call `MatSolves`(A,x,x).

9790: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatGetFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9791: @*/
9792: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9793: {
9794:   PetscFunctionBegin;
9797:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9798:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9799:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9801:   MatCheckPreallocated(mat, 1);
9802:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9803:   PetscUseTypeMethod(mat, solves, b, x);
9804:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9805:   PetscFunctionReturn(PETSC_SUCCESS);
9806: }

9808: /*@
9809:   MatIsSymmetric - Test whether a matrix is symmetric

9811:   Collective

9813:   Input Parameters:
9814: + A   - the matrix to test
9815: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9817:   Output Parameter:
9818: . flg - the result

9820:   Level: intermediate

9822:   Notes:
9823:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9825:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9827:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9828:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9829:   have been set then `MatIsSymmetric()` does not need to perform any computations and returns immediately with the result.

9831: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9832:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9833: @*/
9834: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9835: {
9836:   PetscFunctionBegin;
9838:   PetscAssertPointer(flg, 3);
9839:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9840:   else {
9841:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9842:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9843:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9844:   }
9845:   PetscFunctionReturn(PETSC_SUCCESS);
9846: }

9848: /*@
9849:   MatIsHermitian - Test whether a matrix is Hermitian

9851:   Collective

9853:   Input Parameters:
9854: + A   - the matrix to test
9855: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9857:   Output Parameter:
9858: . flg - the result

9860:   Level: intermediate

9862:   Notes:
9863:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9865:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9867:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9868:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9869:   have been set then `MatIsHermitian()` does not need to perform any computations and returns immediately with the result.

9871: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9872:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9873: @*/
9874: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9875: {
9876:   PetscFunctionBegin;
9878:   PetscAssertPointer(flg, 3);
9879:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9880:   else {
9881:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9882:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9883:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9884:   }
9885:   PetscFunctionReturn(PETSC_SUCCESS);
9886: }

9888: /*@
9889:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9891:   Not Collective

9893:   Input Parameter:
9894: . A - the matrix to check

9896:   Output Parameters:
9897: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9898: - flg - the result (only valid if set is `PETSC_TRUE`)

9900:   Level: advanced

9902:   Notes:
9903:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9904:   if you want it explicitly checked

9906:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9907:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9909: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9910: @*/
9911: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9912: {
9913:   PetscFunctionBegin;
9915:   PetscAssertPointer(set, 2);
9916:   PetscAssertPointer(flg, 3);
9917:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9918:     *set = PETSC_TRUE;
9919:     *flg = PetscBool3ToBool(A->symmetric);
9920:   } else *set = PETSC_FALSE;
9921:   PetscFunctionReturn(PETSC_SUCCESS);
9922: }

9924: /*@
9925:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9927:   Not Collective

9929:   Input Parameter:
9930: . A - the matrix to check

9932:   Output Parameters:
9933: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9934: - flg - the result (only valid if set is `PETSC_TRUE`)

9936:   Level: advanced

9938:   Notes:
9939:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9941:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9942:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9944: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9945: @*/
9946: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9947: {
9948:   PetscFunctionBegin;
9950:   PetscAssertPointer(set, 2);
9951:   PetscAssertPointer(flg, 3);
9952:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9953:     *set = PETSC_TRUE;
9954:     *flg = PetscBool3ToBool(A->spd);
9955:   } else *set = PETSC_FALSE;
9956:   PetscFunctionReturn(PETSC_SUCCESS);
9957: }

9959: /*@
9960:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9962:   Not Collective

9964:   Input Parameter:
9965: . A - the matrix to check

9967:   Output Parameters:
9968: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9969: - flg - the result (only valid if set is `PETSC_TRUE`)

9971:   Level: advanced

9973:   Notes:
9974:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9975:   if you want it explicitly checked

9977:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9978:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9980: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9981: @*/
9982: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9983: {
9984:   PetscFunctionBegin;
9986:   PetscAssertPointer(set, 2);
9987:   PetscAssertPointer(flg, 3);
9988:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9989:     *set = PETSC_TRUE;
9990:     *flg = PetscBool3ToBool(A->hermitian);
9991:   } else *set = PETSC_FALSE;
9992:   PetscFunctionReturn(PETSC_SUCCESS);
9993: }

9995: /*@
9996:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9998:   Collective

10000:   Input Parameter:
10001: . A - the matrix to test

10003:   Output Parameter:
10004: . flg - the result

10006:   Level: intermediate

10008:   Notes:
10009:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

10011:   One can declare that a matrix is structurally symmetric with `MatSetOption`(mat,`MAT_STRUCTURALLY_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain structurally
10012:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
10013:   have been set then `MatIsStructurallySymmetric()` does not need to perform any computations and returns immediately with the result.

10015: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
10016: @*/
10017: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
10018: {
10019:   PetscFunctionBegin;
10021:   PetscAssertPointer(flg, 2);
10022:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
10023:   else {
10024:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
10025:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
10026:   }
10027:   PetscFunctionReturn(PETSC_SUCCESS);
10028: }

10030: /*@
10031:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

10033:   Not Collective

10035:   Input Parameter:
10036: . A - the matrix to check

10038:   Output Parameters:
10039: + set - `PETSC_TRUE` if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
10040: - flg - the result (only valid if set is `PETSC_TRUE`)

10042:   Level: advanced

10044:   Notes:
10045:   One can declare that a matrix is structurally symmetric with `MatSetOption`(mat,`MAT_STRUCTURALLY_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain structurally
10046:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10048:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

10050: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
10051: @*/
10052: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
10053: {
10054:   PetscFunctionBegin;
10056:   PetscAssertPointer(set, 2);
10057:   PetscAssertPointer(flg, 3);
10058:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
10059:     *set = PETSC_TRUE;
10060:     *flg = PetscBool3ToBool(A->structurally_symmetric);
10061:   } else *set = PETSC_FALSE;
10062:   PetscFunctionReturn(PETSC_SUCCESS);
10063: }

10065: /*@
10066:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10067:   to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10069:   Not Collective

10071:   Input Parameter:
10072: . mat - the matrix

10074:   Output Parameters:
10075: + nstash    - the size of the stash
10076: . reallocs  - the number of additional mallocs incurred.
10077: . bnstash   - the size of the block stash
10078: - breallocs - the number of additional mallocs incurred.in the block stash

10080:   Level: advanced

10082: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10083: @*/
10084: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10085: {
10086:   PetscFunctionBegin;
10087:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10088:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10089:   PetscFunctionReturn(PETSC_SUCCESS);
10090: }

10092: /*@
10093:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10094:   parallel layout, `PetscLayout` for rows and columns

10096:   Collective

10098:   Input Parameter:
10099: . mat - the matrix

10101:   Output Parameters:
10102: + right - (optional) vector that the matrix can be multiplied against
10103: - left  - (optional) vector that the matrix vector product can be stored in

10105:   Options Database Key:
10106: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10108:   Level: advanced

10110:   Notes:
10111:   The blocksize of the returned vectors is determined by the row and column block sizes set with `MatSetBlockSizes()` or the single blocksize (same for both) set by `MatSetBlockSize()`.

10113:   The `VecType` of the created vectors is determined by the `MatType` of `mat`. This can be overridden by using `MatSetVecType()` or the option `-mat_vec_type`.

10115:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10117:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10118:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10120: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10121: @*/
10122: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10123: {
10124:   PetscFunctionBegin;
10127:   if (mat->ops->getvecs) {
10128:     PetscUseTypeMethod(mat, getvecs, right, left);
10129:   } else {
10130:     if (right) {
10131:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10132:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10133:       PetscCall(VecSetType(*right, mat->defaultvectype));
10134: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10135:       if (mat->boundtocpu && mat->bindingpropagates) {
10136:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10137:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10138:       }
10139: #endif
10140:     }
10141:     if (left) {
10142:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10143:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10144:       PetscCall(VecSetType(*left, mat->defaultvectype));
10145: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10146:       if (mat->boundtocpu && mat->bindingpropagates) {
10147:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10148:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10149:       }
10150: #endif
10151:     }
10152:   }
10153:   PetscFunctionReturn(PETSC_SUCCESS);
10154: }

10156: /*@
10157:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10158:   with default values.

10160:   Not Collective

10162:   Input Parameter:
10163: . info - the `MatFactorInfo` data structure

10165:   Level: developer

10167:   Notes:
10168:   The solvers are generally used through the `KSP` and `PC` objects, for example
10169:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10171:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10173: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10174: @*/
10175: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10176: {
10177:   PetscFunctionBegin;
10178:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10179:   PetscFunctionReturn(PETSC_SUCCESS);
10180: }

10182: /*@
10183:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10185:   Collective

10187:   Input Parameters:
10188: + mat - the factored matrix
10189: - is  - the index set defining the Schur indices (0-based)

10191:   Level: advanced

10193:   Notes:
10194:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10196:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10198:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10200: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10201:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10202: @*/
10203: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10204: {
10205:   PetscErrorCode (*f)(Mat, IS);

10207:   PetscFunctionBegin;
10212:   PetscCheckSameComm(mat, 1, is, 2);
10213:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10214:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10215:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10216:   PetscCall((*f)(mat, is));
10217:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10218:   PetscFunctionReturn(PETSC_SUCCESS);
10219: }

10221: /*@
10222:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10224:   Logically Collective

10226:   Input Parameters:
10227: + F      - the factored matrix obtained by calling `MatGetFactor()`
10228: . S      - location where to return the Schur complement, can be `NULL`
10229: - status - the status of the Schur complement matrix, can be `NULL`

10231:   Level: advanced

10233:   Notes:
10234:   You must call `MatFactorSetSchurIS()` before calling this routine.

10236:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10238:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10239:   The caller must destroy the object when it is no longer needed.
10240:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10242:   Use `MatFactorGetSchurComplement()` to get access to the Schur complement matrix inside the factored matrix instead of making a copy of it (which this function does)

10244:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10246:   Developer Note:
10247:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10248:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10250: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10251: @*/
10252: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10253: {
10254:   PetscFunctionBegin;
10256:   if (S) PetscAssertPointer(S, 2);
10257:   if (status) PetscAssertPointer(status, 3);
10258:   if (S) {
10259:     PetscErrorCode (*f)(Mat, Mat *);

10261:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10262:     if (f) PetscCall((*f)(F, S));
10263:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10264:   }
10265:   if (status) *status = F->schur_status;
10266:   PetscFunctionReturn(PETSC_SUCCESS);
10267: }

10269: /*@
10270:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10272:   Logically Collective

10274:   Input Parameters:
10275: + F      - the factored matrix obtained by calling `MatGetFactor()`
10276: . S      - location where to return the Schur complement, can be `NULL`
10277: - status - the status of the Schur complement matrix, can be `NULL`

10279:   Level: advanced

10281:   Notes:
10282:   You must call `MatFactorSetSchurIS()` before calling this routine.

10284:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10286:   The routine returns a the Schur Complement stored within the data structures of the solver.

10288:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10290:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10292:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10294:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10296: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10297: @*/
10298: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10299: {
10300:   PetscFunctionBegin;
10302:   if (S) {
10303:     PetscAssertPointer(S, 2);
10304:     *S = F->schur;
10305:   }
10306:   if (status) {
10307:     PetscAssertPointer(status, 3);
10308:     *status = F->schur_status;
10309:   }
10310:   PetscFunctionReturn(PETSC_SUCCESS);
10311: }

10313: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10314: {
10315:   Mat S = F->schur;

10317:   PetscFunctionBegin;
10318:   switch (F->schur_status) {
10319:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10320:   case MAT_FACTOR_SCHUR_INVERTED:
10321:     if (S) {
10322:       S->ops->solve             = NULL;
10323:       S->ops->matsolve          = NULL;
10324:       S->ops->solvetranspose    = NULL;
10325:       S->ops->matsolvetranspose = NULL;
10326:       S->ops->solveadd          = NULL;
10327:       S->ops->solvetransposeadd = NULL;
10328:       S->factortype             = MAT_FACTOR_NONE;
10329:       PetscCall(PetscFree(S->solvertype));
10330:     }
10331:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10332:     break;
10333:   default:
10334:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10335:   }
10336:   PetscFunctionReturn(PETSC_SUCCESS);
10337: }

10339: /*@
10340:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10342:   Logically Collective

10344:   Input Parameters:
10345: + F      - the factored matrix obtained by calling `MatGetFactor()`
10346: . S      - location where the Schur complement is stored
10347: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10349:   Level: advanced

10351: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10352: @*/
10353: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10354: {
10355:   PetscFunctionBegin;
10357:   if (S) {
10359:     *S = NULL;
10360:   }
10361:   F->schur_status = status;
10362:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10363:   PetscFunctionReturn(PETSC_SUCCESS);
10364: }

10366: /*@
10367:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10369:   Logically Collective

10371:   Input Parameters:
10372: + F   - the factored matrix obtained by calling `MatGetFactor()`
10373: . rhs - location where the right-hand side of the Schur complement system is stored
10374: - sol - location where the solution of the Schur complement system has to be returned

10376:   Level: advanced

10378:   Notes:
10379:   The sizes of the vectors should match the size of the Schur complement

10381:   Must be called after `MatFactorSetSchurIS()`

10383: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10384: @*/
10385: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10386: {
10387:   PetscFunctionBegin;
10394:   PetscCheckSameComm(F, 1, rhs, 2);
10395:   PetscCheckSameComm(F, 1, sol, 3);
10396:   PetscCall(MatFactorFactorizeSchurComplement(F));
10397:   switch (F->schur_status) {
10398:   case MAT_FACTOR_SCHUR_FACTORED:
10399:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10400:     break;
10401:   case MAT_FACTOR_SCHUR_INVERTED:
10402:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10403:     break;
10404:   default:
10405:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10406:   }
10407:   PetscFunctionReturn(PETSC_SUCCESS);
10408: }

10410: /*@
10411:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10413:   Logically Collective

10415:   Input Parameters:
10416: + F   - the factored matrix obtained by calling `MatGetFactor()`
10417: . rhs - location where the right-hand side of the Schur complement system is stored
10418: - sol - location where the solution of the Schur complement system has to be returned

10420:   Level: advanced

10422:   Notes:
10423:   The sizes of the vectors should match the size of the Schur complement

10425:   Must be called after `MatFactorSetSchurIS()`

10427: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10428: @*/
10429: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10430: {
10431:   PetscFunctionBegin;
10438:   PetscCheckSameComm(F, 1, rhs, 2);
10439:   PetscCheckSameComm(F, 1, sol, 3);
10440:   PetscCall(MatFactorFactorizeSchurComplement(F));
10441:   switch (F->schur_status) {
10442:   case MAT_FACTOR_SCHUR_FACTORED:
10443:     PetscCall(MatSolve(F->schur, rhs, sol));
10444:     break;
10445:   case MAT_FACTOR_SCHUR_INVERTED:
10446:     PetscCall(MatMult(F->schur, rhs, sol));
10447:     break;
10448:   default:
10449:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10450:   }
10451:   PetscFunctionReturn(PETSC_SUCCESS);
10452: }

10454: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10455: #if PetscDefined(HAVE_CUDA)
10456: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10457: #endif

10459: /* Schur status updated in the interface */
10460: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10461: {
10462:   Mat S = F->schur;

10464:   PetscFunctionBegin;
10465:   if (S) {
10466:     PetscMPIInt size;
10467:     PetscBool   isdense, isdensecuda;

10469:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10470:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10471:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10472:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10473:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10474:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10475:     if (isdense) {
10476:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10477:     } else if (isdensecuda) {
10478: #if PetscDefined(HAVE_CUDA)
10479:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10480: #endif
10481:     }
10482:     // HIP??????????????
10483:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10484:   }
10485:   PetscFunctionReturn(PETSC_SUCCESS);
10486: }

10488: /*@
10489:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10491:   Logically Collective

10493:   Input Parameter:
10494: . F - the factored matrix obtained by calling `MatGetFactor()`

10496:   Level: advanced

10498:   Notes:
10499:   Must be called after `MatFactorSetSchurIS()`.

10501:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10503: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10504: @*/
10505: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10506: {
10507:   PetscFunctionBegin;
10510:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10511:   PetscCall(MatFactorFactorizeSchurComplement(F));
10512:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10513:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10514:   PetscFunctionReturn(PETSC_SUCCESS);
10515: }

10517: /*@
10518:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10520:   Logically Collective

10522:   Input Parameter:
10523: . F - the factored matrix obtained by calling `MatGetFactor()`

10525:   Level: advanced

10527:   Note:
10528:   Must be called after `MatFactorSetSchurIS()`

10530: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10531: @*/
10532: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10533: {
10534:   MatFactorInfo info;

10536:   PetscFunctionBegin;
10539:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10540:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10541:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10542:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10543:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10544:   } else {
10545:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10546:   }
10547:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10548:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10549:   PetscFunctionReturn(PETSC_SUCCESS);
10550: }

10552: /*@
10553:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10555:   Neighbor-wise Collective

10557:   Input Parameters:
10558: + A     - the matrix
10559: . P     - the projection matrix
10560: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10561: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10562:           if the result is a dense matrix this is irrelevant

10564:   Output Parameter:
10565: . C - the product matrix

10567:   Level: intermediate

10569:   Notes:
10570:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10572:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10573:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10575:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10577:   Developer Note:
10578:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10580: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10581: @*/
10582: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10583: {
10584:   PetscFunctionBegin;
10585:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10586:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10588:   if (scall == MAT_INITIAL_MATRIX) {
10589:     PetscCall(MatProductCreate(A, P, NULL, C));
10590:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10591:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10592:     PetscCall(MatProductSetFill(*C, fill));

10594:     (*C)->product->api_user = PETSC_TRUE;
10595:     PetscCall(MatProductSetFromOptions(*C));
10596:     PetscCheck((*C)->ops->productsymbolic, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "MatProduct %s not supported for A %s and P %s", MatProductTypes[MATPRODUCT_PtAP], ((PetscObject)A)->type_name, ((PetscObject)P)->type_name);
10597:     PetscCall(MatProductSymbolic(*C));
10598:   } else { /* scall == MAT_REUSE_MATRIX */
10599:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10600:   }

10602:   PetscCall(MatProductNumeric(*C));
10603:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10604:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10605:     (*C)->spd = A->spd;
10606:   }
10607:   PetscFunctionReturn(PETSC_SUCCESS);
10608: }

10610: /*@
10611:   MatRARt - Creates the matrix product $C = R * A * R^T$

10613:   Neighbor-wise Collective

10615:   Input Parameters:
10616: + A     - the matrix
10617: . R     - the projection matrix
10618: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10619: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10620:           if the result is a dense matrix this is irrelevant

10622:   Output Parameter:
10623: . C - the product matrix

10625:   Level: intermediate

10627:   Notes:
10628:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10630:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10631:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10633:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10634:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10635:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10636:   We recommend using `MatPtAP()` when possible.

10638:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10640: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10641: @*/
10642: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10643: {
10644:   PetscFunctionBegin;
10645:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10646:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10648:   if (scall == MAT_INITIAL_MATRIX) {
10649:     PetscCall(MatProductCreate(A, R, NULL, C));
10650:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10651:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10652:     PetscCall(MatProductSetFill(*C, fill));

10654:     (*C)->product->api_user = PETSC_TRUE;
10655:     PetscCall(MatProductSetFromOptions(*C));
10656:     PetscCheck((*C)->ops->productsymbolic, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "MatProduct %s not supported for A %s and R %s", MatProductTypes[MATPRODUCT_RARt], ((PetscObject)A)->type_name, ((PetscObject)R)->type_name);
10657:     PetscCall(MatProductSymbolic(*C));
10658:   } else { /* scall == MAT_REUSE_MATRIX */
10659:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10660:   }

10662:   PetscCall(MatProductNumeric(*C));
10663:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10664:   PetscFunctionReturn(PETSC_SUCCESS);
10665: }

10667: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10668: {
10669:   PetscBool flg = PETSC_TRUE;

10671:   PetscFunctionBegin;
10672:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10673:   if (scall == MAT_INITIAL_MATRIX) {
10674:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10675:     PetscCall(MatProductCreate(A, B, NULL, C));
10676:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10677:     PetscCall(MatProductSetFill(*C, fill));
10678:   } else { /* scall == MAT_REUSE_MATRIX */
10679:     Mat_Product *product = (*C)->product;

10681:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10682:     if (flg && product && product->type != ptype) {
10683:       PetscCall(MatProductClear(*C));
10684:       product = NULL;
10685:     }
10686:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10687:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10688:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10689:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10690:       product        = (*C)->product;
10691:       product->fill  = fill;
10692:       product->clear = PETSC_TRUE;
10693:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10694:       flg = PETSC_FALSE;
10695:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10696:     }
10697:   }
10698:   if (flg) {
10699:     (*C)->product->api_user = PETSC_TRUE;
10700:     PetscCall(MatProductSetType(*C, ptype));
10701:     PetscCall(MatProductSetFromOptions(*C));
10702:     PetscCall(MatProductSymbolic(*C));
10703:   }
10704:   PetscCall(MatProductNumeric(*C));
10705:   PetscFunctionReturn(PETSC_SUCCESS);
10706: }

10708: /*@
10709:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10711:   Neighbor-wise Collective

10713:   Input Parameters:
10714: + A     - the left matrix
10715: . B     - the right matrix
10716: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10717: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10718:           if the result is a dense matrix this is irrelevant

10720:   Output Parameter:
10721: . C - the product matrix

10723:   Notes:
10724:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10726:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call and C was obtained from a previous
10727:   call to this function with `MAT_INITIAL_MATRIX`.

10729:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10731:   In the special case where matrix `B` (and hence `C`) are dense you can create the correctly sized matrix `C` yourself and then call this routine with `MAT_REUSE_MATRIX`,
10732:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10734:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10736:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10737:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10739:   Example of Usage:
10740: .vb
10741:      MatProductCreate(A,B,NULL,&C);
10742:      MatProductSetType(C,MATPRODUCT_AB);
10743:      MatProductSymbolic(C);
10744:      MatProductNumeric(C); // compute C=A * B
10745:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10746:      MatProductNumeric(C);
10747:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10748:      MatProductNumeric(C);
10749: .ve

10751:   Level: intermediate

10753: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10754: @*/
10755: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10756: {
10757:   PetscFunctionBegin;
10758:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10759:   PetscFunctionReturn(PETSC_SUCCESS);
10760: }

10762: /*@
10763:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10765:   Neighbor-wise Collective

10767:   Input Parameters:
10768: + A     - the left matrix
10769: . B     - the right matrix
10770: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10771: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10773:   Output Parameter:
10774: . C - the product matrix

10776:   Options Database Key:
10777: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10778:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10779:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10781:   Level: intermediate

10783:   Notes:
10784:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10786:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10788:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10789:   actually needed.

10791:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10792:   and for pairs of `MATMPIDENSE` matrices.

10794:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10795:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10797:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10799: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10800: @*/
10801: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10802: {
10803:   PetscFunctionBegin;
10804:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10805:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10806:   PetscFunctionReturn(PETSC_SUCCESS);
10807: }

10809: /*@
10810:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10812:   Neighbor-wise Collective

10814:   Input Parameters:
10815: + A     - the left matrix
10816: . B     - the right matrix
10817: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10818: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10820:   Output Parameter:
10821: . C - the product matrix

10823:   Level: intermediate

10825:   Notes:
10826:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10828:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10830:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10831:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10833:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10834:   actually needed.

10836:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10837:   which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.

10839:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10841: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10842: @*/
10843: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10844: {
10845:   PetscFunctionBegin;
10846:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10847:   PetscFunctionReturn(PETSC_SUCCESS);
10848: }

10850: /*@
10851:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10853:   Neighbor-wise Collective

10855:   Input Parameters:
10856: + A     - the left matrix
10857: . B     - the middle matrix
10858: . C     - the right matrix
10859: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10860: - fill  - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10861:           if the result is a dense matrix this is irrelevant

10863:   Output Parameter:
10864: . D - the product matrix

10866:   Level: intermediate

10868:   Notes:
10869:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10871:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10873:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10874:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10876:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10877:   actually needed.

10879:   If you have many matrices with the same non-zero structure to multiply, you
10880:   should use `MAT_REUSE_MATRIX` in all calls but the first

10882:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10884: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10885: @*/
10886: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10887: {
10888:   PetscFunctionBegin;
10889:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10890:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10892:   if (scall == MAT_INITIAL_MATRIX) {
10893:     PetscCall(MatProductCreate(A, B, C, D));
10894:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10895:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10896:     PetscCall(MatProductSetFill(*D, fill));

10898:     (*D)->product->api_user = PETSC_TRUE;
10899:     PetscCall(MatProductSetFromOptions(*D));
10900:     PetscCheck((*D)->ops->productsymbolic, PetscObjectComm((PetscObject)*D), PETSC_ERR_SUP, "MatProduct %s not supported for A %s, B %s and C %s", MatProductTypes[MATPRODUCT_ABC], ((PetscObject)A)->type_name, ((PetscObject)B)->type_name,
10901:                ((PetscObject)C)->type_name);
10902:     PetscCall(MatProductSymbolic(*D));
10903:   } else { /* user may change input matrices when REUSE */
10904:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10905:   }
10906:   PetscCall(MatProductNumeric(*D));
10907:   PetscFunctionReturn(PETSC_SUCCESS);
10908: }

10910: /*@
10911:   MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.

10913:   Collective

10915:   Input Parameters:
10916: + mat      - the matrix
10917: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10918: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10919: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10921:   Output Parameter:
10922: . matredundant - redundant matrix

10924:   Level: advanced

10926:   Notes:
10927:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10928:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10930:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10931:   calling it.

10933:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10935: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10936: @*/
10937: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10938: {
10939:   MPI_Comm       comm;
10940:   PetscMPIInt    size;
10941:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10942:   Mat_Redundant *redund     = NULL;
10943:   PetscSubcomm   psubcomm   = NULL;
10944:   MPI_Comm       subcomm_in = subcomm;
10945:   Mat           *matseq;
10946:   IS             isrow, iscol;
10947:   PetscBool      newsubcomm = PETSC_FALSE;

10949:   PetscFunctionBegin;
10951:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10952:     PetscAssertPointer(*matredundant, 5);
10954:   }

10956:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10957:   if (size == 1 || nsubcomm == 1) {
10958:     if (reuse == MAT_INITIAL_MATRIX) {
10959:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10960:     } else {
10961:       PetscCheck(*matredundant != mat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
10962:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10963:     }
10964:     PetscFunctionReturn(PETSC_SUCCESS);
10965:   }

10967:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10968:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10969:   MatCheckPreallocated(mat, 1);

10971:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10972:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10973:     /* create psubcomm, then get subcomm */
10974:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10975:     PetscCallMPI(MPI_Comm_size(comm, &size));
10976:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10978:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10979:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10980:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10981:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10982:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10983:     newsubcomm = PETSC_TRUE;
10984:     PetscCall(PetscSubcommDestroy(&psubcomm));
10985:   }

10987:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10988:   if (reuse == MAT_INITIAL_MATRIX) {
10989:     mloc_sub = PETSC_DECIDE;
10990:     nloc_sub = PETSC_DECIDE;
10991:     if (bs < 1) {
10992:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10993:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10994:     } else {
10995:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10996:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10997:     }
10998:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10999:     rstart = rend - mloc_sub;
11000:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
11001:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
11002:     PetscCall(ISSetIdentity(iscol));
11003:   } else { /* reuse == MAT_REUSE_MATRIX */
11004:     PetscCheck(*matredundant != mat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
11005:     /* retrieve subcomm */
11006:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
11007:     redund = (*matredundant)->redundant;
11008:     isrow  = redund->isrow;
11009:     iscol  = redund->iscol;
11010:     matseq = redund->matseq;
11011:   }
11012:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

11014:   /* get matredundant over subcomm */
11015:   if (reuse == MAT_INITIAL_MATRIX) {
11016:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

11018:     /* create a supporting struct and attach it to C for reuse */
11019:     PetscCall(PetscNew(&redund));
11020:     (*matredundant)->redundant = redund;
11021:     redund->isrow              = isrow;
11022:     redund->iscol              = iscol;
11023:     redund->matseq             = matseq;
11024:     if (newsubcomm) {
11025:       redund->subcomm = subcomm;
11026:     } else {
11027:       redund->subcomm = MPI_COMM_NULL;
11028:     }
11029:   } else {
11030:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
11031:   }
11032: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
11033:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
11034:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
11035:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
11036:   }
11037: #endif
11038:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
11039:   PetscFunctionReturn(PETSC_SUCCESS);
11040: }

11042: /*@
11043:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
11044:   a given `Mat`. Each submatrix can span multiple procs.

11046:   Collective

11048:   Input Parameters:
11049: + mat     - the matrix
11050: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
11051: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11053:   Output Parameter:
11054: . subMat - parallel sub-matrices each spanning a given `subcomm`

11056:   Level: advanced

11058:   Notes:
11059:   The submatrix partition across processes is dictated by `subComm` a
11060:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
11061:   is not restricted to be grouped with consecutive original MPI processes.

11063:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11064:   map directly to the layout of the original matrix [wrt the local
11065:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
11066:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11067:   the `subMat`. However the offDiagMat looses some columns - and this is
11068:   reconstructed with `MatSetValues()`

11070:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11072: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11073: @*/
11074: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11075: {
11076:   PetscMPIInt commsize, subCommSize;

11078:   PetscFunctionBegin;
11079:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11080:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11081:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11083:   PetscCheck(scall != MAT_REUSE_MATRIX || *subMat != mat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
11084:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11085:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11086:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11087:   PetscFunctionReturn(PETSC_SUCCESS);
11088: }

11090: /*@
11091:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11093:   Not Collective

11095:   Input Parameters:
11096: + mat   - matrix to extract local submatrix from
11097: . isrow - local row indices for submatrix
11098: - iscol - local column indices for submatrix

11100:   Output Parameter:
11101: . submat - the submatrix

11103:   Level: intermediate

11105:   Notes:
11106:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11108:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11109:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11111:   `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11112:   `MatSetValuesBlockedLocal()` will also be implemented.

11114:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11115:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11117: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11118: @*/
11119: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11120: {
11121:   PetscFunctionBegin;
11125:   PetscCheckSameComm(isrow, 2, iscol, 3);
11126:   PetscAssertPointer(submat, 4);
11127:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11129:   if (mat->ops->getlocalsubmatrix) {
11130:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11131:   } else {
11132:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11133:   }
11134:   (*submat)->assembled = mat->assembled;
11135:   PetscFunctionReturn(PETSC_SUCCESS);
11136: }

11138: /*@
11139:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11141:   Not Collective

11143:   Input Parameters:
11144: + mat    - matrix to extract local submatrix from
11145: . isrow  - local row indices for submatrix
11146: . iscol  - local column indices for submatrix
11147: - submat - the submatrix

11149:   Level: intermediate

11151: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11152: @*/
11153: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11154: {
11155:   PetscFunctionBegin;
11159:   PetscCheckSameComm(isrow, 2, iscol, 3);
11160:   PetscAssertPointer(submat, 4);

11163:   if (mat->ops->restorelocalsubmatrix) {
11164:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11165:   } else {
11166:     PetscCall(MatDestroy(submat));
11167:   }
11168:   *submat = NULL;
11169:   PetscFunctionReturn(PETSC_SUCCESS);
11170: }

11172: /*@
11173:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11175:   Collective

11177:   Input Parameter:
11178: . mat - the matrix

11180:   Output Parameter:
11181: . is - if any rows have zero diagonals this contains the list of them

11183:   Level: developer

11185: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11186: @*/
11187: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11188: {
11189:   PetscFunctionBegin;
11192:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11193:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11195:   if (!mat->ops->findzerodiagonals) {
11196:     Vec                diag;
11197:     const PetscScalar *a;
11198:     PetscInt          *rows;
11199:     PetscInt           rStart, rEnd, r, nrow = 0;

11201:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11202:     PetscCall(MatGetDiagonal(mat, diag));
11203:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11204:     PetscCall(VecGetArrayRead(diag, &a));
11205:     for (r = 0; r < rEnd - rStart; ++r)
11206:       if (a[r] == 0.0) ++nrow;
11207:     PetscCall(PetscMalloc1(nrow, &rows));
11208:     nrow = 0;
11209:     for (r = 0; r < rEnd - rStart; ++r)
11210:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11211:     PetscCall(VecRestoreArrayRead(diag, &a));
11212:     PetscCall(VecDestroy(&diag));
11213:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11214:   } else {
11215:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11216:   }
11217:   PetscFunctionReturn(PETSC_SUCCESS);
11218: }

11220: /*@
11221:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11223:   Collective

11225:   Input Parameter:
11226: . mat - the matrix

11228:   Output Parameter:
11229: . is - contains the list of rows with off block diagonal entries

11231:   Level: developer

11233: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11234: @*/
11235: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11236: {
11237:   PetscFunctionBegin;
11240:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11241:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11243:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11244:   PetscFunctionReturn(PETSC_SUCCESS);
11245: }

11247: /*@
11248:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11250:   Collective; No Fortran Support

11252:   Input Parameter:
11253: . mat - the matrix

11255:   Output Parameter:
11256: . values - the block inverses in column major order (FORTRAN-like)

11258:   Level: advanced

11260:   Notes:
11261:   The size of the blocks is determined by the block size of the matrix.

11263:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11265:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11267: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11268: @*/
11269: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11270: {
11271:   PetscFunctionBegin;
11273:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11274:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11275:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11276:   PetscFunctionReturn(PETSC_SUCCESS);
11277: }

11279: /*@
11280:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11282:   Collective; No Fortran Support

11284:   Input Parameters:
11285: + mat     - the matrix
11286: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11287: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11289:   Output Parameter:
11290: . values - the block inverses in column major order (FORTRAN-like)

11292:   Level: advanced

11294:   Notes:
11295:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11297:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11299: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11300: @*/
11301: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11302: {
11303:   PetscFunctionBegin;
11305:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11306:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11307:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11308:   PetscFunctionReturn(PETSC_SUCCESS);
11309: }

11311: /*@
11312:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11314:   Collective

11316:   Input Parameters:
11317: + A - the matrix
11318: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.

11320:   Level: advanced

11322:   Note:
11323:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11325: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11326: @*/
11327: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11328: {
11329:   const PetscScalar *vals;
11330:   PetscInt          *dnnz;
11331:   PetscInt           m, rstart, rend, bs, i, j;

11333:   PetscFunctionBegin;
11334:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11335:   PetscCall(MatGetBlockSize(A, &bs));
11336:   PetscCall(MatGetLocalSize(A, &m, NULL));
11337:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11338:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11339:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11340:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11341:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11342:   PetscCall(PetscFree(dnnz));
11343:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11344:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11345:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11346:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11347:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11348:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11349:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11350:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11351:   PetscFunctionReturn(PETSC_SUCCESS);
11352: }

11354: /*@
11355:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11356:   via `MatTransposeColoringCreate()`.

11358:   Collective

11360:   Input Parameter:
11361: . c - coloring context

11363:   Level: intermediate

11365: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11366: @*/
11367: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11368: {
11369:   MatTransposeColoring matcolor = *c;

11371:   PetscFunctionBegin;
11372:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11373:   if (--((PetscObject)matcolor)->refct > 0) {
11374:     matcolor = NULL;
11375:     PetscFunctionReturn(PETSC_SUCCESS);
11376:   }

11378:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11379:   PetscCall(PetscFree(matcolor->rows));
11380:   PetscCall(PetscFree(matcolor->den2sp));
11381:   PetscCall(PetscFree(matcolor->colorforcol));
11382:   PetscCall(PetscFree(matcolor->columns));
11383:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11384:   PetscCall(PetscHeaderDestroy(c));
11385:   PetscFunctionReturn(PETSC_SUCCESS);
11386: }

11388: /*@
11389:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11390:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11391:   `MatTransposeColoring` to sparse `B`.

11393:   Collective

11395:   Input Parameters:
11396: + coloring - coloring context created with `MatTransposeColoringCreate()`
11397: - B        - sparse matrix

11399:   Output Parameter:
11400: . Btdense - dense matrix $B^T$

11402:   Level: developer

11404:   Note:
11405:   These are used internally for some implementations of `MatRARt()`

11407: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11408: @*/
11409: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11410: {
11411:   PetscFunctionBegin;

11416:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11417:   PetscFunctionReturn(PETSC_SUCCESS);
11418: }

11420: /*@
11421:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11422:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11423:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11424:   $C_{sp}$ from $C_{den}$.

11426:   Collective

11428:   Input Parameters:
11429: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11430: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11432:   Output Parameter:
11433: . Csp - sparse matrix

11435:   Level: developer

11437:   Note:
11438:   These are used internally for some implementations of `MatRARt()`

11440: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11441: @*/
11442: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11443: {
11444:   PetscFunctionBegin;

11449:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11450:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11451:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11452:   PetscFunctionReturn(PETSC_SUCCESS);
11453: }

11455: /*@
11456:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11458:   Collective

11460:   Input Parameters:
11461: + mat        - the matrix product C
11462: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11464:   Output Parameter:
11465: . color - the new coloring context

11467:   Level: intermediate

11469: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11470:           `MatTransColoringApplyDenToSp()`
11471: @*/
11472: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11473: {
11474:   MatTransposeColoring c;
11475:   MPI_Comm             comm;

11477:   PetscFunctionBegin;
11478:   PetscAssertPointer(color, 3);

11480:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11481:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11482:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11483:   c->ctype = iscoloring->ctype;
11484:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11485:   *color = c;
11486:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11487:   PetscFunctionReturn(PETSC_SUCCESS);
11488: }

11490: /*@
11491:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11492:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11494:   Not Collective

11496:   Input Parameter:
11497: . mat - the matrix

11499:   Output Parameter:
11500: . state - the current state

11502:   Level: intermediate

11504:   Notes:
11505:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11506:   different matrices

11508:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11510:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11512: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11513: @*/
11514: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11515: {
11516:   PetscFunctionBegin;
11518:   *state = mat->nonzerostate;
11519:   PetscFunctionReturn(PETSC_SUCCESS);
11520: }

11522: /*@
11523:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11524:   matrices from each process

11526:   Collective

11528:   Input Parameters:
11529: + comm   - the communicators the parallel matrix will live on
11530: . seqmat - the input sequential matrices
11531: . n      - number of local columns (or `PETSC_DECIDE`)
11532: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11534:   Output Parameter:
11535: . mpimat - the parallel matrix generated

11537:   Level: developer

11539:   Note:
11540:   The number of columns of the matrix in EACH process MUST be the same.

11542: .seealso: [](ch_matrices), `Mat`
11543: @*/
11544: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11545: {
11546:   PetscMPIInt size;

11548:   PetscFunctionBegin;
11549:   PetscCallMPI(MPI_Comm_size(comm, &size));
11550:   if (size == 1) {
11551:     if (reuse == MAT_INITIAL_MATRIX) {
11552:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11553:     } else {
11554:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11555:     }
11556:     PetscFunctionReturn(PETSC_SUCCESS);
11557:   }

11559:   PetscCheck(reuse != MAT_REUSE_MATRIX || seqmat != *mpimat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");

11561:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11562:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11563:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11564:   PetscFunctionReturn(PETSC_SUCCESS);
11565: }

11567: /*@
11568:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11570:   Collective

11572:   Input Parameters:
11573: + A - the matrix to create subdomains from
11574: - N - requested number of subdomains

11576:   Output Parameters:
11577: + n   - number of subdomains resulting on this MPI process
11578: - iss - `IS` list with indices of subdomains on this MPI process

11580:   Level: advanced

11582:   Note:
11583:   The number of subdomains must be smaller than the communicator size

11585: .seealso: [](ch_matrices), `Mat`, `IS`
11586: @*/
11587: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11588: {
11589:   MPI_Comm    comm, subcomm;
11590:   PetscMPIInt size, rank, color;
11591:   PetscInt    rstart, rend, k;

11593:   PetscFunctionBegin;
11594:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11595:   PetscCallMPI(MPI_Comm_size(comm, &size));
11596:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11597:   PetscCheck(N >= 1 && N < size, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "number of subdomains must be > 0 and < %d, got N = %" PetscInt_FMT, size, N);
11598:   *n    = 1;
11599:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11600:   color = rank / k;
11601:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11602:   PetscCall(PetscMalloc1(1, iss));
11603:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11604:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11605:   PetscCallMPI(MPI_Comm_free(&subcomm));
11606:   PetscFunctionReturn(PETSC_SUCCESS);
11607: }

11609: /*@
11610:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11612:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11613:   If they are not the same, uses `MatMatMatMult()`.

11615:   Once the coarse grid problem is constructed, correct for interpolation operators
11616:   that are not of full rank, which can legitimately happen in the case of non-nested
11617:   geometric multigrid.

11619:   Input Parameters:
11620: + restrct     - restriction operator
11621: . dA          - fine grid matrix
11622: . interpolate - interpolation operator
11623: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11624: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11626:   Output Parameter:
11627: . A - the Galerkin coarse matrix

11629:   Options Database Key:
11630: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11632:   Level: developer

11634:   Note:
11635:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11637: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11638: @*/
11639: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11640: {
11641:   IS  zerorows;
11642:   Vec diag;

11644:   PetscFunctionBegin;
11645:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11646:   /* Construct the coarse grid matrix */
11647:   if (interpolate == restrct) {
11648:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11649:   } else {
11650:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11651:   }

11653:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11654:      This can legitimately happen in the case of non-nested geometric multigrid.
11655:      In that event, we set the rows of the matrix to the rows of the identity,
11656:      ignoring the equations (as the RHS will also be zero). */

11658:   PetscCall(MatFindZeroRows(*A, &zerorows));

11660:   if (zerorows != NULL) { /* if there are any zero rows */
11661:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11662:     PetscCall(MatGetDiagonal(*A, diag));
11663:     PetscCall(VecISSet(diag, zerorows, 1.0));
11664:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11665:     PetscCall(VecDestroy(&diag));
11666:     PetscCall(ISDestroy(&zerorows));
11667:   }
11668:   PetscFunctionReturn(PETSC_SUCCESS);
11669: }

11671: /*@
11672:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11674:   Logically Collective

11676:   Input Parameters:
11677: + mat - the matrix
11678: . op  - the name of the operation
11679: - f   - the function that provides the operation

11681:   Level: developer

11683:   Example Usage:
11684: .vb
11685:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11687:   PetscCall(MatCreateXXX(comm, ..., &A));
11688:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11689: .ve

11691:   Notes:
11692:   See the file `include/petscmat.h` for a complete list of matrix
11693:   operations, which all have the form MATOP_<OPERATION>, where
11694:   <OPERATION> is the name (in all capital letters) of the
11695:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11697:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11698:   sequence as the usual matrix interface routines, since they
11699:   are intended to be accessed via the usual matrix interface
11700:   routines, e.g.,
11701: .vb
11702:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11703: .ve

11705:   In particular each function MUST return `PETSC_SUCCESS` on success and
11706:   nonzero on failure.

11708:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11710: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11711: @*/
11712: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11713: {
11714:   PetscFunctionBegin;
11717:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11718: #if !PetscDefined(USE_COMPLEX)
11719:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11720:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11721:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11722: #endif
11723:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11724:   PetscFunctionReturn(PETSC_SUCCESS);
11725: }

11727: /*@
11728:   MatGetOperation - Gets a matrix operation for any matrix type.

11730:   Not Collective

11732:   Input Parameters:
11733: + mat - the matrix
11734: - op  - the name of the operation

11736:   Output Parameter:
11737: . f - the function that provides the operation

11739:   Level: developer

11741:   Example Usage:
11742: .vb
11743:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11745:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11746: .ve

11748:   Notes:
11749:   See the file `include/petscmat.h` for a complete list of matrix
11750:   operations, which all have the form MATOP_<OPERATION>, where
11751:   <OPERATION> is the name (in all capital letters) of the
11752:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11754:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11756: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11757: @*/
11758: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11759: {
11760:   PetscFunctionBegin;
11762:   PetscAssertPointer(f, 3);
11763: #if !PetscDefined(USE_COMPLEX)
11764:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11765:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11766:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11767: #endif
11768:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11769:   PetscFunctionReturn(PETSC_SUCCESS);
11770: }

11772: /*@
11773:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11775:   Not Collective

11777:   Input Parameters:
11778: + mat - the matrix
11779: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11781:   Output Parameter:
11782: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11784:   Level: advanced

11786:   Note:
11787:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11789: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11790: @*/
11791: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11792: {
11793:   PetscFunctionBegin;
11795:   PetscAssertPointer(has, 3);
11796: #if !PetscDefined(USE_COMPLEX)
11797:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11798:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11799:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11800: #endif
11801:   if (op == MATOP_ADOT || op == MATOP_ANORM) {
11802:     /* MatADot() and MatANorm() fall back to MatMult() when the type has no method */
11803:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11804:     else PetscCall(MatHasOperation(mat, MATOP_MULT, has));
11805:     PetscFunctionReturn(PETSC_SUCCESS);
11806:   }
11807:   if (mat->ops->hasoperation) {
11808:     PetscUseTypeMethod(mat, hasoperation, op, has);
11809:   } else {
11810:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11811:     else {
11812:       *has = PETSC_FALSE;
11813:       if (op == MATOP_CREATE_SUBMATRIX) {
11814:         PetscMPIInt size;

11816:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11817:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11818:       }
11819:     }
11820:   }
11821:   PetscFunctionReturn(PETSC_SUCCESS);
11822: }

11824: /*@
11825:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11827:   Collective

11829:   Input Parameter:
11830: . mat - the matrix

11832:   Output Parameter:
11833: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11835:   Level: beginner

11837: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11838: @*/
11839: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11840: {
11841:   PetscFunctionBegin;
11844:   PetscAssertPointer(cong, 2);
11845:   if (!mat->rmap || !mat->cmap) {
11846:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11847:     PetscFunctionReturn(PETSC_SUCCESS);
11848:   }
11849:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11850:     PetscCall(PetscLayoutSetUp(mat->rmap));
11851:     PetscCall(PetscLayoutSetUp(mat->cmap));
11852:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11853:     if (*cong) mat->congruentlayouts = 1;
11854:     else mat->congruentlayouts = 0;
11855:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11856:   PetscFunctionReturn(PETSC_SUCCESS);
11857: }

11859: /*@
11860:   MatSetInf - Set every entry (of a given nonzero pattern) of a matrix to positive infinity.

11862:   Logically Collective

11864:   Input Parameter:
11865: . A - the matrix

11867:   Level: developer

11869:   Notes:
11870:   Only the dense types (`MATSEQDENSE`, `MATMPIDENSE`, and their device variants) currently implement this operation, which is used to flag a block of solutions that a linear solver failed to compute, as `VecFlag()` does for a single solution.

11872:   The state of `A` is increased, so an outer solver that tracks it detects the failure even when the entries were already infinite.

11874: .seealso: `Mat`, `MatZeroEntries()`, `MatSetValues()`, `VecFlag()`
11875: @*/
11876: PetscErrorCode MatSetInf(Mat A)
11877: {
11878:   PetscFunctionBegin;
11881:   MatCheckPreallocated(A, 1);
11882:   PetscUseTypeMethod(A, setinf);
11883:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
11884:   PetscFunctionReturn(PETSC_SUCCESS);
11885: }

11887: /*@
11888:   MatCreateGraph - create a scalar matrix (that is a matrix with one vertex for each block vertex in the original matrix), for use in graph algorithms
11889:   and possibly removes small values from the graph structure.

11891:   Collective

11893:   Input Parameters:
11894: + A       - the matrix
11895: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11896: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11897: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with $|entries| \le filter$
11898: . num_idx - size of `index` array
11899: - index   - array of block indices to use for graph strength of connection weight

11901:   Output Parameter:
11902: . graph - the resulting graph

11904:   Level: advanced

11906: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11907: @*/
11908: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11909: {
11910:   PetscFunctionBegin;
11914:   PetscAssertPointer(graph, 7);
11915:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11916:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11917:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11918:   PetscFunctionReturn(PETSC_SUCCESS);
11919: }

11921: /*@
11922:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11923:   meaning the same memory is used for the matrix, and no new memory is allocated.

11925:   Collective

11927:   Input Parameters:
11928: + A    - the matrix
11929: - keep - if for a given row of `A`, the diagonal coefficient is zero, indicates whether it should be left in the structure or eliminated as well

11931:   Level: intermediate

11933:   Developer Note:
11934:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11935:   of the arrays in the data structure may be no longer needed to represent the matrix.

11937: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11938: @*/
11939: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11940: {
11941:   PetscFunctionBegin;
11943:   PetscUseTypeMethod(A, eliminatezeros, keep);
11944:   PetscFunctionReturn(PETSC_SUCCESS);
11945: }

11947: /*@
11948:   MatGetCurrentMemType - Get the memory location of the matrix

11950:   Not Collective, but the result will be the same on all MPI processes

11952:   Input Parameter:
11953: . A - the matrix whose memory type we are checking

11955:   Output Parameter:
11956: . m - the memory type, see `PetscMemType`

11958:   Level: intermediate

11960: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11961: @*/
11962: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11963: {
11964:   PetscFunctionBegin;
11966:   PetscAssertPointer(m, 2);
11967:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11968:   else *m = PETSC_MEMTYPE_HOST;
11969:   PetscFunctionReturn(PETSC_SUCCESS);
11970: }