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. `vals` must be `NULL` for a matrix with
586:   the `MAT_STRUCTURE_ONLY` option set to true, since no numerical values are stored.

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

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

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

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

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

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

615:   PetscFunctionBegin;
618:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
619:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
620:   PetscCheck(!mat->structure_only || vals == NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for matrix with MAT_STRUCTURE_ONLY");
621:   MatCheckPreallocated(mat, 1);
622:   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);
623:   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
624:   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
625:   if (ncols) *ncols = incols;
626:   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
627:   PetscFunctionReturn(PETSC_SUCCESS);
628: }

630: /*@
631:   MatConjugate - replaces the matrix values with their complex conjugates

633:   Logically Collective

635:   Input Parameter:
636: . mat - the matrix

638:   Level: advanced

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

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

657:   Not Collective

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

666:   Level: advanced

668:   Notes:
669:   This routine should be called after you have finished examining the entries.

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

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

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

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

700:   Not Collective

702:   Input Parameter:
703: . mat - the matrix

705:   Level: advanced

707:   Note:
708:   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.

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

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

727:   Not Collective

729:   Input Parameter:
730: . mat - the matrix

732:   Level: advanced

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

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

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

755:   Logically Collective

757:   Input Parameters:
758: + A      - the matrix
759: - prefix - the prefix to prepend to all option names

761:   Level: advanced

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

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

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

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

786:   Logically Collective

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

792:   Level: developer

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

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

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

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

822:   Logically Collective

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

828:   Level: developer

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

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

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

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

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

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

866:   Logically Collective

868:   Input Parameters:
869: + A      - the matrix
870: - prefix - the prefix to prepend to all option names

872:   Level: advanced

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

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

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

893:   Not Collective

895:   Input Parameter:
896: . A - the matrix

898:   Output Parameter:
899: . prefix - pointer to the prefix string used

901:   Level: advanced

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

914: /*@
915:   MatGetState - Gets a snapshot of the state of a `Mat`

917:   Not Collective, No Fortran Support

919:   Input Parameter:
920: . A - the matrix

922:   Output Parameter:
923: . state - the matrix state

925:   Level: developer

927:   Notes:
928:   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.

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

943: /*@
944:   MatStateCompare - Compares two matrix state snapshots

946:   Not Collective, No Fortran Support

948:   Input Parameters:
949: + state1 - the first matrix state
950: - state2 - the second matrix state

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

955:   Level: developer

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

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

970:   Not Collective, No Fortran Support

972:   Input Parameter:
973: . A - the matrix

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

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

981:   Level: developer

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

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

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

1002:   Collective

1004:   Input Parameter:
1005: . A - the matrix

1007:   Level: beginner

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

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

1016:   Currently only supported for  `MATAIJ` matrices.

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

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

1032:   Collective

1034:   Input Parameter:
1035: . A - the matrix

1037:   Level: intermediate

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

1042:   Currently only supported for `MATAIJ` matrices.

1044: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
1045: @*/
1046: PetscErrorCode MatResetHash(Mat A)
1047: {
1048:   PetscFunctionBegin;
1051:   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()");
1052:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
1053:   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
1054:   /* These flags are used to determine whether certain setups occur */
1055:   A->was_assembled = PETSC_FALSE;
1056:   A->assembled     = PETSC_FALSE;
1057:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
1058:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1059:   PetscFunctionReturn(PETSC_SUCCESS);
1060: }

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

1065:   Collective

1067:   Input Parameter:
1068: . A - the matrix

1070:   Level: advanced

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

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

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

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

1097: #if PetscDefined(HAVE_SAWS)
1098: #include <petscviewersaws.h>
1099: #endif

1101: /*
1102:    If threadsafety is on extraneous matrices may be printed

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

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

1113:   Collective

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

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

1123:   Level: intermediate

1125:   Note:
1126:   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,
1127:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

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

1142: /*@
1143:   MatView - display information about a matrix in a variety ways

1145:   Collective on viewer

1147:   Input Parameters:
1148: + mat    - the matrix
1149: - viewer - visualization context

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

1155:   Level: beginner

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

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

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

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

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

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

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

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

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

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

1213:   PetscFunctionBegin;
1216:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

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

1223: #if !PetscDefined(HAVE_THREADSAFETY)
1224:   insidematview++;
1225: #endif
1226:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1227:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1228:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1229:   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");

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

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

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

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

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

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

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

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

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

1355:   Collective

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

1362:   Options Database Key:
1363: . -matload_block_size bs - set block size

1365:   Level: beginner

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

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

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

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

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

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

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

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

1417: .vb
1418:     PetscInt    MAT_FILE_CLASSID
1419:     PetscInt    number of rows
1420:     PetscInt    number of columns
1421:     PetscInt    total number of nonzeros
1422:     PetscInt    *number nonzeros in each row
1423:     PetscInt    *column indices of all nonzeros (starting index is zero)
1424:     PetscScalar *values of all nonzeros
1425: .ve
1426:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1427:   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
1428:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

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

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

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

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

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

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

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

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

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

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

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

1474:   PetscFunctionBegin;

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

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

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

1496: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1497: {
1498:   Mat_Redundant *redund = *redundant;

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

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

1523: /*@
1524:   MatDestroy - Frees space taken by a matrix.

1526:   Collective

1528:   Input Parameter:
1529: . A - the matrix

1531:   Level: beginner

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

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

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

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

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

1581:   Not Collective

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

1593:   Level: beginner

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

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

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

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

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

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

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

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

1636:   if (PetscDefined(USE_DEBUG)) {
1637:     PetscInt i, j;

1639:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1640:     if (v) {
1641:       for (i = 0; i < m; i++) {
1642:         for (j = 0; j < n; j++) {
1643:           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1644: #if PetscDefined(USE_COMPLEX)
1645:             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]);
1646: #else
1647:             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]);
1648: #endif
1649:         }
1650:       }
1651:     }
1652:     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);
1653:     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);
1654:   }

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

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

1672:   Not Collective

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

1682:   Level: beginner

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

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

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

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

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

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

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

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

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

1729: /*@
1730:   MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix

1732:   Not Collective

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

1739:   Level: intermediate

1741:   Notes:
1742:   Currently only supported for `MATAIJ`.

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

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

1748:   `row` must belong to this MPI process

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

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

1766: /*@
1767:   MatSetValuesRow - Inserts a row of nonzero values into a matrix

1769:   Not Collective

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

1776:   Level: advanced

1778:   Notes:
1779:   Currently only supported for `MATAIJ`.

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

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

1785:   `row` must belong to this process

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

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

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

1816:   Not Collective

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

1828:   Level: beginner

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

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

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

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

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

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

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

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

1858:   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
1859:   a single value per point) you can skip filling those indices.

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

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

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

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

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

1886:   PetscFunctionBegin;
1887:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1890:   PetscAssertPointer(idxm, 3);
1891:   PetscAssertPointer(idxn, 5);

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

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

1930:   Not Collective

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

1942:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

1995:   PetscFunctionBegin;
1996:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1999:   PetscAssertPointer(idxm, 3);
2000:   PetscAssertPointer(idxn, 5);
2001:   PetscAssertPointer(v, 6);

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

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

2040:   Not Collective

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

2049:   Level: beginner

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

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

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

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

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

2082:   Not Collective

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

2094:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2214: /*@
2215:   MatGetValues - Gets a block of local values from a matrix.

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

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

2227:   Level: advanced

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

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

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

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

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

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

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

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

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

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

2277:   Not Collective

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

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

2290:   Level: advanced

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

2295:   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,
2296:   are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2297:   determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2298:   with `MatSetLocalToGlobalMapping()`.

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

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

2344:   Not Collective

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

2353:   Level: advanced

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

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

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

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

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

2383:   Not Collective

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

2390:   Level: intermediate

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

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

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

2415:   Not Collective

2417:   Input Parameter:
2418: . A - the matrix

2420:   Output Parameters:
2421: + rmapping - row mapping
2422: - cmapping - column mapping

2424:   Level: advanced

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

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

2447:   Logically Collective

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

2454:   Level: advanced

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

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

2470: /*@
2471:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2473:   Not Collective

2475:   Input Parameter:
2476: . A - the matrix

2478:   Output Parameters:
2479: + rmap - row layout
2480: - cmap - column layout

2482:   Level: advanced

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

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

2506:   Not Collective

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

2518:   Level: intermediate

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

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

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

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

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

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

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

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

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

2595:   Not Collective

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

2607:   Level: intermediate

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

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

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

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

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

2629: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2630:           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2631: @*/
2632: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2633: {
2634:   PetscFunctionBeginHot;
2637:   MatCheckPreallocated(mat, 1);
2638:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2639:   PetscAssertPointer(irow, 3);
2640:   PetscAssertPointer(icol, 5);
2641:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2642:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2643:   if (PetscDefined(USE_DEBUG)) {
2644:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2645:     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);
2646:   }

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

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

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

2696:   Collective

2698:   Input Parameters:
2699: + mat - the matrix
2700: - x   - the vector to be multiplied

2702:   Output Parameter:
2703: . y - the result

2705:   Level: developer

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

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

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

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

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

2734:   Neighbor-wise Collective

2736:   Input Parameters:
2737: + mat - the matrix
2738: - x   - the vector to be multiplied

2740:   Output Parameter:
2741: . y - the result

2743:   Level: beginner

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

2749: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2750: @*/
2751: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2752: {
2753:   PetscFunctionBegin;
2757:   VecCheckAssembled(x);
2759:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2760:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2761:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2762:   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);
2763:   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);
2764:   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);
2765:   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);
2766:   PetscCall(VecSetErrorIfLocked(y, 3));
2767:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2768:   MatCheckPreallocated(mat, 1);

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

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

2782:   Neighbor-wise Collective

2784:   Input Parameters:
2785: + mat - the matrix
2786: - x   - the vector to be multiplied

2788:   Output Parameter:
2789: . y - the result

2791:   Level: beginner

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

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

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

2806:   PetscFunctionBegin;
2810:   VecCheckAssembled(x);

2813:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2814:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2815:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2816:   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);
2817:   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);
2818:   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);
2819:   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);
2820:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2821:   MatCheckPreallocated(mat, 1);

2823:   if (!mat->ops->multtranspose) {
2824:     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2825:     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);
2826:   } else op = mat->ops->multtranspose;
2827:   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2828:   PetscCall(VecLockReadPush(x));
2829:   PetscCall((*op)(mat, x, y));
2830:   PetscCall(VecLockReadPop(x));
2831:   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2832:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2833:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2834:   PetscFunctionReturn(PETSC_SUCCESS);
2835: }

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

2840:   Neighbor-wise Collective

2842:   Input Parameters:
2843: + mat - the matrix
2844: - x   - the vector to be multiplied

2846:   Output Parameter:
2847: . y - the result

2849:   Level: beginner

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

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

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

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

2869:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2870:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2871:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2872:   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);
2873:   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);
2874:   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);
2875:   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);
2876:   MatCheckPreallocated(mat, 1);

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

2900: /*@
2901:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2903:   Neighbor-wise Collective

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

2910:   Output Parameter:
2911: . v3 - the result

2913:   Level: beginner

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

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

2930:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2931:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2932:   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);
2933:   /* 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);
2934:      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); */
2935:   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);
2936:   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);
2937:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2938:   MatCheckPreallocated(mat, 1);

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

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

2952:   Neighbor-wise Collective

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

2959:   Output Parameter:
2960: . v3 - the result

2962:   Level: beginner

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

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

2974:   PetscFunctionBegin;

2981:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2982:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2983:   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);
2984:   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);
2985:   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);
2986:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2987:   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2988:   MatCheckPreallocated(mat, 1);

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

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

3002:   Neighbor-wise Collective

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

3009:   Output Parameter:
3010: . v3 - the result

3012:   Level: beginner

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

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

3029:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3030:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3031:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
3032:   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);
3033:   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);
3034:   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);
3035:   MatCheckPreallocated(mat, 1);

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

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

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

3072:   PetscFunctionBegin;
3073:   PetscCall(MatADot(mat, x, x, &sval));
3074:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3075:   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");
3076:   *val = PetscSqrtReal(PetscRealPart(sval));
3077:   PetscFunctionReturn(PETSC_SUCCESS);
3078: }

3080: /*@
3081:   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)
3082:   positive definite.

3084:   Collective

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

3091:   Output Parameter:
3092: . val - the dot product with respect to `A`

3094:   Level: intermediate

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

3104: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3105: @*/
3106: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3107: {
3108:   PetscFunctionBegin;
3112:   VecCheckAssembled(x);
3114:   VecCheckAssembled(y);
3117:   PetscAssertPointer(val, 4);
3118:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3119:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3120:   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);
3121:   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);
3122:   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);
3123:   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);
3124:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3125:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3126:   MatCheckPreallocated(mat, 1);

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

3139: /*@
3140:   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)
3141:   positive definite.

3143:   Collective

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

3149:   Output Parameter:
3150: . val - the norm with respect to `A`

3152:   Level: intermediate

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

3161: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3162: @*/
3163: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3164: {
3165:   PetscFunctionBegin;
3169:   VecCheckAssembled(x);
3171:   PetscAssertPointer(val, 3);
3172:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3173:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3174:   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);
3175:   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);
3176:   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);
3177:   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);
3178:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3179:   MatCheckPreallocated(mat, 1);

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

3190: /*@
3191:   MatGetFactorType - gets the type of factorization a matrix is

3193:   Not Collective

3195:   Input Parameter:
3196: . mat - the matrix

3198:   Output Parameter:
3199: . 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`

3201:   Level: intermediate

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

3216: /*@
3217:   MatSetFactorType - sets the type of factorization a matrix is

3219:   Logically Collective

3221:   Input Parameters:
3222: + mat - the matrix
3223: - 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`

3225:   Level: intermediate

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

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

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

3245:   Input Parameters:
3246: + mat  - the matrix
3247: - 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)

3249:   Output Parameter:
3250: . info - matrix information context

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

3255:   Level: intermediate

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

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

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

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

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

3301: /*@
3302:   MatLUFactor - Performs in-place LU factorization of matrix.

3304:   Collective

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

3317:   Level: developer

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

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

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

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

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

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

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

3361: /*@
3362:   MatILUFactor - Performs in-place ILU factorization of matrix.

3364:   Collective

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

3378:   Level: developer

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

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

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

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

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

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

3418:   Collective

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

3431:   Level: developer

3433:   Notes:
3434:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

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

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

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

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

3476:   Collective

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

3483:   Level: developer

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

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

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

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

3502:   PetscFunctionBegin;
3507:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3508:   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,
3509:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

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

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

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

3531:   Collective

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

3538:   Level: developer

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

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

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

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

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

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

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

3583:   Collective

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

3596:   Level: developer

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

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

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

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

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

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

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

3644:   Collective

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

3651:   Level: developer

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

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

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

3667:   PetscFunctionBegin;
3672:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3673:   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,
3674:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3675:   MatCheckPreallocated(mat, 2);
3676:   if (!info) {
3677:     PetscCall(MatFactorInfoInitialize(&tinfo));
3678:     info = &tinfo;
3679:   }

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

3691: /*@
3692:   MatQRFactor - Performs in-place QR factorization of matrix.

3694:   Collective

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

3706:   Level: developer

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

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

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

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

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

3743:   Collective

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

3756:   Level: developer

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

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

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

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

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

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

3798:   Collective

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

3805:   Level: developer

3807:   Notes:
3808:   See `MatQRFactor()` for in-place factorization.

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

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

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

3823:   PetscFunctionBegin;
3828:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3829:   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,
3830:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

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

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

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

3851:   Neighbor-wise Collective

3853:   Input Parameters:
3854: + mat - the factored matrix
3855: - b   - the right-hand-side vector

3857:   Output Parameter:
3858: . x - the result vector

3860:   Level: developer

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

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

3870: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3871: @*/
3872: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3873: {
3874:   PetscFunctionBegin;
3879:   PetscCheckSameComm(mat, 1, b, 2);
3880:   PetscCheckSameComm(mat, 1, x, 3);
3881:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3882:   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);
3883:   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);
3884:   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);
3885:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3886:   MatCheckPreallocated(mat, 1);

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

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

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

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

3935:   Neighbor-wise Collective

3937:   Input Parameters:
3938: + A - the factored matrix
3939: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3941:   Output Parameter:
3942: . X - the result matrix (dense matrix)

3944:   Level: developer

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

3950: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3951: @*/
3952: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3953: {
3954:   PetscFunctionBegin;
3959:   PetscCheckSameComm(A, 1, B, 2);
3960:   PetscCheckSameComm(A, 1, X, 3);
3961:   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);
3962:   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);
3963:   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");
3964:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3965:   MatCheckPreallocated(A, 1);

3967:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3968:   if (A->factorerrortype) {
3969:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3970:     PetscCall(MatFlag(X, 1));
3971:   } else 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->factorerrortype) {
4019:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4020:     PetscCall(MatFlag(X, 1));
4021:   } else if (!A->ops->matsolvetranspose) {
4022:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
4023:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
4024:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
4025:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
4026:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4027:   PetscFunctionReturn(PETSC_SUCCESS);
4028: }

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

4033:   Neighbor-wise Collective

4035:   Input Parameters:
4036: + A  - the factored matrix
4037: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

4039:   Output Parameter:
4040: . X - the result matrix (dense matrix)

4042:   Level: developer

4044:   Note:
4045:   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
4046:   format on the host process and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.

4048: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
4049: @*/
4050: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
4051: {
4052:   PetscFunctionBegin;
4057:   PetscCheckSameComm(A, 1, Bt, 2);
4058:   PetscCheckSameComm(A, 1, X, 3);

4060:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4061:   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);
4062:   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);
4063:   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");
4064:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4065:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
4066:   MatCheckPreallocated(A, 1);

4068:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
4069:   if (A->factorerrortype) {
4070:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4071:     PetscCall(MatFlag(X, 1));
4072:   } else PetscUseTypeMethod(A, mattransposesolve, Bt, X);
4073:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
4074:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4075:   PetscFunctionReturn(PETSC_SUCCESS);
4076: }

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

4082:   Neighbor-wise Collective

4084:   Input Parameters:
4085: + mat - the factored matrix
4086: - b   - the right-hand-side vector

4088:   Output Parameter:
4089: . x - the result vector

4091:   Level: developer

4093:   Notes:
4094:   `MatSolve()` should be used for most applications, as it performs
4095:   a forward solve followed by a backward solve.

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

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

4106: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4107: @*/
4108: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4109: {
4110:   PetscFunctionBegin;
4115:   PetscCheckSameComm(mat, 1, b, 2);
4116:   PetscCheckSameComm(mat, 1, x, 3);
4117:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4118:   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);
4119:   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);
4120:   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);
4121:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4122:   MatCheckPreallocated(mat, 1);

4124:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4125:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4126:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4127:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4128:   PetscFunctionReturn(PETSC_SUCCESS);
4129: }

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

4135:   Neighbor-wise Collective

4137:   Input Parameters:
4138: + mat - the factored matrix
4139: - b   - the right-hand-side vector

4141:   Output Parameter:
4142: . x - the result vector

4144:   Level: developer

4146:   Notes:
4147:   `MatSolve()` should be used for most applications, as it performs
4148:   a forward solve followed by a backward solve.

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

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

4159: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4160: @*/
4161: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4162: {
4163:   PetscFunctionBegin;
4168:   PetscCheckSameComm(mat, 1, b, 2);
4169:   PetscCheckSameComm(mat, 1, x, 3);
4170:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4171:   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);
4172:   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);
4173:   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);
4174:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4175:   MatCheckPreallocated(mat, 1);

4177:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4178:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4179:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4180:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4181:   PetscFunctionReturn(PETSC_SUCCESS);
4182: }

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

4187:   Neighbor-wise Collective

4189:   Input Parameters:
4190: + mat - the factored matrix
4191: . b   - the right-hand-side vector
4192: - y   - the vector to be added to

4194:   Output Parameter:
4195: . x - the result vector

4197:   Level: developer

4199:   Note:
4200:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4201:   call `MatSolveAdd`(A,x,y,x).

4203: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4204: @*/
4205: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4206: {
4207:   PetscScalar one = 1.0;
4208:   Vec         tmp;

4210:   PetscFunctionBegin;
4216:   PetscCheckSameComm(mat, 1, b, 2);
4217:   PetscCheckSameComm(mat, 1, y, 3);
4218:   PetscCheckSameComm(mat, 1, x, 4);
4219:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4220:   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);
4221:   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);
4222:   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);
4223:   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);
4224:   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);
4225:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4226:   MatCheckPreallocated(mat, 1);

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

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

4255:   Neighbor-wise Collective

4257:   Input Parameters:
4258: + mat - the factored matrix
4259: - b   - the right-hand-side vector

4261:   Output Parameter:
4262: . x - the result vector

4264:   Level: developer

4266:   Notes:
4267:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4268:   call `MatSolveTranspose`(A,x,x).

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

4274: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4275: @*/
4276: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4277: {
4278:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

4280:   PetscFunctionBegin;
4285:   PetscCheckSameComm(mat, 1, b, 2);
4286:   PetscCheckSameComm(mat, 1, x, 3);
4287:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4288:   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);
4289:   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);
4290:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4291:   MatCheckPreallocated(mat, 1);
4292:   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4293:   PetscCall(VecFlag(x, mat->factorerrortype));
4294:   if (mat->factorerrortype) {
4295:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4296:   } else {
4297:     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4298:     PetscCall((*f)(mat, b, x));
4299:   }
4300:   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4301:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4302:   PetscFunctionReturn(PETSC_SUCCESS);
4303: }

4305: /*@
4306:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4307:   factored matrix.

4309:   Neighbor-wise Collective

4311:   Input Parameters:
4312: + mat - the factored matrix
4313: . b   - the right-hand-side vector
4314: - y   - the vector to be added to

4316:   Output Parameter:
4317: . x - the result vector

4319:   Level: developer

4321:   Note:
4322:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4323:   call `MatSolveTransposeAdd`(A,x,y,x).

4325: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4326: @*/
4327: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4328: {
4329:   PetscScalar one = 1.0;
4330:   Vec         tmp;
4331:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

4333:   PetscFunctionBegin;
4339:   PetscCheckSameComm(mat, 1, b, 2);
4340:   PetscCheckSameComm(mat, 1, y, 3);
4341:   PetscCheckSameComm(mat, 1, x, 4);
4342:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4343:   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);
4344:   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);
4345:   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);
4346:   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);
4347:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4348:   MatCheckPreallocated(mat, 1);

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

4374: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4375: /*@
4376:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4378:   Neighbor-wise Collective

4380:   Input Parameters:
4381: + mat   - the matrix
4382: . b     - the right-hand side
4383: . omega - the relaxation factor
4384: . flag  - flag indicating the type of SOR (see below)
4385: . shift - diagonal shift
4386: . its   - the number of iterations
4387: - lits  - the number of local iterations

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

4392:   SOR Flags:
4393: +     `SOR_FORWARD_SWEEP` - forward SOR
4394: .     `SOR_BACKWARD_SWEEP` - backward SOR
4395: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4396: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4397: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4398: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4399: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4400: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4401: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4403:   Level: developer

4405:   Notes:
4406:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4407:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4408:   on each process.

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

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

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

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

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

4425: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4426: @*/
4427: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4428: {
4429:   PetscFunctionBegin;
4434:   PetscCheckSameComm(mat, 1, b, 2);
4435:   PetscCheckSameComm(mat, 1, x, 8);
4436:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4437:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4438:   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);
4439:   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);
4440:   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);
4441:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4442:   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4443:   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");

4445:   MatCheckPreallocated(mat, 1);
4446:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4447:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4448:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4449:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4450:   PetscFunctionReturn(PETSC_SUCCESS);
4451: }

4453: /*
4454:       Default matrix copy routine.
4455: */
4456: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4457: {
4458:   PetscInt           i, rstart = 0, rend = 0, nz;
4459:   const PetscInt    *cwork;
4460:   const PetscScalar *vwork;

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

4479: /*@
4480:   MatCopy - Copies a matrix to another matrix.

4482:   Collective

4484:   Input Parameters:
4485: + A   - the matrix
4486: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4488:   Output Parameter:
4489: . B - where the copy is put

4491:   Level: intermediate

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

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

4500: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4501: @*/
4502: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4503: {
4504:   PetscInt i;

4506:   PetscFunctionBegin;
4511:   PetscCheckSameComm(A, 1, B, 2);
4512:   MatCheckPreallocated(B, 2);
4513:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4514:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4515:   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,
4516:              A->cmap->N, B->cmap->N);
4517:   MatCheckPreallocated(A, 1);
4518:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4520:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4521:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4522:   else PetscCall(MatCopy_Basic(A, B, str));

4524:   B->stencil.dim = A->stencil.dim;
4525:   B->stencil.noc = A->stencil.noc;
4526:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4527:     B->stencil.dims[i]   = A->stencil.dims[i];
4528:     B->stencil.starts[i] = A->stencil.starts[i];
4529:   }

4531:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4532:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4533:   PetscFunctionReturn(PETSC_SUCCESS);
4534: }

4536: /*@
4537:   MatConvert - Converts a matrix to another matrix, either of the same
4538:   or different type.

4540:   Collective

4542:   Input Parameters:
4543: + mat     - the matrix
4544: . newtype - new matrix type. Use `MATSAME` to create a new matrix of the
4545:             same type as the original matrix.
4546: - reuse   - denotes if the destination matrix is to be created or reused.
4547:             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
4548:             `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).

4550:   Output Parameter:
4551: . M - pointer to place new matrix

4553:   Level: intermediate

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

4560:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4561:   the MPI communicator of the generated matrix is always the same as the communicator
4562:   of the input matrix.

4564: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4565: @*/
4566: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4567: {
4568:   PetscBool  sametype, issame, flg;
4569:   PetscBool3 issymmetric, ishermitian, isspd;
4570:   char       convname[256], mtype[256];
4571:   Mat        B;

4573:   PetscFunctionBegin;
4576:   PetscAssertPointer(M, 4);
4577:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4578:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4579:   MatCheckPreallocated(mat, 1);

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

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

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

4597:   /* Cache Mat options because some converters use MatHeaderReplace() */
4598:   issymmetric = mat->symmetric;
4599:   ishermitian = mat->hermitian;
4600:   isspd       = mat->spd;

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

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

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

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

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

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

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

4711:   /* Reset Mat options */
4712:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4713:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4714:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4715:   PetscFunctionReturn(PETSC_SUCCESS);
4716: }

4718: /*@
4719:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4721:   Not Collective

4723:   Input Parameter:
4724: . mat - the matrix, must be a factored matrix

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

4729:   Level: intermediate

4731: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4732: @*/
4733: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4734: {
4735:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4737:   PetscFunctionBegin;
4740:   PetscAssertPointer(type, 2);
4741:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4742:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4743:   if (conv) PetscCall((*conv)(mat, type));
4744:   else *type = MATSOLVERPETSC;
4745:   PetscFunctionReturn(PETSC_SUCCESS);
4746: }

4748: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4749: struct _MatSolverTypeForSpecifcType {
4750:   MatType mtype;
4751:   /* no entry for MAT_FACTOR_NONE */
4752:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4753:   MatSolverTypeForSpecifcType next;
4754: };

4756: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4757: struct _MatSolverTypeHolder {
4758:   char                       *name;
4759:   MatSolverTypeForSpecifcType handlers;
4760:   MatSolverTypeHolder         next;
4761: };

4763: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4768:   Logically Collective, No Fortran Support

4770:   Input Parameters:
4771: + package      - name of the package, for example `petsc` or `superlu`
4772: . mtype        - the matrix type that works with this package
4773: . ftype        - the type of factorization supported by the package
4774: - createfactor - routine that will create the factored matrix ready to be used

4776:   Level: developer

4778: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4779:   `MatGetFactor()`
4780: @*/
4781: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4782: {
4783:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4784:   PetscBool                   flg;
4785:   MatSolverTypeForSpecifcType inext, iprev = NULL;

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

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

4830:   Input Parameters:
4831: + 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
4832: . ftype - the type of factorization supported by the type
4833: - mtype - the matrix type that works with this type

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

4840:   Calling sequence of `createfactor`:
4841: + A     - the matrix providing the factor matrix
4842: . ftype - the `MatFactorType` of the factor requested
4843: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4845:   Level: developer

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

4852: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4853:           `MatInitializePackage()`
4854: @*/
4855: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4856: {
4857:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4858:   PetscBool                   flg;
4859:   MatSolverTypeForSpecifcType inext;

4861:   PetscFunctionBegin;
4862:   if (foundtype) *foundtype = PETSC_FALSE;
4863:   if (foundmtype) *foundmtype = PETSC_FALSE;
4864:   if (createfactor) *createfactor = NULL;

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

4919: PetscErrorCode MatSolverTypeDestroy(void)
4920: {
4921:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4922:   MatSolverTypeForSpecifcType inext, iprev;

4924:   PetscFunctionBegin;
4925:   while (next) {
4926:     PetscCall(PetscFree(next->name));
4927:     inext = next->handlers;
4928:     while (inext) {
4929:       PetscCall(PetscFree(inext->mtype));
4930:       iprev = inext;
4931:       inext = inext->next;
4932:       PetscCall(PetscFree(iprev));
4933:     }
4934:     prev = next;
4935:     next = next->next;
4936:     PetscCall(PetscFree(prev));
4937:   }
4938:   MatSolverTypeHolders = NULL;
4939:   PetscFunctionReturn(PETSC_SUCCESS);
4940: }

4942: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4943: {
4944:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4945:   MatSolverTypeForSpecifcType inext;
4946:   PetscBool                   flg, same;

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

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

4980:   Logically Collective

4982:   Input Parameter:
4983: . mat - the matrix

4985:   Output Parameter:
4986: . flg - `PETSC_TRUE` if uses the ordering

4988:   Level: developer

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

4994: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4995: @*/
4996: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4997: {
4998:   PetscFunctionBegin;
4999:   *flg = mat->canuseordering;
5000:   PetscFunctionReturn(PETSC_SUCCESS);
5001: }

5003: /*@
5004:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

5006:   Logically Collective

5008:   Input Parameters:
5009: + mat   - the matrix obtained with `MatGetFactor()`
5010: - ftype - the factorization type to be used

5012:   Output Parameter:
5013: . otype - the preferred ordering type

5015:   Level: developer

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

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

5031:   Collective

5033:   Input Parameters:
5034: + mat   - the matrix
5035: . 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
5036:           the other criteria is returned
5037: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

5047:   Level: intermediate

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

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

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

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

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

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

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

5083:   PetscFunctionBegin;

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

5090:   PetscCall(MatIsShell(mat, &shell));
5091:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
5092:   if (hasop) {
5093:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
5094:     PetscFunctionReturn(PETSC_SUCCESS);
5095:   }

5097:   if (!type) {
5098:     PetscBool foundbase;

5100:     /* First try exact MatType registrations in solver registration order. If all matching backends
5101:        decline this matrix instance by returning NULL, then try base-type registrations. */
5102:     PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
5103:     if (!*f) {
5104:       PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
5105:       foundtype = (PetscBool)(foundtype || foundbase);
5106:     }
5107:     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);
5108:     if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5109:     PetscFunctionReturn(PETSC_SUCCESS);
5110:   }

5112:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
5113:   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],
5114:              ((PetscObject)mat)->type_name, type ? " Perhaps you must ./configure with --download-" : "", type ? type : "");
5115:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
5116:   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);

5118:   PetscCall((*conv)(mat, ftype, f));
5119:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5120:   PetscFunctionReturn(PETSC_SUCCESS);
5121: }

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

5126:   Not Collective

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

5133:   Output Parameter:
5134: . flg - `PETSC_TRUE` if the factorization is available

5136:   Level: intermediate

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

5142:   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

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

5147: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5148:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5149: @*/
5150: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5151: {
5152:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5154:   PetscFunctionBegin;
5156:   PetscAssertPointer(flg, 4);

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

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

5164:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5165:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5166:   PetscFunctionReturn(PETSC_SUCCESS);
5167: }

5169: /*@
5170:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5172:   Collective

5174:   Input Parameters:
5175: + mat - the matrix
5176: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5177:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5179:   Output Parameter:
5180: . M - pointer to place new matrix

5182:   Level: intermediate

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

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

5189:   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.

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

5195: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5196: @*/
5197: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5198: {
5199:   Mat               B;
5200:   VecType           vtype;
5201:   PetscInt          i;
5202:   PetscObject       dm, container_h, container_d;
5203:   PetscErrorCodeFn *viewf;

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

5213:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5214:   PetscUseTypeMethod(mat, duplicate, op, M);
5215:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5216:   B = *M;

5218:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5219:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5220:   PetscCall(MatGetVecType(mat, &vtype));
5221:   PetscCall(MatSetVecType(B, vtype));

5223:   B->stencil.dim = mat->stencil.dim;
5224:   B->stencil.noc = mat->stencil.noc;
5225:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5226:     B->stencil.dims[i]   = mat->stencil.dims[i];
5227:     B->stencil.starts[i] = mat->stencil.starts[i];
5228:   }

5230:   B->nooffproczerorows = mat->nooffproczerorows;
5231:   B->nooffprocentries  = mat->nooffprocentries;

5233:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5234:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5235:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5236:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5237:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5238:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5239:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5240:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5241:   PetscFunctionReturn(PETSC_SUCCESS);
5242: }

5244: /*@
5245:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5247:   Logically Collective

5249:   Input Parameter:
5250: . mat - the matrix

5252:   Output Parameter:
5253: . v - the diagonal of the matrix

5255:   Level: intermediate

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

5262:   Currently only correct in parallel for square matrices.

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

5277:     PetscCall(VecGetLocalSize(v, &nv));
5278:     PetscCall(MatGetLocalSize(mat, &row, &col));
5279:     ndiag = PetscMin(row, col);
5280:     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);
5281:   }

5283:   PetscUseTypeMethod(mat, getdiagonal, v);
5284:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5285:   PetscFunctionReturn(PETSC_SUCCESS);
5286: }

5288: /*@
5289:   MatGetRowMin - Gets the minimum value (of the real part) of each
5290:   row of the matrix

5292:   Logically Collective

5294:   Input Parameter:
5295: . mat - the matrix

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

5301:   Level: intermediate

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

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

5309: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5310:           `MatGetRowMax()`
5311: @*/
5312: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5313: {
5314:   PetscFunctionBegin;
5318:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5320:   if (!mat->cmap->N) {
5321:     PetscCall(VecSet(v, PETSC_MAX_REAL));
5322:     if (idx) {
5323:       PetscInt i, m = mat->rmap->n;
5324:       for (i = 0; i < m; i++) idx[i] = -1;
5325:     }
5326:   } else {
5327:     MatCheckPreallocated(mat, 1);
5328:   }
5329:   PetscUseTypeMethod(mat, getrowmin, v, idx);
5330:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5331:   PetscFunctionReturn(PETSC_SUCCESS);
5332: }

5334: /*@
5335:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5336:   row of the matrix

5338:   Logically Collective

5340:   Input Parameter:
5341: . mat - the matrix

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

5347:   Level: intermediate

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

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

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

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

5381: /*@
5382:   MatGetRowMax - Gets the maximum value (of the real part) of each
5383:   row of the matrix

5385:   Logically Collective

5387:   Input Parameter:
5388: . mat - the matrix

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

5394:   Level: intermediate

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

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

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

5412:   if (!mat->cmap->N) {
5413:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5414:     if (idx) {
5415:       PetscInt i, m = mat->rmap->n;
5416:       for (i = 0; i < m; i++) idx[i] = -1;
5417:     }
5418:   } else {
5419:     MatCheckPreallocated(mat, 1);
5420:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5421:   }
5422:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5423:   PetscFunctionReturn(PETSC_SUCCESS);
5424: }

5426: /*@
5427:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5428:   row of the matrix

5430:   Logically Collective

5432:   Input Parameter:
5433: . mat - the matrix

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

5439:   Level: intermediate

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

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

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

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

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

5475:   Logically Collective

5477:   Input Parameter:
5478: . mat - the matrix

5480:   Output Parameter:
5481: . v - the vector for storing the sum

5483:   Level: intermediate

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

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

5497:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5498:   else {
5499:     MatCheckPreallocated(mat, 1);
5500:     PetscUseTypeMethod(mat, getrowsumabs, v);
5501:   }
5502:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5503:   PetscFunctionReturn(PETSC_SUCCESS);
5504: }

5506: /*@
5507:   MatGetRowSum - Gets the sum of each row of the matrix

5509:   Logically or Neighborhood Collective

5511:   Input Parameter:
5512: . mat - the matrix

5514:   Output Parameter:
5515: . v - the vector for storing the sum of rows

5517:   Level: intermediate

5519:   Note:
5520:   This code is slow since it is not currently specialized for different formats

5522: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5523: @*/
5524: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5525: {
5526:   Vec ones;

5528:   PetscFunctionBegin;
5532:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5533:   MatCheckPreallocated(mat, 1);
5534:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5535:   PetscCall(VecSet(ones, 1.));
5536:   PetscCall(MatMult(mat, ones, v));
5537:   PetscCall(VecDestroy(&ones));
5538:   PetscFunctionReturn(PETSC_SUCCESS);
5539: }

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

5545:   Collective

5547:   Input Parameter:
5548: . mat - the matrix to provide the transpose

5550:   Output Parameter:
5551: . 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

5553:   Level: advanced

5555:   Note:
5556:   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
5557:   routine allows bypassing that call.

5559: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5560: @*/
5561: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5562: {
5563:   MatState *rb = NULL;

5565:   PetscFunctionBegin;
5566:   PetscCall(PetscNew(&rb));
5567:   rb->id    = ((PetscObject)mat)->id;
5568:   rb->state = 0;
5569:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5570:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5571:   PetscFunctionReturn(PETSC_SUCCESS);
5572: }

5574: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5575: {
5576:   PetscContainer rB                         = NULL;
5577:   MatState      *rb                         = NULL;
5578:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

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

5596:   if (conjugate) {
5597:     f = mat->ops->hermitiantranspose;
5598:     if (f) PetscCall((*f)(mat, reuse, B));
5599:   }
5600:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5601:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5602:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5603:       PetscUseTypeMethod(mat, transpose, reuse, B);
5604:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5605:     }
5606:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5607:     if (conjugate) PetscCall(MatConjugate(*B));
5608:   }

5610:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5611:   if (reuse != MAT_INPLACE_MATRIX) {
5612:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5613:     PetscCall(PetscContainerGetPointer(rB, &rb));
5614:     rb->state        = ((PetscObject)mat)->state;
5615:     rb->nonzerostate = mat->nonzerostate;
5616:   }
5617:   PetscFunctionReturn(PETSC_SUCCESS);
5618: }

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

5623:   Collective

5625:   Input Parameters:
5626: + mat   - the matrix to transpose
5627: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5629:   Output Parameter:
5630: . B - the transpose of the matrix

5632:   Level: intermediate

5634:   Notes:
5635:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

5637:   `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
5638:   transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.

5640:   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.

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

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

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

5649: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5650:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5651: @*/
5652: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5653: {
5654:   PetscFunctionBegin;
5655:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5656:   PetscFunctionReturn(PETSC_SUCCESS);
5657: }

5659: /*@
5660:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5662:   Collective

5664:   Input Parameter:
5665: . A - the matrix to transpose

5667:   Output Parameter:
5668: . 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
5669:       numerical portion.

5671:   Level: intermediate

5673:   Note:
5674:   This is not supported for many matrix types, use `MatTranspose()` in those cases

5676: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5677: @*/
5678: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5679: {
5680:   PetscFunctionBegin;
5683:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5684:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5685:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5686:   PetscUseTypeMethod(A, transposesymbolic, B);
5687:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5689:   PetscCall(MatTransposeSetPrecursor(A, *B));
5690:   PetscFunctionReturn(PETSC_SUCCESS);
5691: }

5693: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5694: {
5695:   PetscContainer rB;
5696:   MatState      *rb;

5698:   PetscFunctionBegin;
5701:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5702:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5703:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5704:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5705:   PetscCall(PetscContainerGetPointer(rB, &rb));
5706:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5707:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5708:   PetscFunctionReturn(PETSC_SUCCESS);
5709: }

5711: /*@
5712:   MatIsTranspose - Test whether a matrix is another one's transpose,
5713:   or its own, in which case it tests symmetry.

5715:   Collective

5717:   Input Parameters:
5718: + A   - the matrix to test
5719: . B   - the matrix to test against, this can equal the first parameter
5720: - tol - tolerance, differences between entries smaller than this are counted as zero

5722:   Output Parameter:
5723: . flg - the result

5725:   Level: intermediate

5727:   Notes:
5728:   The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5729:   test involves parallel copies of the block off-diagonal parts of the matrix.

5731: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5732: @*/
5733: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5734: {
5735:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5737:   PetscFunctionBegin;
5740:   PetscAssertPointer(flg, 4);
5741:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5742:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5743:   *flg = PETSC_FALSE;
5744:   if (f && g) {
5745:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5746:     PetscCall((*f)(A, B, tol, flg));
5747:   } else {
5748:     MatType mattype;

5750:     PetscCall(MatGetType(f ? B : A, &mattype));
5751:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5752:   }
5753:   PetscFunctionReturn(PETSC_SUCCESS);
5754: }

5756: /*@
5757:   MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.

5759:   Collective

5761:   Input Parameters:
5762: + mat   - the matrix to transpose and complex conjugate
5763: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5765:   Output Parameter:
5766: . B - the Hermitian transpose

5768:   Level: intermediate

5770: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5771: @*/
5772: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5773: {
5774:   PetscFunctionBegin;
5775:   PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5776:   PetscFunctionReturn(PETSC_SUCCESS);
5777: }

5779: /*@
5780:   MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,

5782:   Collective

5784:   Input Parameters:
5785: + A   - the matrix to test
5786: . B   - the matrix to test against, this can equal the first parameter
5787: - tol - tolerance, differences between entries smaller than this are counted as zero

5789:   Output Parameter:
5790: . flg - the result

5792:   Level: intermediate

5794:   Notes:
5795:   Only available for `MATAIJ` matrices.

5797:   The sequential algorithm
5798:   has a running time of the order of the number of nonzeros; the parallel
5799:   test involves parallel copies of the block off-diagonal parts of the matrix.

5801: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5802: @*/
5803: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5804: {
5805:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5807:   PetscFunctionBegin;
5810:   PetscAssertPointer(flg, 4);
5811:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5812:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5813:   if (f && g) {
5814:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5815:     PetscCall((*f)(A, B, tol, flg));
5816:   } else {
5817:     MatType mattype;

5819:     PetscCall(MatGetType(f ? B : A, &mattype));
5820:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5821:   }
5822:   PetscFunctionReturn(PETSC_SUCCESS);
5823: }

5825: /*@
5826:   MatPermute - Creates a new matrix with rows and columns permuted from the
5827:   original.

5829:   Collective

5831:   Input Parameters:
5832: + mat - the matrix to permute
5833: . row - row permutation, each process supplies only the permutation for its rows
5834: - col - column permutation, each process supplies only the permutation for its columns

5836:   Output Parameter:
5837: . B - the permuted matrix

5839:   Level: advanced

5841:   Note:
5842:   The index sets map from `row`/`col` of permuted matrix to `row`/`col` of original matrix.
5843:   The index sets should be on the same communicator as mat and have the same local sizes.
5844:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the permutation does not preserve symmetry.

5846:   Developer Note:
5847:   If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5848:   exploit the fact that `row` and `col` are permutations, consider implementing the
5849:   more general `MatCreateSubMatrix()` instead.

5851: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5852: @*/
5853: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5854: {
5855:   PetscFunctionBegin;
5860:   PetscAssertPointer(B, 4);
5861:   PetscCheckSameComm(mat, 1, row, 2);
5862:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5863:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5864:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5865:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5866:   MatCheckPreallocated(mat, 1);

5868:   if (mat->ops->permute) {
5869:     PetscUseTypeMethod(mat, permute, row, col, B);
5870:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5871:   } else {
5872:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5873:   }
5874:   PetscFunctionReturn(PETSC_SUCCESS);
5875: }

5877: /*@
5878:   MatEqual - Compares two matrices.

5880:   Collective

5882:   Input Parameters:
5883: + A - the first matrix
5884: - B - the second matrix

5886:   Output Parameter:
5887: . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.

5889:   Level: intermediate

5891:   Note:
5892:   If either of the matrix is "matrix-free", meaning the matrix entries are not stored explicitly then equality is determined by comparing
5893:   the results of several matrix-vector product using randomly created vectors, see `MatMultEqual()`.

5895: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5896: @*/
5897: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5898: {
5899:   PetscFunctionBegin;
5904:   PetscAssertPointer(flg, 3);
5905:   PetscCheckSameComm(A, 1, B, 2);
5906:   MatCheckPreallocated(A, 1);
5907:   MatCheckPreallocated(B, 2);
5908:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5909:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5910:   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,
5911:              B->cmap->N);
5912:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5913:   else PetscCall(MatMultEqual(A, B, 10, flg));
5914:   PetscFunctionReturn(PETSC_SUCCESS);
5915: }

5917: /*@
5918:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5919:   matrices that are stored as vectors. Either of the two scaling
5920:   matrices can be `NULL`.

5922:   Collective

5924:   Input Parameters:
5925: + mat - the matrix to be scaled
5926: . l   - the left scaling vector (or `NULL`)
5927: - r   - the right scaling vector (or `NULL`)

5929:   Level: intermediate

5931:   Note:
5932:   `MatDiagonalScale()` computes $A = LAR$, where
5933:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5934:   The L scales the rows of the matrix, the R scales the columns of the matrix.
5935:   For `MATSEQSBAIJ`, if `l` and `r` are different `Vec` objects, `mat` changes to type `MATSEQBAIJ` because the result is not necessarily symmetric.

5937: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5938: @*/
5939: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5940: {
5941:   PetscBool flg = PETSC_FALSE;

5943:   PetscFunctionBegin;
5946:   if (l) {
5948:     PetscCheckSameComm(mat, 1, l, 2);
5949:   }
5950:   if (r) {
5952:     PetscCheckSameComm(mat, 1, r, 3);
5953:   }
5954:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5955:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5956:   MatCheckPreallocated(mat, 1);
5957:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5959:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5960:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5961:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5962:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5963:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5964:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5965:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5966:       if (!flg) {
5967:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5968:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For MATMPISBAIJ, left and right scaling vectors must be the same");
5969:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5970:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5971:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5972:       }
5973:     }
5974:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5975:       flg = PETSC_FALSE;
5976:       if (l && r) {
5977:         Vec conjugate;

5979:         PetscCall(VecDuplicate(l, &conjugate));
5980:         PetscCall(VecCopy(l, conjugate));
5981:         PetscCall(VecConjugate(conjugate));
5982:         PetscCall(VecEqual(conjugate, r, &flg));
5983:         PetscCall(VecDestroy(&conjugate));
5984:       }
5985:       if (!flg) {
5986:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5987:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For Hermitian MATMPISBAIJ, left and right scaling vectors must be conjugate one of the other");
5988:         mat->hermitian = PETSC_BOOL3_FALSE;
5989:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5990:       }
5991:     }
5992:   }
5993:   PetscFunctionReturn(PETSC_SUCCESS);
5994: }

5996: /*@
5997:   MatScale - Scales all elements of a matrix by a given number.

5999:   Logically Collective

6001:   Input Parameters:
6002: + mat - the matrix to be scaled
6003: - a   - the scaling value

6005:   Level: intermediate

6007: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
6008: @*/
6009: PetscErrorCode MatScale(Mat mat, PetscScalar a)
6010: {
6011:   PetscFunctionBegin;
6014:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6015:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6017:   MatCheckPreallocated(mat, 1);

6019:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6020:   if (a != (PetscScalar)1.0) {
6021:     PetscUseTypeMethod(mat, scale, a);
6022:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6023:   }
6024:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6025:   PetscFunctionReturn(PETSC_SUCCESS);
6026: }

6028: /*@
6029:   MatNorm - Calculates various norms of a matrix.

6031:   Collective

6033:   Input Parameters:
6034: + mat  - the matrix
6035: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

6037:   Output Parameter:
6038: . nrm - the resulting norm

6040:   Level: intermediate

6042: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
6043: @*/
6044: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
6045: {
6046:   PetscFunctionBegin;
6050:   PetscAssertPointer(nrm, 3);

6052:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6053:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6054:   MatCheckPreallocated(mat, 1);

6056:   PetscUseTypeMethod(mat, norm, type, nrm);
6057:   PetscFunctionReturn(PETSC_SUCCESS);
6058: }

6060: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6061: {
6062:   PetscScalar *ax, nm1;
6063:   PetscInt     st, en, n;

6065:   PetscFunctionBegin;
6066:   PetscCall(VecGetSize(x, &n));
6067:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6068:   nm1 = n - 1;
6069:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6070:   PetscCall(VecGetArrayWrite(x, &ax));
6071:   for (PetscInt i = st; i < en; i++) {
6072:     const PetscInt    ii = i - st;
6073:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6075:     ax[ii] = s * (1.0 + i / nm1);
6076:   }
6077:   PetscCall(VecRestoreArrayWrite(x, &ax));
6078:   PetscFunctionReturn(PETSC_SUCCESS);
6079: }

6081: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6082: {
6083:   Vec         x, y;
6084:   PetscReal   normx, normy;
6085:   PetscInt    i, N;
6086:   PetscRandom rnd;

6088:   PetscFunctionBegin;
6089:   if (maxit < 0) maxit = 1;
6090:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6091:   PetscCall(PetscRandomSetFromOptions(rnd));
6092:   PetscCall(MatCreateVecs(A, &x, &y));
6093:   PetscCall(VecBindToCPU(x, boundtocpu));
6094:   PetscCall(VecBindToCPU(y, boundtocpu));
6095:   PetscCall(VecGetSize(x, &N));
6096:   *n = 0.0;
6097:   for (i = 0; i < maxit; i++) {
6098:     PetscCall(VecSetRandom(x, rnd));
6099:     switch (normtype) {
6100:     case NORM_1:
6101:       PetscCall(VecNorm(x, NORM_1, &normx));
6102:       if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6103:       break;
6104:     case NORM_INFINITY:
6105:       PetscCall(VecShift(x, -0.5));
6106:       PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6107:       break;
6108:     case NORM_2:
6109:       PetscCall(VecNormalize(x, NULL));
6110:       break;
6111:     default:
6112:       PetscUnreachable();
6113:     }
6114:     PetscCall(MatMult(A, x, y));
6115:     PetscCall(VecNorm(y, normtype, &normy));
6116:     *n = PetscMax(*n, normy);
6117:     PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6118:   }
6119:   PetscCall(VecDestroy(&x));
6120:   PetscCall(VecDestroy(&y));
6121:   PetscCall(PetscRandomDestroy(&rnd));
6122:   PetscFunctionReturn(PETSC_SUCCESS);
6123: }

6125: /*@
6126:   MatNormApproximate - Approximate the norm of a matrix.

6128:   Collective

6130:   Input Parameters:
6131: + A        - the matrix
6132: . normtype - the `NormType`
6133: - maxit    - maximum number of iterations to use

6135:   Output Parameter:
6136: . n - the norm estimate

6138:   Level: intermediate

6140:   Notes:
6141:   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`.

6143:   If `maxit` is negative, a default number of iterations (10 for `NORM_1` and `NORM_INFINITY` and 20 for `NORM_2`) is performed.

6145: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6146: @*/
6147: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6148: {
6149:   Vec         x, y, w, z;
6150:   PetscReal   normz, adot;
6151:   PetscScalar dot;
6152:   PetscInt    i, j, N, jold = -1;
6153:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

6155:   PetscFunctionBegin;
6160:   PetscAssertPointer(n, 4);
6161: #if PetscDefined(HAVE_DEVICE)
6162:   boundtocpu = A->boundtocpu;
6163: #endif
6164:   PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6165:   switch (normtype) {
6166:   case NORM_INFINITY:
6167:   case NORM_1:
6168:     if (!hasop) {
6169:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6170:       i = maxit;
6171:       break;
6172:     } else {
6173:       PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6174:       if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6175:       else {
6176:         Mat B;

6178:         PetscCall(MatCreateHermitianTranspose(A, &B));
6179:         A = B;
6180:       }
6181:     }
6182:     if (maxit < 0) maxit = 10; /* pure guess */
6183:     PetscCall(MatCreateVecs(A, &x, &y));
6184:     PetscCall(MatCreateVecs(A, &z, &w));
6185:     PetscCall(VecBindToCPU(x, boundtocpu));
6186:     PetscCall(VecBindToCPU(y, boundtocpu));
6187:     PetscCall(VecBindToCPU(z, boundtocpu));
6188:     PetscCall(VecBindToCPU(w, boundtocpu));
6189:     PetscCall(VecGetSize(x, &N));
6190:     PetscCall(VecSet(x, 1. / N));
6191:     *n = 0.0;
6192:     for (i = 0; i < maxit; i++) {
6193:       PetscCall(MatMult(A, x, y));
6194:       PetscCall(VecNorm(y, NORM_1, n));
6195:       if (PetscDefined(USE_COMPLEX)) {
6196:         PetscCall(VecCopy(y, w));
6197:         PetscCall(VecAbs(w));
6198:         PetscCall(VecPointwiseDivide(w, y, w));
6199:       } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6200:       PetscCall(MatMultHermitianTranspose(A, w, z));
6201:       PetscCall(VecRealPart(z));
6202:       PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6203:       PetscCall(VecDot(x, z, &dot));
6204:       adot = PetscAbsScalar(dot);
6205:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6206:       if (normz <= adot && i > 0) {
6207:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6208:         break;
6209:       }
6210:       PetscCall(VecAbs(z));
6211:       PetscCall(VecMax(z, &j, &normz));
6212:       if (j == jold) {
6213:         PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6214:         break;
6215:       }
6216:       jold = j;
6217:       if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6218:     }
6219:     /* last check */
6220:     if (N > 1) {
6221:       PetscReal ny;

6223:       PetscCall(VecSetFinalNormApp_Private(x));
6224:       PetscCall(MatMult(A, x, y));
6225:       PetscCall(VecNorm(y, NORM_1, &ny));
6226:       ny = 2 * ny / (3 * N);
6227:       PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6228:       *n = PetscMax(*n, ny);
6229:     }
6230:     PetscCall(MatDestroy(&A));
6231:     PetscCall(VecDestroy(&x));
6232:     PetscCall(VecDestroy(&w));
6233:     PetscCall(VecDestroy(&y));
6234:     PetscCall(VecDestroy(&z));
6235:     break;
6236:   case NORM_2:
6237:     if (!hasop) {
6238:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6239:       i = maxit;
6240:       break;
6241:     }
6242:     if (maxit < 0) maxit = 20; /* pure guess */
6243:     PetscCall(MatCreateVecs(A, &x, &y));
6244:     PetscCall(MatCreateVecs(A, &z, NULL));
6245:     PetscCall(VecBindToCPU(x, boundtocpu));
6246:     PetscCall(VecBindToCPU(y, boundtocpu));
6247:     PetscCall(VecBindToCPU(z, boundtocpu));
6248:     PetscCall(VecSetRandom(x, NULL));
6249:     PetscCall(VecNormalize(x, NULL));
6250:     *n = 0.0;
6251:     for (i = 0; i < maxit; i++) {
6252:       PetscCall(MatMult(A, x, y));
6253:       PetscCall(VecNormalize(y, n));
6254:       PetscCall(MatMultHermitianTranspose(A, y, z));
6255:       PetscCall(VecNorm(z, NORM_2, &normz));
6256:       PetscCall(VecDot(x, z, &dot));
6257:       adot = PetscAbsScalar(dot);
6258:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6259:       if (normz <= adot) {
6260:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6261:         break;
6262:       }
6263:       if (i < maxit - 1) {
6264:         Vec t;

6266:         PetscCall(VecNormalize(z, NULL));
6267:         t = x;
6268:         x = z;
6269:         z = t;
6270:       }
6271:     }
6272:     PetscCall(VecDestroy(&x));
6273:     PetscCall(VecDestroy(&y));
6274:     PetscCall(VecDestroy(&z));
6275:     break;
6276:   default:
6277:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6278:   }
6279:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6280:   PetscFunctionReturn(PETSC_SUCCESS);
6281: }

6283: /*
6284:      This variable is used to prevent counting of MatAssemblyBegin() that
6285:    are called from within a MatAssemblyEnd().
6286: */
6287: static PetscInt MatAssemblyEnd_InUse = 0;
6288: /*@
6289:   MatAssemblyBegin - Begins assembling the matrix. This routine should
6290:   be called after completing all calls to `MatSetValues()`.

6292:   Collective

6294:   Input Parameters:
6295: + mat  - the matrix
6296: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6298:   Level: beginner

6300:   Notes:
6301:   `MatSetValues()` generally caches the values that belong to other MPI processes. The matrix is ready to
6302:   use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.

6304:   Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
6305:   in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
6306:   using the matrix.

6308:   ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
6309:   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
6310:   a global collective operation requiring all processes that share the matrix.

6312:   Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
6313:   out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
6314:   before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.

6316: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6317: @*/
6318: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6319: {
6320:   PetscFunctionBegin;
6323:   MatCheckPreallocated(mat, 1);
6324:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6325:   if (mat->assembled) {
6326:     mat->was_assembled = PETSC_TRUE;
6327:     mat->assembled     = PETSC_FALSE;
6328:   }

6330:   if (!MatAssemblyEnd_InUse) {
6331:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6332:     PetscTryTypeMethod(mat, assemblybegin, type);
6333:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6334:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6335:   PetscFunctionReturn(PETSC_SUCCESS);
6336: }

6338: /*@
6339:   MatAssembled - Indicates if a matrix has been assembled and is ready for
6340:   use; for example, in matrix-vector product.

6342:   Not Collective

6344:   Input Parameter:
6345: . mat - the matrix

6347:   Output Parameter:
6348: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6350:   Level: advanced

6352: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6353: @*/
6354: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6355: {
6356:   PetscFunctionBegin;
6358:   PetscAssertPointer(assembled, 2);
6359:   *assembled = mat->assembled;
6360:   PetscFunctionReturn(PETSC_SUCCESS);
6361: }

6363: /*@
6364:   MatAssemblyEnd - Completes assembling the matrix. This routine should
6365:   be called after `MatAssemblyBegin()`.

6367:   Collective

6369:   Input Parameters:
6370: + mat  - the matrix
6371: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6373:   Options Database Key:
6374: . -mat_view viewer_specification - Displays the matrix during this function call. See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

6376:   Level: beginner

6378: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6379:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`, `PetscOptionsCreateViewer()`
6380: @*/
6381: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6382: {
6383:   static PetscInt inassm = 0;
6384:   PetscBool       flg    = PETSC_FALSE;

6386:   PetscFunctionBegin;

6390:   inassm++;
6391:   MatAssemblyEnd_InUse++;
6392:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6393:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6394:     PetscTryTypeMethod(mat, assemblyend, type);
6395:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6396:   } else PetscTryTypeMethod(mat, assemblyend, type);

6398:   /* Flush assembly is not a true assembly */
6399:   if (type != MAT_FLUSH_ASSEMBLY) {
6400:     if (mat->num_ass) {
6401:       if (!mat->symmetry_eternal) {
6402:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6403:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6404:       }
6405:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6406:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6407:     }
6408:     mat->num_ass++;
6409:     mat->assembled        = PETSC_TRUE;
6410:     mat->ass_nonzerostate = mat->nonzerostate;
6411:   }

6413:   mat->insertmode = NOT_SET_VALUES;
6414:   MatAssemblyEnd_InUse--;
6415:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6416:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6417:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6419:     if (mat->checksymmetryonassembly) {
6420:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6421:       if (flg) {
6422:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6423:       } else {
6424:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6425:       }
6426:     }
6427:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6428:   }
6429:   inassm--;
6430:   PetscFunctionReturn(PETSC_SUCCESS);
6431: }

6433: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6434: /*@
6435:   MatSetOption - Sets a parameter option for a matrix. Some options
6436:   may be specific to certain storage formats. Some options
6437:   determine how values will be inserted (or added). Sorted,
6438:   row-oriented input will generally assemble the fastest. The default
6439:   is row-oriented.

6441:   Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`

6443:   Input Parameters:
6444: + mat - the matrix
6445: . op  - the option, one of those listed below (and possibly others),
6446: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6448:   Options Describing Matrix Structure:
6449: + `MAT_SPD`                         - symmetric positive definite
6450: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6451: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6452: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6453: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6454: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6455: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

6457:    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6458:    do not need to be computed (usually at a high cost)

6460:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6461:    Insert a logically dense subblock, which can be
6462: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6464:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6465:    nothing to do with how the data is stored internally in the matrix
6466:    data structure.

6468:    When (re)assembling a matrix, we can restrict the input for
6469:    efficiency/debugging purposes. These options include
6470: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6471: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6472: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-process entries
6473: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6474: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6475: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6476:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6477:                                       performance for very large process counts.
6478: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6479:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6480:                                       functions, instead sending only neighbor messages.

6482:   Level: intermediate

6484:   Notes:
6485:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6487:   Some options are relevant only for particular matrix types and
6488:   are thus ignored by others. Other options are not supported by
6489:   certain matrix types and will generate an error message if set.

6491:   Once `MAT_STRUCTURE_ONLY` has been set to `PETSC_TRUE`, it cannot be set back to `PETSC_FALSE`.

6493:   If using Fortran to compute a matrix, one may need to
6494:   use the column-oriented option (or convert to the row-oriented
6495:   format).

6497:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6498:   that would generate a new entry in the nonzero structure is instead
6499:   ignored. Thus, if memory has not already been allocated for this particular
6500:   data, then the insertion is ignored. For dense matrices, in which
6501:   the entire array is allocated, no entries are ever ignored.
6502:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6504:   `MAT_NEW_NONZERO_LOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6505:   that would generate a new entry in the nonzero structure instead produces
6506:   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

6508:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6509:   that would generate a new entry that has not been preallocated will
6510:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6511:   only.) This is a useful flag when debugging matrix memory preallocation.
6512:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6514:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6515:   other processes should be dropped, rather than stashed.
6516:   This is useful if you know that the "owning" process is also
6517:   always generating the correct matrix entries, so that PETSc need
6518:   not transfer duplicate entries generated on another process.

6520:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6521:   searches during matrix assembly. When this flag is set, the hash table
6522:   is created during the first matrix assembly. This hash table is
6523:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6524:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6525:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6526:   supported by `MATMPIBAIJ` format only.

6528:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6529:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6531:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ`, `MATSELL`, and `MATIS` matrices this will stop zero values
6532:   from creating a zero location in the matrix. A zero on the diagonal is exempt and still creates its
6533:   location, so that operations needing a full diagonal, such as `MatSOR()`, keep working. The exemption
6534:   covers the diagonal portion of the owning process's rows; a zero added with `ADD_VALUES` to a row owned
6535:   by another process is dropped as it is stashed and never reaches that test. A matrix assembled without
6536:   preallocation, through `MatSetUp()`, decides the exemption from process-local indices, so it does not
6537:   hold there when the row and column layouts differ

6539:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6541:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6542:   zero row routines and thus improves performance for very large process counts.

6544:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6545:   part of the matrix (since they should match the upper triangular part).

6547:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6548:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6549:   with finite difference schemes with non-periodic boundary conditions.

6551:   Developer Note:
6552:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6553:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6554:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6555:   not changed.

6557: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6558: @*/
6559: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6560: {
6561:   PetscFunctionBegin;
6563:   if (op > 0) {
6566:   }

6568:   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);

6570:   switch (op) {
6571:   case MAT_FORCE_DIAGONAL_ENTRIES:
6572:     mat->force_diagonals = flg;
6573:     PetscFunctionReturn(PETSC_SUCCESS);
6574:   case MAT_NO_OFF_PROC_ENTRIES:
6575:     mat->nooffprocentries = flg;
6576:     PetscFunctionReturn(PETSC_SUCCESS);
6577:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6578:     mat->assembly_subset = flg;
6579:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6580: #if !PetscDefined(HAVE_MPIUNI)
6581:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6582: #endif
6583:       mat->stash.first_assembly_done = PETSC_FALSE;
6584:     }
6585:     PetscFunctionReturn(PETSC_SUCCESS);
6586:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6587:     mat->nooffproczerorows = flg;
6588:     PetscFunctionReturn(PETSC_SUCCESS);
6589:   case MAT_SPD:
6590:     if (flg) {
6591:       mat->spd                    = PETSC_BOOL3_TRUE;
6592:       mat->symmetric              = PETSC_BOOL3_TRUE;
6593:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6594: #if !PetscDefined(USE_COMPLEX)
6595:       mat->hermitian = PETSC_BOOL3_TRUE;
6596: #endif
6597:     } else {
6598:       mat->spd = PETSC_BOOL3_FALSE;
6599:     }
6600:     break;
6601:   case MAT_SYMMETRIC:
6602:     mat->symmetric = PetscBoolToBool3(flg);
6603:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6604: #if !PetscDefined(USE_COMPLEX)
6605:     mat->hermitian = PetscBoolToBool3(flg);
6606: #endif
6607:     break;
6608:   case MAT_HERMITIAN:
6609:     mat->hermitian = PetscBoolToBool3(flg);
6610:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6611: #if !PetscDefined(USE_COMPLEX)
6612:     mat->symmetric = PetscBoolToBool3(flg);
6613: #endif
6614:     break;
6615:   case MAT_STRUCTURALLY_SYMMETRIC:
6616:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6617:     break;
6618:   case MAT_SYMMETRY_ETERNAL:
6619:     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");
6620:     mat->symmetry_eternal = flg;
6621:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6622:     break;
6623:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6624:     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");
6625:     mat->structural_symmetry_eternal = flg;
6626:     break;
6627:   case MAT_SPD_ETERNAL:
6628:     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");
6629:     mat->spd_eternal = flg;
6630:     if (flg) {
6631:       mat->structural_symmetry_eternal = PETSC_TRUE;
6632:       mat->symmetry_eternal            = PETSC_TRUE;
6633:     }
6634:     break;
6635:   case MAT_STRUCTURE_ONLY:
6636:     PetscCheck(flg || !mat->structure_only, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_STRUCTURE_ONLY to PETSC_FALSE after it has been set to PETSC_TRUE");
6637:     mat->structure_only = flg;
6638:     break;
6639:   case MAT_SORTED_FULL:
6640:     mat->sortedfull = flg;
6641:     break;
6642:   default:
6643:     break;
6644:   }
6645:   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");
6646:   PetscTryTypeMethod(mat, setoption, op, flg);
6647:   PetscFunctionReturn(PETSC_SUCCESS);
6648: }

6650: /*@
6651:   MatGetOption - Gets a parameter option that has been set for a matrix.

6653:   Logically Collective

6655:   Input Parameters:
6656: + mat - the matrix
6657: - op  - the option, this only responds to certain options, check the code for which ones

6659:   Output Parameter:
6660: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6662:   Level: intermediate

6664:   Notes:
6665:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6667:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6668:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6670: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6671:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6672: @*/
6673: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6674: {
6675:   PetscFunctionBegin;

6679:   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);
6680:   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()");

6682:   switch (op) {
6683:   case MAT_NO_OFF_PROC_ENTRIES:
6684:     *flg = mat->nooffprocentries;
6685:     break;
6686:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6687:     *flg = mat->nooffproczerorows;
6688:     break;
6689:   case MAT_SYMMETRIC:
6690:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6691:     break;
6692:   case MAT_HERMITIAN:
6693:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6694:     break;
6695:   case MAT_STRUCTURALLY_SYMMETRIC:
6696:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6697:     break;
6698:   case MAT_SPD:
6699:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6700:     break;
6701:   case MAT_SYMMETRY_ETERNAL:
6702:     *flg = mat->symmetry_eternal;
6703:     break;
6704:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6705:     *flg = mat->symmetry_eternal;
6706:     break;
6707:   default:
6708:     break;
6709:   }
6710:   PetscFunctionReturn(PETSC_SUCCESS);
6711: }

6713: /*@
6714:   MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6715:   this routine retains the old nonzero structure.

6717:   Logically Collective

6719:   Input Parameter:
6720: . mat - the matrix

6722:   Level: intermediate

6724:   Note:
6725:   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.
6726:   See the Performance chapter of the users manual for information on preallocating matrices.
6727:   For matrices with the `MAT_STRUCTURE_ONLY` option set to true, this routine leaves the structure and object state unchanged because no numerical values are stored.

6729: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6730: @*/
6731: PetscErrorCode MatZeroEntries(Mat mat)
6732: {
6733:   PetscFunctionBegin;
6736:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6737:   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");
6738:   MatCheckPreallocated(mat, 1);

6740:   if (mat->structure_only == PETSC_FALSE) {
6741:     PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6742:     PetscUseTypeMethod(mat, zeroentries);
6743:     PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6744:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6745:   }
6746:   PetscFunctionReturn(PETSC_SUCCESS);
6747: }

6749: /*@
6750:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6751:   of a set of rows and columns of a matrix.

6753:   Collective

6755:   Input Parameters:
6756: + mat     - the matrix
6757: . numRows - the number of rows/columns to zero
6758: . rows    - the global row indices
6759: . diag    - value put in the diagonal of the eliminated rows
6760: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6761: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6763:   Level: intermediate

6765:   Notes:
6766:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6768:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6769:   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

6771:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6772:   Krylov method to take advantage of the known solution on the zeroed rows.

6774:   For the parallel case, all processes that share the matrix (i.e.,
6775:   those in the communicator used for matrix creation) MUST call this
6776:   routine, regardless of whether any rows being zeroed are owned by
6777:   them.

6779:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6780:   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
6781:   missing.

6783:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6784:   list only rows local to itself).

6786:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6788: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6789:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6790: @*/
6791: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6792: {
6793:   PetscFunctionBegin;
6796:   if (numRows) PetscAssertPointer(rows, 3);
6797:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6798:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6799:   MatCheckPreallocated(mat, 1);

6801:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6802:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6803:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6804:   PetscFunctionReturn(PETSC_SUCCESS);
6805: }

6807: /*@
6808:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6809:   of a set of rows and columns of a matrix.

6811:   Collective

6813:   Input Parameters:
6814: + mat  - the matrix
6815: . is   - the rows to zero
6816: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6817: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6818: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6820:   Level: intermediate

6822:   Note:
6823:   See `MatZeroRowsColumns()` for details on how this routine operates.

6825: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6826:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6827: @*/
6828: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6829: {
6830:   PetscInt        numRows;
6831:   const PetscInt *rows;

6833:   PetscFunctionBegin;
6838:   PetscCall(ISGetLocalSize(is, &numRows));
6839:   PetscCall(ISGetIndices(is, &rows));
6840:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6841:   PetscCall(ISRestoreIndices(is, &rows));
6842:   PetscFunctionReturn(PETSC_SUCCESS);
6843: }

6845: /*@
6846:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6847:   of a set of rows of a matrix.

6849:   Collective

6851:   Input Parameters:
6852: + mat     - the matrix
6853: . numRows - the number of rows to zero
6854: . rows    - the global row indices
6855: . diag    - value put in the diagonal of the zeroed rows
6856: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6857: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6859:   Level: intermediate

6861:   Notes:
6862:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6864:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6866:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6867:   Krylov method to take advantage of the known solution on the zeroed rows.

6869:   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)
6870:   from the matrix.

6872:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6873:   but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6874:   formats this does not alter the nonzero structure.

6876:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6877:   of the matrix is not changed the values are
6878:   merely zeroed.

6880:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6881:   formats can optionally remove the main diagonal entry from the
6882:   nonzero structure as well, by passing 0.0 as the final argument).

6884:   For the parallel case, all processes that share the matrix (i.e.,
6885:   those in the communicator used for matrix creation) MUST call this
6886:   routine, regardless of whether any rows being zeroed are owned by
6887:   them.

6889:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6890:   list only rows local to itself).

6892:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6893:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6895: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6896:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6897: @*/
6898: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6899: {
6900:   PetscFunctionBegin;
6903:   if (numRows) PetscAssertPointer(rows, 3);
6904:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6905:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6906:   MatCheckPreallocated(mat, 1);

6908:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6909:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6910:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6911:   PetscFunctionReturn(PETSC_SUCCESS);
6912: }

6914: /*@
6915:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6916:   of a set of rows of a matrix indicated by an `IS`

6918:   Collective

6920:   Input Parameters:
6921: + mat  - the matrix
6922: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6923: . diag - value put in all diagonals of eliminated rows
6924: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6925: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6927:   Level: intermediate

6929:   Note:
6930:   See `MatZeroRows()` for details on how this routine operates.

6932: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6933:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6934: @*/
6935: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6936: {
6937:   PetscInt        numRows = 0;
6938:   const PetscInt *rows    = NULL;

6940:   PetscFunctionBegin;
6943:   if (is) {
6945:     PetscCall(ISGetLocalSize(is, &numRows));
6946:     PetscCall(ISGetIndices(is, &rows));
6947:   }
6948:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6949:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6950:   PetscFunctionReturn(PETSC_SUCCESS);
6951: }

6953: /*@
6954:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6955:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6957:   Collective

6959:   Input Parameters:
6960: + mat     - the matrix
6961: . numRows - the number of rows to remove
6962: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6963: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6964: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6965: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6967:   Level: intermediate

6969:   Notes:
6970:   See `MatZeroRows()` for details on how this routine operates.

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

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

6979:   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
6980:   a single value per point) you can skip filling those indices.

6982:   Fortran Note:
6983:   `idxm` and `idxn` should be declared as
6984: .vb
6985:     MatStencil idxm(4, m)
6986: .ve
6987:   and the values inserted using
6988: .vb
6989:     idxm(MatStencil_i, 1) = i
6990:     idxm(MatStencil_j, 1) = j
6991:     idxm(MatStencil_k, 1) = k
6992:     idxm(MatStencil_c, 1) = c
6993:    etc
6994: .ve

6996: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6997:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6998: @*/
6999: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7000: {
7001:   PetscInt  dim    = mat->stencil.dim;
7002:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7003:   PetscInt *dims   = mat->stencil.dims + 1;
7004:   PetscInt *starts = mat->stencil.starts;
7005:   PetscInt *dxm    = (PetscInt *)rows;
7006:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7008:   PetscFunctionBegin;
7011:   if (numRows) PetscAssertPointer(rows, 3);

7013:   PetscCall(PetscMalloc1(numRows, &jdxm));
7014:   for (i = 0; i < numRows; ++i) {
7015:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7016:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7017:     /* Local index in X dir */
7018:     tmp = *dxm++ - starts[0];
7019:     /* Loop over remaining dimensions */
7020:     for (j = 0; j < dim - 1; ++j) {
7021:       /* If nonlocal, set index to be negative */
7022:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7023:       /* Update local index */
7024:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7025:     }
7026:     /* Skip component slot if necessary */
7027:     if (mat->stencil.noc) dxm++;
7028:     /* Local row number */
7029:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7030:   }
7031:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
7032:   PetscCall(PetscFree(jdxm));
7033:   PetscFunctionReturn(PETSC_SUCCESS);
7034: }

7036: /*@
7037:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
7038:   of a set of rows and columns of a matrix.

7040:   Collective

7042:   Input Parameters:
7043: + mat     - the matrix
7044: . numRows - the number of rows/columns to remove
7045: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
7046: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
7047: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7048: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7050:   Level: intermediate

7052:   Notes:
7053:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

7062:   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
7063:   a single value per point) you can skip filling those indices.

7065:   Fortran Note:
7066:   `idxm` and `idxn` should be declared as
7067: .vb
7068:     MatStencil idxm(4, m)
7069: .ve
7070:   and the values inserted using
7071: .vb
7072:     idxm(MatStencil_i, 1) = i
7073:     idxm(MatStencil_j, 1) = j
7074:     idxm(MatStencil_k, 1) = k
7075:     idxm(MatStencil_c, 1) = c
7076:     etc
7077: .ve

7079: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7080:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7081: @*/
7082: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7083: {
7084:   PetscInt  dim    = mat->stencil.dim;
7085:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7086:   PetscInt *dims   = mat->stencil.dims + 1;
7087:   PetscInt *starts = mat->stencil.starts;
7088:   PetscInt *dxm    = (PetscInt *)rows;
7089:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7091:   PetscFunctionBegin;
7094:   if (numRows) PetscAssertPointer(rows, 3);

7096:   PetscCall(PetscMalloc1(numRows, &jdxm));
7097:   for (i = 0; i < numRows; ++i) {
7098:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7099:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7100:     /* Local index in X dir */
7101:     tmp = *dxm++ - starts[0];
7102:     /* Loop over remaining dimensions */
7103:     for (j = 0; j < dim - 1; ++j) {
7104:       /* If nonlocal, set index to be negative */
7105:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7106:       /* Update local index */
7107:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7108:     }
7109:     /* Skip component slot if necessary */
7110:     if (mat->stencil.noc) dxm++;
7111:     /* Local row number */
7112:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7113:   }
7114:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7115:   PetscCall(PetscFree(jdxm));
7116:   PetscFunctionReturn(PETSC_SUCCESS);
7117: }

7119: /*@
7120:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7121:   of a set of rows of a matrix; using local numbering of rows.

7123:   Collective

7125:   Input Parameters:
7126: + mat     - the matrix
7127: . numRows - the number of rows to remove
7128: . rows    - the local row indices
7129: . diag    - value put in all diagonals of eliminated rows
7130: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7131: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7133:   Level: intermediate

7135:   Notes:
7136:   Before calling `MatZeroRowsLocal()`, the user must first set the
7137:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7139:   See `MatZeroRows()` for details on how this routine operates.

7141: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7142:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7143: @*/
7144: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7145: {
7146:   PetscFunctionBegin;
7149:   if (numRows) PetscAssertPointer(rows, 3);
7150:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7151:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7152:   MatCheckPreallocated(mat, 1);

7154:   if (mat->ops->zerorowslocal) {
7155:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7156:   } else {
7157:     IS        is, newis;
7158:     PetscInt *newRows, nl = 0;

7160:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7161:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7162:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7163:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7164:     for (PetscInt i = 0; i < numRows; i++)
7165:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7166:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7167:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7168:     PetscCall(ISDestroy(&newis));
7169:     PetscCall(ISDestroy(&is));
7170:   }
7171:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7172:   PetscFunctionReturn(PETSC_SUCCESS);
7173: }

7175: /*@
7176:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7177:   of a set of rows of a matrix; using local numbering of rows.

7179:   Collective

7181:   Input Parameters:
7182: + mat  - the matrix
7183: . is   - index set of rows to remove
7184: . diag - value put in all diagonals of eliminated rows
7185: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7186: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7188:   Level: intermediate

7190:   Notes:
7191:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7192:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7194:   See `MatZeroRows()` for details on how this routine operates.

7196: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7197:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7198: @*/
7199: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7200: {
7201:   PetscInt        numRows;
7202:   const PetscInt *rows;

7204:   PetscFunctionBegin;
7208:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7209:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7210:   MatCheckPreallocated(mat, 1);

7212:   PetscCall(ISGetLocalSize(is, &numRows));
7213:   PetscCall(ISGetIndices(is, &rows));
7214:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7215:   PetscCall(ISRestoreIndices(is, &rows));
7216:   PetscFunctionReturn(PETSC_SUCCESS);
7217: }

7219: /*@
7220:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7221:   of a set of rows and columns of a matrix; using local numbering of rows.

7223:   Collective

7225:   Input Parameters:
7226: + mat     - the matrix
7227: . numRows - the number of rows to remove
7228: . rows    - the global row indices
7229: . diag    - value put in all diagonals of eliminated rows
7230: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7231: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7233:   Level: intermediate

7235:   Notes:
7236:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7237:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7239:   See `MatZeroRowsColumns()` for details on how this routine operates.

7241: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7242:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7243: @*/
7244: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7245: {
7246:   PetscFunctionBegin;
7249:   if (numRows) PetscAssertPointer(rows, 3);
7250:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7251:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7252:   MatCheckPreallocated(mat, 1);

7254:   if (mat->ops->zerorowscolumnslocal) {
7255:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7256:   } else {
7257:     IS        is, newis;
7258:     PetscInt *newRows, nl = 0;

7260:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7261:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7262:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7263:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7264:     for (PetscInt i = 0; i < numRows; i++)
7265:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7266:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7267:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7268:     PetscCall(ISDestroy(&newis));
7269:     PetscCall(ISDestroy(&is));
7270:   }
7271:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7272:   PetscFunctionReturn(PETSC_SUCCESS);
7273: }

7275: /*@
7276:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7277:   of a set of rows and columns of a matrix; using local numbering of rows.

7279:   Collective

7281:   Input Parameters:
7282: + mat  - the matrix
7283: . is   - index set of rows to remove
7284: . diag - value put in all diagonals of eliminated rows
7285: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7286: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7288:   Level: intermediate

7290:   Notes:
7291:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7292:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7294:   See `MatZeroRowsColumns()` for details on how this routine operates.

7296: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7297:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7298: @*/
7299: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7300: {
7301:   PetscInt        numRows;
7302:   const PetscInt *rows;

7304:   PetscFunctionBegin;
7308:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7309:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7310:   MatCheckPreallocated(mat, 1);

7312:   PetscCall(ISGetLocalSize(is, &numRows));
7313:   PetscCall(ISGetIndices(is, &rows));
7314:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7315:   PetscCall(ISRestoreIndices(is, &rows));
7316:   PetscFunctionReturn(PETSC_SUCCESS);
7317: }

7319: /*@
7320:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7322:   Not Collective

7324:   Input Parameter:
7325: . mat - the matrix

7327:   Output Parameters:
7328: + m - the number of global rows
7329: - n - the number of global columns

7331:   Level: beginner

7333:   Note:
7334:   Both output parameters can be `NULL` on input.

7336: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7337: @*/
7338: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7339: {
7340:   PetscFunctionBegin;
7342:   if (m) *m = mat->rmap->N;
7343:   if (n) *n = mat->cmap->N;
7344:   PetscFunctionReturn(PETSC_SUCCESS);
7345: }

7347: /*@
7348:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7349:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7351:   Not Collective

7353:   Input Parameter:
7354: . mat - the matrix

7356:   Output Parameters:
7357: + m - the number of local rows, use `NULL` to not obtain this value
7358: - n - the number of local columns, use `NULL` to not obtain this value

7360:   Level: beginner

7362: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7363: @*/
7364: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7365: {
7366:   PetscFunctionBegin;
7368:   if (m) PetscAssertPointer(m, 2);
7369:   if (n) PetscAssertPointer(n, 3);
7370:   if (m) *m = mat->rmap->n;
7371:   if (n) *n = mat->cmap->n;
7372:   PetscFunctionReturn(PETSC_SUCCESS);
7373: }

7375: /*@
7376:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7377:   vector one multiplies this matrix by that are owned by this process.

7379:   Not Collective, unless matrix has not been allocated, then collective

7381:   Input Parameter:
7382: . mat - the matrix

7384:   Output Parameters:
7385: + m - the global index of the first local column, use `NULL` to not obtain this value
7386: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7388:   Level: developer

7390:   Notes:
7391:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7393:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7394:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7399:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7400:   Layouts](sec_matlayout) for details on matrix layouts.

7402: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7403:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7404: @*/
7405: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7406: {
7407:   PetscFunctionBegin;
7410:   if (m) PetscAssertPointer(m, 2);
7411:   if (n) PetscAssertPointer(n, 3);
7412:   MatCheckPreallocated(mat, 1);
7413:   if (m) *m = mat->cmap->rstart;
7414:   if (n) *n = mat->cmap->rend;
7415:   PetscFunctionReturn(PETSC_SUCCESS);
7416: }

7418: /*@
7419:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7420:   this MPI process.

7422:   Not Collective

7424:   Input Parameter:
7425: . mat - the matrix

7427:   Output Parameters:
7428: + m - the global index of the first local row, use `NULL` to not obtain this value
7429: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7431:   Level: beginner

7433:   Notes:
7434:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7436:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7437:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

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

7444:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7445:   would contain the result of a matrix vector product with this matrix. See [Matrix
7446:   Layouts](sec_matlayout) for details on matrix layouts.

7448: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7449:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7450: @*/
7451: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7452: {
7453:   PetscFunctionBegin;
7456:   if (m) PetscAssertPointer(m, 2);
7457:   if (n) PetscAssertPointer(n, 3);
7458:   MatCheckPreallocated(mat, 1);
7459:   if (m) *m = mat->rmap->rstart;
7460:   if (n) *n = mat->rmap->rend;
7461:   PetscFunctionReturn(PETSC_SUCCESS);
7462: }

7464: /*@
7465:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7466:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7468:   Not Collective, unless matrix has not been allocated

7470:   Input Parameter:
7471: . mat - the matrix

7473:   Output Parameter:
7474: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7475:            where `size` is the number of MPI processes used by `mat`

7477:   Level: beginner

7479:   Notes:
7480:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7482:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7483:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7488:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7489:   would contain the result of a matrix vector product with this matrix. See [Matrix
7490:   Layouts](sec_matlayout) for details on matrix layouts.

7492: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7493:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7494:           `DMDAGetGhostCorners()`, `DM`
7495: @*/
7496: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7497: {
7498:   PetscFunctionBegin;
7501:   MatCheckPreallocated(mat, 1);
7502:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7503:   PetscFunctionReturn(PETSC_SUCCESS);
7504: }

7506: /*@
7507:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7508:   vector one multiplies this vector by that are owned by each process.

7510:   Not Collective, unless matrix has not been allocated

7512:   Input Parameter:
7513: . mat - the matrix

7515:   Output Parameter:
7516: . ranges - start of each process's portion plus one more than the total length at the end

7518:   Level: beginner

7520:   Notes:
7521:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7523:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7524:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7529:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7530:   Layouts](sec_matlayout) for details on matrix layouts.

7532: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7533:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7534:           `DMDAGetGhostCorners()`, `DM`
7535: @*/
7536: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7537: {
7538:   PetscFunctionBegin;
7541:   MatCheckPreallocated(mat, 1);
7542:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7543:   PetscFunctionReturn(PETSC_SUCCESS);
7544: }

7546: /*@
7547:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7549:   Not Collective

7551:   Input Parameter:
7552: . A - matrix

7554:   Output Parameters:
7555: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7556: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7558:   Level: intermediate

7560:   Note:
7561:   You should call `ISDestroy()` on the returned `IS`

7563:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7564:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7565:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7566:   details on matrix layouts.

7568: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7569: @*/
7570: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7571: {
7572:   PetscErrorCode (*f)(Mat, IS *, IS *);

7574:   PetscFunctionBegin;
7577:   MatCheckPreallocated(A, 1);
7578:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7579:   if (f) {
7580:     PetscCall((*f)(A, rows, cols));
7581:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7582:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7583:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7584:   }
7585:   PetscFunctionReturn(PETSC_SUCCESS);
7586: }

7588: /*@
7589:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7590:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7591:   to complete the factorization.

7593:   Collective

7595:   Input Parameters:
7596: + fact - the factorized matrix obtained with `MatGetFactor()`
7597: . mat  - the matrix
7598: . row  - row permutation
7599: . col  - column permutation
7600: - info - structure containing
7601: .vb
7602:       levels - number of levels of fill.
7603:       expected fill - as ratio of original fill.
7604:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7605:                 missing diagonal entries)
7606: .ve

7608:   Level: developer

7610:   Notes:
7611:   See [Matrix Factorization](sec_matfactor) for additional information.

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

7617:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

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

7622: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7623:           `MatGetOrdering()`, `MatFactorInfo`
7624: @*/
7625: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7626: {
7627:   PetscFunctionBegin;
7632:   PetscAssertPointer(info, 5);
7633:   PetscAssertPointer(fact, 1);
7634:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7635:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7636:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7637:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7638:   MatCheckPreallocated(mat, 2);

7640:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7641:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7642:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7643:   PetscFunctionReturn(PETSC_SUCCESS);
7644: }

7646: /*@
7647:   MatICCFactorSymbolic - Performs symbolic incomplete
7648:   Cholesky factorization for a symmetric matrix. Use
7649:   `MatCholeskyFactorNumeric()` to complete the factorization.

7651:   Collective

7653:   Input Parameters:
7654: + fact - the factorized matrix obtained with `MatGetFactor()`
7655: . mat  - the matrix to be factored
7656: . perm - row and column permutation
7657: - info - structure containing
7658: .vb
7659:       levels - number of levels of fill.
7660:       expected fill - as ratio of original fill.
7661: .ve

7663:   Level: developer

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

7670:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

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

7675: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7676: @*/
7677: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7678: {
7679:   PetscFunctionBegin;
7683:   PetscAssertPointer(info, 4);
7684:   PetscAssertPointer(fact, 1);
7685:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7686:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7687:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7688:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7689:   MatCheckPreallocated(mat, 2);

7691:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7692:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7693:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7694:   PetscFunctionReturn(PETSC_SUCCESS);
7695: }

7697: /*@
7698:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7699:   points to an array of valid matrices, they may be reused to store the new
7700:   submatrices.

7702:   Collective

7704:   Input Parameters:
7705: + mat   - the matrix
7706: . n     - the number of submatrixes to be extracted (on this process, may be zero)
7707: . irow  - index set of rows to extract
7708: . icol  - index set of columns to extract
7709: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7711:   Output Parameter:
7712: . submat - the array of submatrices

7714:   Level: advanced

7716:   Notes:
7717:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7718:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7719:   to extract a parallel submatrix.

7721:   Some matrix types place restrictions on the row and column
7722:   indices, such as that they be sorted or that they be equal to each other.
7723:   `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.

7725:   The index sets may not have duplicate entries.

7727:   When extracting submatrices from a parallel matrix, each process can
7728:   form a different submatrix by setting the rows and columns of its
7729:   individual index sets according to the local submatrix desired.

7731:   When finished using the submatrices, the user should destroy
7732:   them with `MatDestroySubMatrices()`.

7734:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7735:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7737:   This routine creates the matrices in submat; you should NOT create them before
7738:   calling it. It also allocates the array of matrix pointers submat.

7740:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7741:   request one row/column in a block, they must request all rows/columns that are in
7742:   that block. For example, if the block size is 2 you cannot request just row 0 and
7743:   column 0.

7745:   Fortran Note:
7746: .vb
7747:   Mat, pointer :: submat(:)
7748: .ve

7750: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7751: @*/
7752: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7753: {
7754:   PetscInt  i;
7755:   PetscBool eq;

7757:   PetscFunctionBegin;
7760:   if (n) {
7761:     PetscAssertPointer(irow, 3);
7763:     PetscAssertPointer(icol, 4);
7765:   }
7766:   PetscAssertPointer(submat, 6);
7767:   if (n && scall == MAT_REUSE_MATRIX) {
7768:     PetscAssertPointer(*submat, 6);
7770:   }
7771:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7772:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7773:   MatCheckPreallocated(mat, 1);
7774:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7775:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7776:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7777:   for (i = 0; i < n; i++) {
7778:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7779:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7780:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7781: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7782:     if (mat->boundtocpu && mat->bindingpropagates) {
7783:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7784:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7785:     }
7786: #endif
7787:   }
7788:   PetscFunctionReturn(PETSC_SUCCESS);
7789: }

7791: /*@
7792:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7794:   Collective

7796:   Input Parameters:
7797: + mat   - the matrix
7798: . n     - the number of submatrixes to be extracted
7799: . irow  - index set of rows to extract
7800: . icol  - index set of columns to extract
7801: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7803:   Output Parameter:
7804: . submat - the array of submatrices

7806:   Level: advanced

7808:   Note:
7809:   This is used by `PCGASM`

7811: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7812: @*/
7813: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7814: {
7815:   PetscInt  i;
7816:   PetscBool eq;

7818:   PetscFunctionBegin;
7821:   if (n) {
7822:     PetscAssertPointer(irow, 3);
7824:     PetscAssertPointer(icol, 4);
7826:   }
7827:   PetscAssertPointer(submat, 6);
7828:   if (n && scall == MAT_REUSE_MATRIX) {
7829:     PetscAssertPointer(*submat, 6);
7831:   }
7832:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7833:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7834:   MatCheckPreallocated(mat, 1);

7836:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7837:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7838:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7839:   for (i = 0; i < n; i++) {
7840:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7841:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7842:   }
7843:   PetscFunctionReturn(PETSC_SUCCESS);
7844: }

7846: /*@
7847:   MatDestroyMatrices - Destroys an array of matrices

7849:   Collective

7851:   Input Parameters:
7852: + n   - the number of local matrices
7853: - mat - the matrices (this is a pointer to the array of matrices)

7855:   Level: advanced

7857:   Notes:
7858:   Frees not only the matrices, but also the array that contains the matrices

7860:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7862: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7863: @*/
7864: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7865: {
7866:   PetscInt i;

7868:   PetscFunctionBegin;
7869:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7870:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7871:   PetscAssertPointer(mat, 2);

7873:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7875:   /* memory is allocated even if n = 0 */
7876:   PetscCall(PetscFree(*mat));
7877:   PetscFunctionReturn(PETSC_SUCCESS);
7878: }

7880: /*@
7881:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7883:   Collective

7885:   Input Parameters:
7886: + n   - the number of local matrices
7887: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7889:   Level: advanced

7891:   Note:
7892:   Frees not only the matrices, but also the array that contains the matrices

7894: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7895: @*/
7896: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7897: {
7898:   Mat mat0;

7900:   PetscFunctionBegin;
7901:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7902:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7903:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7904:   PetscAssertPointer(mat, 2);

7906:   mat0 = (*mat)[0];
7907:   if (mat0 && mat0->ops->destroysubmatrices) {
7908:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7909:   } else {
7910:     PetscCall(MatDestroyMatrices(n, mat));
7911:   }
7912:   PetscFunctionReturn(PETSC_SUCCESS);
7913: }

7915: /*@
7916:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7918:   Collective

7920:   Input Parameter:
7921: . mat - the matrix

7923:   Output Parameter:
7924: . matstruct - the sequential matrix with the nonzero structure of `mat`

7926:   Level: developer

7928: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7929: @*/
7930: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7931: {
7932:   PetscFunctionBegin;
7934:   PetscAssertPointer(matstruct, 2);

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

7940:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7941:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7942:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7943:   PetscFunctionReturn(PETSC_SUCCESS);
7944: }

7946: /*@
7947:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7949:   Collective

7951:   Input Parameter:
7952: . mat - the matrix

7954:   Level: advanced

7956:   Note:
7957:   This is not needed, one can just call `MatDestroy()`

7959: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7960: @*/
7961: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7962: {
7963:   PetscFunctionBegin;
7964:   PetscAssertPointer(mat, 1);
7965:   PetscCall(MatDestroy(mat));
7966:   PetscFunctionReturn(PETSC_SUCCESS);
7967: }

7969: /*@
7970:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7971:   replaces the index sets by larger ones that represent submatrices with
7972:   additional overlap.

7974:   Collective

7976:   Input Parameters:
7977: + mat - the matrix
7978: . n   - the number of index sets
7979: . is  - the array of index sets (these index sets will changed during the call)
7980: - ov  - the additional overlap requested

7982:   Options Database Key:
7983: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7985:   Level: developer

7987:   Note:
7988:   The computed overlap preserves the matrix block sizes when the blocks are square.
7989:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7990:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

7992: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7993: @*/
7994: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7995: {
7996:   PetscInt i, bs, cbs;

7998:   PetscFunctionBegin;
8002:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8003:   if (n) {
8004:     PetscAssertPointer(is, 3);
8006:   }
8007:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8008:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8009:   MatCheckPreallocated(mat, 1);

8011:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
8012:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8013:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
8014:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8015:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
8016:   if (bs == cbs) {
8017:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
8018:   }
8019:   PetscFunctionReturn(PETSC_SUCCESS);
8020: }

8022: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

8024: /*@
8025:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
8026:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
8027:   additional overlap.

8029:   Collective

8031:   Input Parameters:
8032: + mat - the matrix
8033: . n   - the number of index sets
8034: . is  - the array of index sets (these index sets will changed during the call)
8035: - ov  - the additional overlap requested

8037:   `   Options Database Key:
8038: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

8040:   Level: developer

8042: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
8043: @*/
8044: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
8045: {
8046:   PetscInt i;

8048:   PetscFunctionBegin;
8051:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8052:   if (n) {
8053:     PetscAssertPointer(is, 3);
8055:   }
8056:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8057:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8058:   MatCheckPreallocated(mat, 1);
8059:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
8060:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8061:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
8062:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8063:   PetscFunctionReturn(PETSC_SUCCESS);
8064: }

8066: /*@
8067:   MatGetBlockSize - Returns the matrix block size.

8069:   Not Collective

8071:   Input Parameter:
8072: . mat - the matrix

8074:   Output Parameter:
8075: . bs - block size

8077:   Level: intermediate

8079:   Notes:
8080:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8082:   If the block size has not been set yet this routine returns 1.

8084: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8085: @*/
8086: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8087: {
8088:   PetscFunctionBegin;
8090:   PetscAssertPointer(bs, 2);
8091:   *bs = mat->rmap->bs;
8092:   PetscFunctionReturn(PETSC_SUCCESS);
8093: }

8095: /*@
8096:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8098:   Not Collective

8100:   Input Parameter:
8101: . mat - the matrix

8103:   Output Parameters:
8104: + rbs - row block size
8105: - cbs - column block size

8107:   Level: intermediate

8109:   Notes:
8110:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8111:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8113:   If a block size has not been set yet this routine returns 1.

8115: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8116: @*/
8117: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8118: {
8119:   PetscFunctionBegin;
8121:   if (rbs) PetscAssertPointer(rbs, 2);
8122:   if (cbs) PetscAssertPointer(cbs, 3);
8123:   if (rbs) *rbs = mat->rmap->bs;
8124:   if (cbs) *cbs = mat->cmap->bs;
8125:   PetscFunctionReturn(PETSC_SUCCESS);
8126: }

8128: /*@
8129:   MatSetBlockSize - Sets the matrix block size.

8131:   Logically Collective

8133:   Input Parameters:
8134: + mat - the matrix
8135: - bs  - block size

8137:   Level: intermediate

8139:   Notes:
8140:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8141:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8143:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8144:   is compatible with the matrix local sizes.

8146: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8147: @*/
8148: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8149: {
8150:   PetscFunctionBegin;
8153:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8154:   PetscFunctionReturn(PETSC_SUCCESS);
8155: }

8157: typedef struct {
8158:   PetscInt         n;
8159:   IS              *is;
8160:   Mat             *mat;
8161:   PetscObjectState nonzerostate;
8162:   Mat              C;
8163: } EnvelopeData;

8165: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8166: {
8167:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8169:   PetscFunctionBegin;
8170:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8171:   PetscCall(PetscFree(edata->is));
8172:   PetscCall(PetscFree(edata));
8173:   PetscFunctionReturn(PETSC_SUCCESS);
8174: }

8176: /*@
8177:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8178:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8180:   Collective

8182:   Input Parameter:
8183: . mat - the matrix

8185:   Level: intermediate

8187:   Notes:
8188:   There can be zeros within the blocks

8190:   The blocks can overlap between processes, including laying on more than two processes

8192: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8193: @*/
8194: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8195: {
8196:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8197:   PetscInt          *diag, *odiag, sc;
8198:   VecScatter         scatter;
8199:   PetscScalar       *seqv;
8200:   const PetscScalar *parv;
8201:   const PetscInt    *ia, *ja;
8202:   PetscBool          set, flag, done;
8203:   Mat                AA = mat, A;
8204:   MPI_Comm           comm;
8205:   PetscMPIInt        rank, size, tag;
8206:   MPI_Status         status;
8207:   PetscContainer     container;
8208:   EnvelopeData      *edata;
8209:   Vec                seq, par;
8210:   IS                 isglobal;

8212:   PetscFunctionBegin;
8214:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8215:   if (!set || !flag) {
8216:     /* TODO: only needs nonzero structure of transpose */
8217:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8218:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8219:   }
8220:   PetscCall(MatAIJGetLocalMat(AA, &A));
8221:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8222:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8224:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8225:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8226:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8227:   PetscCallMPI(MPI_Comm_size(comm, &size));
8228:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8230:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8232:   if (rank > 0) {
8233:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8234:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8235:   }
8236:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8237:   for (i = 0; i < n; i++) {
8238:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8239:     II  = rstart + i;
8240:     if (env == II) {
8241:       starts[lblocks]  = tbs;
8242:       sizes[lblocks++] = 1 + II - tbs;
8243:       tbs              = 1 + II;
8244:     }
8245:   }
8246:   if (rank < size - 1) {
8247:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8248:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8249:   }

8251:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8252:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8253:   PetscCall(MatDestroy(&A));

8255:   PetscCall(PetscNew(&edata));
8256:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8257:   edata->n = lblocks;
8258:   /* create IS needed for extracting blocks from the original matrix */
8259:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8260:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8262:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8263:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8264:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8265:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8266:   PetscCall(MatSetType(edata->C, MATAIJ));

8268:   /* Communicate the start and end of each row, from each block to the correct rank */
8269:   /* TODO: Use PetscSF instead of VecScatter */
8270:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8271:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8272:   PetscCall(VecGetArrayWrite(seq, &seqv));
8273:   for (PetscInt i = 0; i < lblocks; i++) {
8274:     for (PetscInt j = 0; j < sizes[i]; j++) {
8275:       seqv[cnt]     = starts[i];
8276:       seqv[cnt + 1] = starts[i] + sizes[i];
8277:       cnt += 2;
8278:     }
8279:   }
8280:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
8281:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8282:   sc -= cnt;
8283:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8284:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8285:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8286:   PetscCall(ISDestroy(&isglobal));
8287:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8288:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8289:   PetscCall(VecScatterDestroy(&scatter));
8290:   PetscCall(VecDestroy(&seq));
8291:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8292:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8293:   PetscCall(VecGetArrayRead(par, &parv));
8294:   cnt = 0;
8295:   PetscCall(MatGetSize(mat, NULL, &n));
8296:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8297:     PetscInt start, end, d = 0, od = 0;

8299:     start = (PetscInt)PetscRealPart(parv[cnt]);
8300:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
8301:     cnt += 2;

8303:     if (start < cstart) {
8304:       od += cstart - start + n - cend;
8305:       d += cend - cstart;
8306:     } else if (start < cend) {
8307:       od += n - cend;
8308:       d += cend - start;
8309:     } else od += n - start;
8310:     if (end <= cstart) {
8311:       od -= cstart - end + n - cend;
8312:       d -= cend - cstart;
8313:     } else if (end < cend) {
8314:       od -= n - cend;
8315:       d -= cend - end;
8316:     } else od -= n - end;

8318:     odiag[i] = od;
8319:     diag[i]  = d;
8320:   }
8321:   PetscCall(VecRestoreArrayRead(par, &parv));
8322:   PetscCall(VecDestroy(&par));
8323:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8324:   PetscCall(PetscFree2(diag, odiag));
8325:   PetscCall(PetscFree2(sizes, starts));

8327:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8328:   PetscCall(PetscContainerSetPointer(container, edata));
8329:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8330:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8331:   PetscCall(PetscObjectDereference((PetscObject)container));
8332:   PetscFunctionReturn(PETSC_SUCCESS);
8333: }

8335: /*@
8336:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8338:   Collective

8340:   Input Parameters:
8341: + A     - the matrix
8342: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8344:   Output Parameter:
8345: . C - matrix with inverted block diagonal of `A`

8347:   Level: advanced

8349:   Note:
8350:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8352: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8353: @*/
8354: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8355: {
8356:   PetscContainer   container;
8357:   EnvelopeData    *edata;
8358:   PetscObjectState nonzerostate;

8360:   PetscFunctionBegin;
8361:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8362:   if (!container) {
8363:     PetscCall(MatComputeVariableBlockEnvelope(A));
8364:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8365:   }
8366:   PetscCall(PetscContainerGetPointer(container, &edata));
8367:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8368:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8369:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8371:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8372:   *C = edata->C;

8374:   for (PetscInt i = 0; i < edata->n; i++) {
8375:     Mat          D;
8376:     PetscScalar *dvalues;

8378:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8379:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8380:     PetscCall(MatSeqDenseInvert(D));
8381:     PetscCall(MatDenseGetArray(D, &dvalues));
8382:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8383:     PetscCall(MatDestroy(&D));
8384:   }
8385:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8386:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8387:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8388:   PetscFunctionReturn(PETSC_SUCCESS);
8389: }

8391: /*@
8392:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8394:   Not Collective

8396:   Input Parameters:
8397: + mat     - the matrix
8398: . nblocks - the number of blocks on this process, each block can only exist on a single MPI process
8399: - bsizes  - the block sizes

8401:   Level: intermediate

8403:   Note:
8404:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8406: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8407:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8408: @*/
8409: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8410: {
8411:   PetscInt ncnt = 0, nlocal;

8413:   PetscFunctionBegin;
8415:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8416:   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);
8417:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8418:   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);
8419:   PetscCall(PetscFree(mat->bsizes));
8420:   mat->nblocks = nblocks;
8421:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8422:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8423:   PetscFunctionReturn(PETSC_SUCCESS);
8424: }

8426: /*@
8427:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8429:   Not Collective; No Fortran Support

8431:   Input Parameter:
8432: . mat - the matrix

8434:   Output Parameters:
8435: + nblocks - the number of blocks on this process
8436: - bsizes  - the block sizes

8438:   Level: intermediate

8440: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8441: @*/
8442: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8443: {
8444:   PetscFunctionBegin;
8446:   if (nblocks) *nblocks = mat->nblocks;
8447:   if (bsizes) *bsizes = mat->bsizes;
8448:   PetscFunctionReturn(PETSC_SUCCESS);
8449: }

8451: /*@
8452:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8454:   Not Collective

8456:   Input Parameters:
8457: + subA  - the submatrix
8458: . A     - the original matrix
8459: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8461:   Level: developer

8463:   Note:
8464:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8466: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8467: @*/
8468: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8469: {
8470:   const PetscInt *rows;
8471:   PetscInt        n, rStart, rEnd, Nb = 0;
8472:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8474:   PetscFunctionBegin;
8475:   // The code for block size extraction does not support an unsorted IS
8476:   if (flg) PetscCall(ISSorted(isrow, &flg));
8477:   // We don't support originally off-diagonal blocks
8478:   if (flg) {
8479:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8480:     PetscCall(ISGetLocalSize(isrow, &n));
8481:     PetscCall(ISGetIndices(isrow, &rows));
8482:     for (PetscInt i = 0; i < n && flg; ++i) {
8483:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8484:     }
8485:     PetscCall(ISRestoreIndices(isrow, &rows));
8486:   }
8487:   // quiet return if we can't extract block size
8488:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8489:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8491:   // extract block sizes
8492:   PetscCall(ISGetIndices(isrow, &rows));
8493:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8494:     PetscBool occupied = PETSC_FALSE;

8496:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8497:       const PetscInt row = gr + br;

8499:       if (i == n) break;
8500:       if (rows[i] == row) {
8501:         occupied = PETSC_TRUE;
8502:         ++i;
8503:       }
8504:       while (i < n && rows[i] < row) ++i;
8505:     }
8506:     gr += A->bsizes[b];
8507:     if (occupied) ++Nb;
8508:   }
8509:   subA->nblocks = Nb;
8510:   PetscCall(PetscFree(subA->bsizes));
8511:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8512:   PetscInt sb = 0;
8513:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8514:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8515:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8516:       const PetscInt row = gr + br;

8518:       if (i == n) break;
8519:       if (rows[i] == row) {
8520:         ++subA->bsizes[sb];
8521:         ++i;
8522:       }
8523:       while (i < n && rows[i] < row) ++i;
8524:     }
8525:     gr += A->bsizes[b];
8526:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8527:   }
8528:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8529:   PetscInt nlocal, ncnt = 0;
8530:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8531:   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);
8532:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8533:   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);
8534:   PetscCall(ISRestoreIndices(isrow, &rows));
8535:   PetscFunctionReturn(PETSC_SUCCESS);
8536: }

8538: /*@
8539:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8541:   Logically Collective

8543:   Input Parameters:
8544: + mat - the matrix
8545: . rbs - row block size
8546: - cbs - column block size

8548:   Level: intermediate

8550:   Notes:
8551:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8552:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8553:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8555:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8556:   are compatible with the matrix local sizes.

8558:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8560: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8561: @*/
8562: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8563: {
8564:   PetscFunctionBegin;
8568:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8569:   if (mat->rmap->refcnt) {
8570:     ISLocalToGlobalMapping l2g  = NULL;
8571:     PetscLayout            nmap = NULL;

8573:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8574:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8575:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8576:     mat->rmap          = nmap;
8577:     mat->rmap->mapping = l2g;
8578:   }
8579:   if (mat->cmap->refcnt) {
8580:     ISLocalToGlobalMapping l2g  = NULL;
8581:     PetscLayout            nmap = NULL;

8583:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8584:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8585:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8586:     mat->cmap          = nmap;
8587:     mat->cmap->mapping = l2g;
8588:   }
8589:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8590:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8591:   PetscFunctionReturn(PETSC_SUCCESS);
8592: }

8594: /*@
8595:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8597:   Logically Collective

8599:   Input Parameters:
8600: + mat     - the matrix
8601: . fromRow - matrix from which to copy row block size
8602: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8604:   Level: developer

8606: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8607: @*/
8608: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8609: {
8610:   PetscFunctionBegin;
8614:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8615:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8616:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8617:   PetscFunctionReturn(PETSC_SUCCESS);
8618: }

8620: /*@
8621:   MatResidual - Default routine to calculate the residual $r = b - Ax$

8623:   Collective

8625:   Input Parameters:
8626: + mat - the matrix
8627: . b   - the right-hand-side
8628: - x   - the approximate solution

8630:   Output Parameter:
8631: . r - location to store the residual

8633:   Level: developer

8635: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8636: @*/
8637: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8638: {
8639:   PetscFunctionBegin;
8645:   MatCheckPreallocated(mat, 1);
8646:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8647:   if (!mat->ops->residual) {
8648:     PetscCall(MatMult(mat, x, r));
8649:     PetscCall(VecAYPX(r, -1.0, b));
8650:   } else {
8651:     PetscUseTypeMethod(mat, residual, b, x, r);
8652:   }
8653:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8654:   PetscFunctionReturn(PETSC_SUCCESS);
8655: }

8657: /*@
8658:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8660:   Collective

8662:   Input Parameters:
8663: + mat             - the matrix
8664: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8665: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8666: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8667:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8668:                     always used.

8670:   Output Parameters:
8671: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8672: . 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
8673: . ja   - the column indices, use `NULL` if not needed
8674: - done - indicates if the routine actually worked and returned appropriate `ia` and `ja` arrays; callers
8675:          are responsible for handling the case when done is `PETSC_FALSE` and `ia` and `ja` are not provided

8677:   Level: developer

8679:   Notes:
8680:   You CANNOT change any of the `ia` or `ja` values.

8682:   Use `MatRestoreRowIJ()` when you are finished accessing the `ia` and `ja` values.

8684:   Fortran Notes:
8685:   Use
8686: .vb
8687:     PetscInt, pointer :: ia(:),ja(:)
8688:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8689:     ! Access the ith and jth entries via ia(i) and ja(j)
8690: .ve

8692: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8693: @*/
8694: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8695: {
8696:   PetscFunctionBegin;
8699:   if (n) PetscAssertPointer(n, 5);
8700:   if (ia) PetscAssertPointer(ia, 6);
8701:   if (ja) PetscAssertPointer(ja, 7);
8702:   if (done) PetscAssertPointer(done, 8);
8703:   MatCheckPreallocated(mat, 1);
8704:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8705:   else {
8706:     if (done) *done = PETSC_TRUE;
8707:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8708:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8709:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8710:   }
8711:   PetscFunctionReturn(PETSC_SUCCESS);
8712: }

8714: /*@
8715:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8717:   Collective

8719:   Input Parameters:
8720: + mat             - the matrix
8721: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8722: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8723:                     symmetrized
8724: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8725:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8726:                     always used.

8728:   Output Parameters:
8729: + n    - number of columns in the (possibly compressed) matrix
8730: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8731: . ja   - the row indices
8732: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8734:   Level: developer

8736: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8737: @*/
8738: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8739: {
8740:   PetscFunctionBegin;
8743:   PetscAssertPointer(n, 5);
8744:   if (ia) PetscAssertPointer(ia, 6);
8745:   if (ja) PetscAssertPointer(ja, 7);
8746:   PetscAssertPointer(done, 8);
8747:   MatCheckPreallocated(mat, 1);
8748:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8749:   else {
8750:     *done = PETSC_TRUE;
8751:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8752:   }
8753:   PetscFunctionReturn(PETSC_SUCCESS);
8754: }

8756: /*@
8757:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8759:   Collective

8761:   Input Parameters:
8762: + mat             - the matrix
8763: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8764: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8765: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8766:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8767:                     always used.
8768: . n               - size of (possibly compressed) matrix, or `NULL`
8769: . ia              - the row pointers, or `NULL`
8770: - ja              - the column indices, or `NULL`

8772:   Output Parameter:
8773: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8775:   Level: developer

8777:   Note:
8778:   This routine zeros out `n`, `ia`, and `ja` if they are provided. Use of `ia` or `ja` after `MatRestoreRowIJ()` is always invalid.

8780: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8781: @*/
8782: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8783: {
8784:   PetscFunctionBegin;
8787:   if (ia) PetscAssertPointer(ia, 6);
8788:   if (ja) PetscAssertPointer(ja, 7);
8789:   if (done) PetscAssertPointer(done, 8);
8790:   MatCheckPreallocated(mat, 1);

8792:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8793:   else {
8794:     if (done) *done = PETSC_TRUE;
8795:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8796:     if (n) *n = 0;
8797:     if (ia) *ia = NULL;
8798:     if (ja) *ja = NULL;
8799:   }
8800:   PetscFunctionReturn(PETSC_SUCCESS);
8801: }

8803: /*@
8804:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8806:   Collective

8808:   Input Parameters:
8809: + mat             - the matrix
8810: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8811: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8812: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8813:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8814:                     always used.

8816:   Output Parameters:
8817: + n    - size of (possibly compressed) matrix
8818: . ia   - the column pointers
8819: . ja   - the row indices
8820: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8822:   Level: developer

8824: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8825: @*/
8826: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8827: {
8828:   PetscFunctionBegin;
8831:   if (ia) PetscAssertPointer(ia, 6);
8832:   if (ja) PetscAssertPointer(ja, 7);
8833:   PetscAssertPointer(done, 8);
8834:   MatCheckPreallocated(mat, 1);

8836:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8837:   else {
8838:     *done = PETSC_TRUE;
8839:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8840:     if (n) *n = 0;
8841:     if (ia) *ia = NULL;
8842:     if (ja) *ja = NULL;
8843:   }
8844:   PetscFunctionReturn(PETSC_SUCCESS);
8845: }

8847: /*@
8848:   MatColoringPatch - Utility routine used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8849:   `MatGetColumnIJ()`.

8851:   Collective

8853:   Input Parameters:
8854: + mat        - the matrix
8855: . ncolors    - maximum color value
8856: . n          - number of entries in `colorarray`
8857: - colorarray - array indicating color for each column

8859:   Output Parameter:
8860: . iscoloring - coloring generated using `colorarray` information

8862:   Level: developer

8864: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8865: @*/
8866: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8867: {
8868:   PetscFunctionBegin;
8871:   PetscAssertPointer(colorarray, 4);
8872:   PetscAssertPointer(iscoloring, 5);
8873:   MatCheckPreallocated(mat, 1);

8875:   if (!mat->ops->coloringpatch) {
8876:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8877:   } else {
8878:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8879:   }
8880:   PetscFunctionReturn(PETSC_SUCCESS);
8881: }

8883: /*@
8884:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8886:   Logically Collective

8888:   Input Parameter:
8889: . mat - the factored matrix to be reset

8891:   Level: developer

8893:   Notes:
8894:   This routine should be used only with factored matrices formed by in-place
8895:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8896:   format). This option can save memory, for example, when solving nonlinear
8897:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8898:   ILU(0) preconditioner.

8900:   One can specify in-place ILU(0) factorization by calling
8901: .vb
8902:      PCType(pc,PCILU);
8903:      PCFactorSeUseInPlace(pc);
8904: .ve
8905:   or by using the options -pc_type ilu -pc_factor_in_place

8907:   In-place factorization ILU(0) can also be used as a local
8908:   solver for the blocks within the block Jacobi or additive Schwarz
8909:   methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8910:   for details on setting local solver options.

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

8916: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8917: @*/
8918: PetscErrorCode MatSetUnfactored(Mat mat)
8919: {
8920:   PetscFunctionBegin;
8923:   MatCheckPreallocated(mat, 1);
8924:   mat->factortype = MAT_FACTOR_NONE;
8925:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8926:   PetscUseTypeMethod(mat, setunfactored);
8927:   PetscFunctionReturn(PETSC_SUCCESS);
8928: }

8930: /*@
8931:   MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8932:   as the original matrix.

8934:   Collective

8936:   Input Parameters:
8937: + mat   - the original matrix
8938: . isrow - parallel `IS` containing the rows this process should obtain
8939: . 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.
8940: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8942:   Output Parameter:
8943: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)

8945:   Level: advanced

8947:   Notes:
8948:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8950:   Some matrix types place restrictions on the row and column indices, such
8951:   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;
8952:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8953:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.

8955:   The index sets may not have duplicate entries.

8957:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8958:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8959:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8960:   will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8961:   you are finished using it.

8963:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8964:   the input matrix.

8966:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8968:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8969:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8971:   Example usage:
8972:   Consider the following 8x8 matrix with 34 non-zero values, that is
8973:   assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8974:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8975:   as follows
8976: .vb
8977:             1  2  0  |  0  3  0  |  0  4
8978:     Proc0   0  5  6  |  7  0  0  |  8  0
8979:             9  0 10  | 11  0  0  | 12  0
8980:     -------------------------------------
8981:            13  0 14  | 15 16 17  |  0  0
8982:     Proc1   0 18  0  | 19 20 21  |  0  0
8983:             0  0  0  | 22 23  0  | 24  0
8984:     -------------------------------------
8985:     Proc2  25 26 27  |  0  0 28  | 29  0
8986:            30  0  0  | 31 32 33  |  0 34
8987: .ve

8989:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is

8991: .vb
8992:             2  0  |  0  3  0  |  0
8993:     Proc0   5  6  |  7  0  0  |  8
8994:     -------------------------------
8995:     Proc1  18  0  | 19 20 21  |  0
8996:     -------------------------------
8997:     Proc2  26 27  |  0  0 28  | 29
8998:             0  0  | 31 32 33  |  0
8999: .ve

9001: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
9002: @*/
9003: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
9004: {
9005:   PetscMPIInt size;
9006:   Mat        *local;
9007:   IS          iscoltmp;
9008:   PetscBool   flg;

9010:   PetscFunctionBegin;
9014:   PetscAssertPointer(newmat, 5);
9017:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9018:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
9019:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

9021:   MatCheckPreallocated(mat, 1);
9022:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

9024:   if (!iscol || isrow == iscol) {
9025:     PetscBool   stride;
9026:     PetscMPIInt grab = 0;
9027:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
9028:     if (stride) {
9029:       PetscInt first, step, n, rstart, rend;
9030:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
9031:       if (step == 1) {
9032:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
9033:         if (rstart == first) {
9034:           PetscCall(ISGetLocalSize(isrow, &n));
9035:           if (n == rend - rstart) grab = 1;
9036:         }
9037:       }
9038:     }
9039:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
9040:     if (grab) {
9041:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
9042:       if (cll == MAT_INITIAL_MATRIX) {
9043:         *newmat = mat;
9044:         PetscCall(PetscObjectReference((PetscObject)mat));
9045:       }
9046:       PetscFunctionReturn(PETSC_SUCCESS);
9047:     }
9048:   }

9050:   if (!iscol) {
9051:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
9052:   } else {
9053:     iscoltmp = iscol;
9054:   }

9056:   /* if original matrix is on just one process then use submatrix generated */
9057:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
9058:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
9059:     goto setproperties;
9060:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
9061:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
9062:     *newmat = *local;
9063:     PetscCall(PetscFree(local));
9064:     goto setproperties;
9065:   } else if (!mat->ops->createsubmatrix) {
9066:     /* Create a new matrix type that implements the operation using the full matrix */
9067:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9068:     switch (cll) {
9069:     case MAT_INITIAL_MATRIX:
9070:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9071:       break;
9072:     case MAT_REUSE_MATRIX:
9073:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9074:       break;
9075:     default:
9076:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9077:     }
9078:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9079:     goto setproperties;
9080:   }

9082:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9083:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9084:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9086: setproperties:
9087:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9088:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9089:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9090:   }
9091:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9092:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9093:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9094:   PetscFunctionReturn(PETSC_SUCCESS);
9095: }

9097: /*@
9098:   MatPropagateSymmetryOptions - Propagates symmetry properties set on a matrix to another matrix

9100:   Not Collective

9102:   Input Parameters:
9103: + A - the matrix we wish to propagate properties from
9104: - B - the matrix we wish to propagate properties to

9106:   Level: beginner

9108:   Note:
9109:   Propagates the properties associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9111: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9112: @*/
9113: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9114: {
9115:   PetscFunctionBegin;
9118:   B->symmetry_eternal            = A->symmetry_eternal;
9119:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9120:   B->symmetric                   = A->symmetric;
9121:   B->structurally_symmetric      = A->structurally_symmetric;
9122:   B->spd                         = A->spd;
9123:   B->hermitian                   = A->hermitian;
9124:   PetscFunctionReturn(PETSC_SUCCESS);
9125: }

9127: /*@
9128:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9129:   used during the assembly process to store values that belong to
9130:   other processes.

9132:   Not Collective

9134:   Input Parameters:
9135: + mat   - the matrix
9136: . size  - the initial size of the stash.
9137: - bsize - the initial size of the block-stash(if used).

9139:   Options Database Key:
9140: . -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

9142:   Level: intermediate

9144:   Notes:
9145:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9146:   the stash is used for values set with `MatSetValues()`

9148:   Run with the option `-info` and look for output of the form
9149:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9150:   to determine the appropriate value, MM, to use for size and
9151:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9152:   to determine the value, BMM to use for bsize

9154: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9155: @*/
9156: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9157: {
9158:   PetscFunctionBegin;
9161:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9162:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9163:   PetscFunctionReturn(PETSC_SUCCESS);
9164: }

9166: /*@
9167:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9168:   the matrix

9170:   Neighbor-wise Collective

9172:   Input Parameters:
9173: + A - the matrix
9174: . x - the vector to be multiplied by the interpolation operator
9175: - y - the vector to be added to the result

9177:   Output Parameter:
9178: . w - the resulting vector

9180:   Level: intermediate

9182:   Notes:
9183:   `w` may be the same vector as `y`.

9185:   This allows one to use either the restriction or interpolation (its transpose)
9186:   matrix to do the interpolation

9188: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9189: @*/
9190: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9191: {
9192:   PetscInt M, N, Ny;

9194:   PetscFunctionBegin;
9199:   PetscCall(MatGetSize(A, &M, &N));
9200:   PetscCall(VecGetSize(y, &Ny));
9201:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9202:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9203:   PetscFunctionReturn(PETSC_SUCCESS);
9204: }

9206: /*@
9207:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9208:   the matrix

9210:   Neighbor-wise Collective

9212:   Input Parameters:
9213: + A - the matrix
9214: - x - the vector to be interpolated

9216:   Output Parameter:
9217: . y - the resulting vector

9219:   Level: intermediate

9221:   Note:
9222:   This allows one to use either the restriction or interpolation (its transpose)
9223:   matrix to do the interpolation

9225: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9226: @*/
9227: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9228: {
9229:   PetscInt M, N, Ny;

9231:   PetscFunctionBegin;
9235:   PetscCall(MatGetSize(A, &M, &N));
9236:   PetscCall(VecGetSize(y, &Ny));
9237:   if (M == Ny) PetscCall(MatMult(A, x, y));
9238:   else PetscCall(MatMultTranspose(A, x, y));
9239:   PetscFunctionReturn(PETSC_SUCCESS);
9240: }

9242: /*@
9243:   MatRestrict - $y = A*x$ or $A^T*x$

9245:   Neighbor-wise Collective

9247:   Input Parameters:
9248: + A - the matrix
9249: - x - the vector to be restricted

9251:   Output Parameter:
9252: . y - the resulting vector

9254:   Level: intermediate

9256:   Note:
9257:   This allows one to use either the restriction or interpolation (its transpose)
9258:   matrix to do the restriction

9260: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9261: @*/
9262: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9263: {
9264:   PetscInt M, N, Nx;

9266:   PetscFunctionBegin;
9270:   PetscCall(MatGetSize(A, &M, &N));
9271:   PetscCall(VecGetSize(x, &Nx));
9272:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9273:   else PetscCall(MatMult(A, x, y));
9274:   PetscFunctionReturn(PETSC_SUCCESS);
9275: }

9277: /*@
9278:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

9280:   Neighbor-wise Collective

9282:   Input Parameters:
9283: + A - the matrix
9284: . x - the input dense matrix to be multiplied
9285: - w - the input dense matrix to be added to the result

9287:   Output Parameter:
9288: . y - the output dense matrix

9290:   Level: intermediate

9292:   Note:
9293:   This allows one to use either the restriction or interpolation (its transpose)
9294:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9295:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9297: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9298: @*/
9299: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9300: {
9301:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9302:   PetscBool trans = PETSC_TRUE;
9303:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9305:   PetscFunctionBegin;
9311:   PetscCall(MatGetSize(A, &M, &N));
9312:   PetscCall(MatGetSize(x, &Mx, &Nx));
9313:   if (N == Mx) trans = PETSC_FALSE;
9314:   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);
9315:   Mo = trans ? N : M;
9316:   if (*y) {
9317:     PetscCall(MatGetSize(*y, &My, &Ny));
9318:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9319:     else {
9320:       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);
9321:       PetscCall(MatDestroy(y));
9322:     }
9323:   }

9325:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9326:     PetscBool flg;

9328:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9329:     if (w) {
9330:       PetscInt My, Ny, Mw, Nw;

9332:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9333:       PetscCall(MatGetSize(*y, &My, &Ny));
9334:       PetscCall(MatGetSize(w, &Mw, &Nw));
9335:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9336:     }
9337:     if (!w) {
9338:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9339:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9340:       PetscCall(PetscObjectDereference((PetscObject)w));
9341:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9342:   }
9343:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9344:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9345:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9346:   PetscFunctionReturn(PETSC_SUCCESS);
9347: }

9349: /*@
9350:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9352:   Neighbor-wise Collective

9354:   Input Parameters:
9355: + A - the matrix
9356: - x - the input dense matrix

9358:   Output Parameter:
9359: . y - the output dense matrix

9361:   Level: intermediate

9363:   Note:
9364:   This allows one to use either the restriction or interpolation (its transpose)
9365:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9366:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9368: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9369: @*/
9370: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9371: {
9372:   PetscFunctionBegin;
9373:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9374:   PetscFunctionReturn(PETSC_SUCCESS);
9375: }

9377: /*@
9378:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9380:   Neighbor-wise Collective

9382:   Input Parameters:
9383: + A - the matrix
9384: - x - the input dense matrix

9386:   Output Parameter:
9387: . y - the output dense matrix

9389:   Level: intermediate

9391:   Note:
9392:   This allows one to use either the restriction or interpolation (its transpose)
9393:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9394:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9396: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9397: @*/
9398: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9399: {
9400:   PetscFunctionBegin;
9401:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9402:   PetscFunctionReturn(PETSC_SUCCESS);
9403: }

9405: /*@
9406:   MatGetNullSpace - retrieves the null space of a matrix that was provided with `MatSetNullSpace()`

9408:   Logically Collective

9410:   Input Parameters:
9411: + mat    - the matrix
9412: - nullsp - the null space object

9414:   Level: developer

9416: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9417: @*/
9418: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9419: {
9420:   PetscFunctionBegin;
9422:   PetscAssertPointer(nullsp, 2);
9423:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9424:   PetscFunctionReturn(PETSC_SUCCESS);
9425: }

9427: /*@
9428:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices that were supplied with `MatSetNullSpace()`,
9429:   `MatSetTransposeNullSpace()`, and `MatSetNearNullSpace()`

9431:   Logically Collective

9433:   Input Parameters:
9434: + n   - the number of matrices
9435: - mat - the array of matrices

9437:   Output Parameters:
9438: . nullsp - an array of null spaces, `NULL` will be inserted for each matrix that does not have a null space, length 3 * `n`

9440:   Level: developer

9442:   Note:
9443:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9445: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9446:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`, `MatNullSpace`
9447: @*/
9448: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9449: {
9450:   PetscFunctionBegin;
9451:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9452:   PetscAssertPointer(mat, 2);
9453:   PetscAssertPointer(nullsp, 3);

9455:   PetscCall(PetscCalloc1(3 * n, nullsp));
9456:   for (PetscInt i = 0; i < n; i++) {
9458:     (*nullsp)[i] = mat[i]->nullsp;
9459:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9460:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9461:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9462:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9463:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9464:   }
9465:   PetscFunctionReturn(PETSC_SUCCESS);
9466: }

9468: /*@
9469:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9471:   Logically Collective

9473:   Input Parameters:
9474: + n      - the number of matrices
9475: . mat    - the array of matrices
9476: - nullsp - an array of null spaces, of length  3 * `n`

9478:   Level: developer

9480:   Notes:
9481:   Call `MatGetNullSpaces()` to create `nullsp`.

9483:   Frees `nullsp`.

9485:   Developer Note:
9486:   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.
9487:   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
9488:   should have simply been called `MatSetNullSpaces()`

9490: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9491:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`, `MatNullSpace`
9492: @*/
9493: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9494: {
9495:   PetscFunctionBegin;
9496:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9497:   PetscAssertPointer(mat, 2);
9498:   PetscAssertPointer(nullsp, 3);
9499:   PetscAssertPointer(*nullsp, 3);

9501:   for (PetscInt i = 0; i < n; i++) {
9503:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9504:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9505:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9506:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9507:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9508:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9509:   }
9510:   PetscCall(PetscFree(*nullsp));
9511:   PetscFunctionReturn(PETSC_SUCCESS);
9512: }

9514: /*@
9515:   MatSetNullSpace - attaches a null space to a matrix.

9517:   Logically Collective

9519:   Input Parameters:
9520: + mat    - the matrix
9521: - nullsp - the null space object

9523:   Level: advanced

9525:   Notes:
9526:   This null space is used by the `KSP` linear solvers to solve singular systems.

9528:   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`

9530:   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
9531:   to zero but the linear system will still be solved in a least squares sense.

9533:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9534:   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)$.
9535:   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
9536:   $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
9537:   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)$.
9538:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9540:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9541:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9542:   routine also automatically calls `MatSetTransposeNullSpace()`.

9544:   The user should call `MatNullSpaceDestroy()`.

9546: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9547:           `KSPSetPCSide()`, `MatNullSpace`
9548: @*/
9549: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9550: {
9551:   PetscFunctionBegin;
9554:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9555:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9556:   mat->nullsp = nullsp;
9557:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9558:   PetscFunctionReturn(PETSC_SUCCESS);
9559: }

9561: /*@
9562:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix that was set with `MatSetTransposeNullSpace()`

9564:   Logically Collective

9566:   Input Parameters:
9567: + mat    - the matrix
9568: - nullsp - the null space object

9570:   Level: developer

9572: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9573: @*/
9574: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9575: {
9576:   PetscFunctionBegin;
9579:   PetscAssertPointer(nullsp, 2);
9580:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9581:   PetscFunctionReturn(PETSC_SUCCESS);
9582: }

9584: /*@
9585:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9587:   Logically Collective

9589:   Input Parameters:
9590: + mat    - the matrix
9591: - nullsp - the null space object

9593:   Level: advanced

9595:   Notes:
9596:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9598:   See `MatSetNullSpace()`

9600: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9601: @*/
9602: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9603: {
9604:   PetscFunctionBegin;
9607:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9608:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9609:   mat->transnullsp = nullsp;
9610:   PetscFunctionReturn(PETSC_SUCCESS);
9611: }

9613: /*@
9614:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9615:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9617:   Logically Collective

9619:   Input Parameters:
9620: + mat    - the matrix
9621: - nullsp - the null space object

9623:   Level: advanced

9625:   Notes:
9626:   Overwrites any previous near null space that may have been attached

9628:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9630: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9631: @*/
9632: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9633: {
9634:   PetscFunctionBegin;
9638:   MatCheckPreallocated(mat, 1);
9639:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9640:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9641:   mat->nearnullsp = nullsp;
9642:   PetscFunctionReturn(PETSC_SUCCESS);
9643: }

9645: /*@
9646:   MatGetNearNullSpace - Get null space from a matrix that was attached with `MatSetNearNullSpace()`

9648:   Not Collective

9650:   Input Parameter:
9651: . mat - the matrix

9653:   Output Parameter:
9654: . nullsp - the null space object, `NULL` if not set

9656:   Level: advanced

9658: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9659: @*/
9660: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9661: {
9662:   PetscFunctionBegin;
9665:   PetscAssertPointer(nullsp, 2);
9666:   MatCheckPreallocated(mat, 1);
9667:   *nullsp = mat->nearnullsp;
9668:   PetscFunctionReturn(PETSC_SUCCESS);
9669: }

9671: /*@
9672:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9674:   Collective

9676:   Input Parameters:
9677: + mat  - the matrix
9678: . row  - row/column permutation
9679: - info - information on desired factorization process

9681:   Level: developer

9683:   Notes:
9684:   Probably really in-place only when level of fill is zero, otherwise allocates
9685:   new space to store factored matrix and deletes previous memory.

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

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

9694: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9695: @*/
9696: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9697: {
9698:   PetscFunctionBegin;
9702:   PetscAssertPointer(info, 3);
9703:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9704:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9705:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9706:   MatCheckPreallocated(mat, 1);
9707:   PetscUseTypeMethod(mat, iccfactor, row, info);
9708:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9709:   PetscFunctionReturn(PETSC_SUCCESS);
9710: }

9712: /*@
9713:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9714:   ghosted ones.

9716:   Not Collective

9718:   Input Parameters:
9719: + mat  - the matrix
9720: - diag - the diagonal values, including ghost ones

9722:   Level: developer

9724:   Notes:
9725:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9727:   `diag` is a sequential vector that has a length which is the same as the local (ghosted) length of the vector associated with
9728:   the matrix's `ISLocalToGlobalMapping` set with `MatSetLocalToGlobalMapping()`.

9730:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`.

9732: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`, `MatSetLocalToGlobalMapping()`, `ISLocalToGlobalMapping`
9733: @*/
9734: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9735: {
9736:   PetscMPIInt size;

9738:   PetscFunctionBegin;

9743:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9744:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9745:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9746:   if (size == 1) {
9747:     PetscInt n, m;
9748:     PetscCall(VecGetSize(diag, &n));
9749:     PetscCall(MatGetSize(mat, NULL, &m));
9750:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9751:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9752:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9753:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9754:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9755:   PetscFunctionReturn(PETSC_SUCCESS);
9756: }

9758: /*@
9759:   MatGetInertia - Gets the inertia from a factored matrix

9761:   Collective

9763:   Input Parameter:
9764: . mat - the matrix

9766:   Output Parameters:
9767: + nneg  - number of negative eigenvalues
9768: . nzero - number of zero eigenvalues
9769: - npos  - number of positive eigenvalues

9771:   Level: advanced

9773:   Note:
9774:   Matrix must have been factored by `MatCholeskyFactor()`

9776: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9777: @*/
9778: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9779: {
9780:   PetscFunctionBegin;
9783:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9784:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9785:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9786:   PetscFunctionReturn(PETSC_SUCCESS);
9787: }

9789: /*@
9790:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9792:   Neighbor-wise Collective

9794:   Input Parameters:
9795: + mat - the factored matrix obtained with `MatGetFactor()`
9796: - b   - the right-hand-side vectors

9798:   Output Parameter:
9799: . x - the result vectors

9801:   Level: developer

9803:   Note:
9804:   The vectors `b` and `x` cannot be the same. I.e., one cannot
9805:   call `MatSolves`(A,x,x).

9807: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatGetFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9808: @*/
9809: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9810: {
9811:   PetscFunctionBegin;
9814:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9815:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9816:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9818:   MatCheckPreallocated(mat, 1);
9819:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9820:   PetscUseTypeMethod(mat, solves, b, x);
9821:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9822:   PetscFunctionReturn(PETSC_SUCCESS);
9823: }

9825: /*@
9826:   MatIsSymmetric - Test whether a matrix is symmetric

9828:   Collective

9830:   Input Parameters:
9831: + A   - the matrix to test
9832: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9834:   Output Parameter:
9835: . flg - the result

9837:   Level: intermediate

9839:   Notes:
9840:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9842:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9844:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9845:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9846:   have been set then `MatIsSymmetric()` does not need to perform any computations and returns immediately with the result.

9848: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9849:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9850: @*/
9851: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9852: {
9853:   PetscFunctionBegin;
9855:   PetscAssertPointer(flg, 3);
9856:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9857:   else {
9858:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9859:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9860:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9861:   }
9862:   PetscFunctionReturn(PETSC_SUCCESS);
9863: }

9865: /*@
9866:   MatIsHermitian - Test whether a matrix is Hermitian

9868:   Collective

9870:   Input Parameters:
9871: + A   - the matrix to test
9872: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9874:   Output Parameter:
9875: . flg - the result

9877:   Level: intermediate

9879:   Notes:
9880:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9882:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9884:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9885:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9886:   have been set then `MatIsHermitian()` does not need to perform any computations and returns immediately with the result.

9888: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9889:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9890: @*/
9891: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9892: {
9893:   PetscFunctionBegin;
9895:   PetscAssertPointer(flg, 3);
9896:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9897:   else {
9898:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9899:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9900:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9901:   }
9902:   PetscFunctionReturn(PETSC_SUCCESS);
9903: }

9905: /*@
9906:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9908:   Not Collective

9910:   Input Parameter:
9911: . A - the matrix to check

9913:   Output Parameters:
9914: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9915: - flg - the result (only valid if set is `PETSC_TRUE`)

9917:   Level: advanced

9919:   Notes:
9920:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9921:   if you want it explicitly checked

9923:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9924:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9926: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9927: @*/
9928: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9929: {
9930:   PetscFunctionBegin;
9932:   PetscAssertPointer(set, 2);
9933:   PetscAssertPointer(flg, 3);
9934:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9935:     *set = PETSC_TRUE;
9936:     *flg = PetscBool3ToBool(A->symmetric);
9937:   } else *set = PETSC_FALSE;
9938:   PetscFunctionReturn(PETSC_SUCCESS);
9939: }

9941: /*@
9942:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9944:   Not Collective

9946:   Input Parameter:
9947: . A - the matrix to check

9949:   Output Parameters:
9950: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9951: - flg - the result (only valid if set is `PETSC_TRUE`)

9953:   Level: advanced

9955:   Notes:
9956:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9958:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9959:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9961: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9962: @*/
9963: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9964: {
9965:   PetscFunctionBegin;
9967:   PetscAssertPointer(set, 2);
9968:   PetscAssertPointer(flg, 3);
9969:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9970:     *set = PETSC_TRUE;
9971:     *flg = PetscBool3ToBool(A->spd);
9972:   } else *set = PETSC_FALSE;
9973:   PetscFunctionReturn(PETSC_SUCCESS);
9974: }

9976: /*@
9977:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9979:   Not Collective

9981:   Input Parameter:
9982: . A - the matrix to check

9984:   Output Parameters:
9985: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9986: - flg - the result (only valid if set is `PETSC_TRUE`)

9988:   Level: advanced

9990:   Notes:
9991:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9992:   if you want it explicitly checked

9994:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9995:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9997: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9998: @*/
9999: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
10000: {
10001:   PetscFunctionBegin;
10003:   PetscAssertPointer(set, 2);
10004:   PetscAssertPointer(flg, 3);
10005:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
10006:     *set = PETSC_TRUE;
10007:     *flg = PetscBool3ToBool(A->hermitian);
10008:   } else *set = PETSC_FALSE;
10009:   PetscFunctionReturn(PETSC_SUCCESS);
10010: }

10012: /*@
10013:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

10015:   Collective

10017:   Input Parameter:
10018: . A - the matrix to test

10020:   Output Parameter:
10021: . flg - the result

10023:   Level: intermediate

10025:   Notes:
10026:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

10028:   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
10029:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
10030:   have been set then `MatIsStructurallySymmetric()` does not need to perform any computations and returns immediately with the result.

10032: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
10033: @*/
10034: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
10035: {
10036:   PetscFunctionBegin;
10038:   PetscAssertPointer(flg, 2);
10039:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
10040:   else {
10041:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
10042:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
10043:   }
10044:   PetscFunctionReturn(PETSC_SUCCESS);
10045: }

10047: /*@
10048:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

10050:   Not Collective

10052:   Input Parameter:
10053: . A - the matrix to check

10055:   Output Parameters:
10056: + set - `PETSC_TRUE` if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
10057: - flg - the result (only valid if set is `PETSC_TRUE`)

10059:   Level: advanced

10061:   Notes:
10062:   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
10063:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10065:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

10067: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
10068: @*/
10069: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
10070: {
10071:   PetscFunctionBegin;
10073:   PetscAssertPointer(set, 2);
10074:   PetscAssertPointer(flg, 3);
10075:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
10076:     *set = PETSC_TRUE;
10077:     *flg = PetscBool3ToBool(A->structurally_symmetric);
10078:   } else *set = PETSC_FALSE;
10079:   PetscFunctionReturn(PETSC_SUCCESS);
10080: }

10082: /*@
10083:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10084:   to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10086:   Not Collective

10088:   Input Parameter:
10089: . mat - the matrix

10091:   Output Parameters:
10092: + nstash    - the size of the stash
10093: . reallocs  - the number of additional mallocs incurred.
10094: . bnstash   - the size of the block stash
10095: - breallocs - the number of additional mallocs incurred.in the block stash

10097:   Level: advanced

10099: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10100: @*/
10101: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10102: {
10103:   PetscFunctionBegin;
10104:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10105:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10106:   PetscFunctionReturn(PETSC_SUCCESS);
10107: }

10109: /*@
10110:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10111:   parallel layout, `PetscLayout` for rows and columns

10113:   Collective

10115:   Input Parameter:
10116: . mat - the matrix

10118:   Output Parameters:
10119: + right - (optional) vector that the matrix can be multiplied against
10120: - left  - (optional) vector that the matrix vector product can be stored in

10122:   Options Database Key:
10123: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10125:   Level: advanced

10127:   Notes:
10128:   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()`.

10130:   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`.

10132:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10134:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10135:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10137: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10138: @*/
10139: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10140: {
10141:   PetscFunctionBegin;
10144:   if (mat->ops->getvecs) {
10145:     PetscUseTypeMethod(mat, getvecs, right, left);
10146:   } else {
10147:     if (right) {
10148:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10149:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10150:       PetscCall(VecSetType(*right, mat->defaultvectype));
10151: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10152:       if (mat->boundtocpu && mat->bindingpropagates) {
10153:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10154:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10155:       }
10156: #endif
10157:     }
10158:     if (left) {
10159:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10160:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10161:       PetscCall(VecSetType(*left, mat->defaultvectype));
10162: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10163:       if (mat->boundtocpu && mat->bindingpropagates) {
10164:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10165:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10166:       }
10167: #endif
10168:     }
10169:   }
10170:   PetscFunctionReturn(PETSC_SUCCESS);
10171: }

10173: /*@
10174:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10175:   with default values.

10177:   Not Collective

10179:   Input Parameter:
10180: . info - the `MatFactorInfo` data structure

10182:   Level: developer

10184:   Notes:
10185:   The solvers are generally used through the `KSP` and `PC` objects, for example
10186:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10188:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10190: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10191: @*/
10192: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10193: {
10194:   PetscFunctionBegin;
10195:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10196:   PetscFunctionReturn(PETSC_SUCCESS);
10197: }

10199: /*@
10200:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10202:   Collective

10204:   Input Parameters:
10205: + mat - the factored matrix
10206: - is  - the index set defining the Schur indices (0-based)

10208:   Level: advanced

10210:   Notes:
10211:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10213:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10215:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10217: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10218:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10219: @*/
10220: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10221: {
10222:   PetscErrorCode (*f)(Mat, IS);

10224:   PetscFunctionBegin;
10229:   PetscCheckSameComm(mat, 1, is, 2);
10230:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10231:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10232:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10233:   PetscCall((*f)(mat, is));
10234:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10235:   PetscFunctionReturn(PETSC_SUCCESS);
10236: }

10238: /*@
10239:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10241:   Logically Collective

10243:   Input Parameters:
10244: + F      - the factored matrix obtained by calling `MatGetFactor()`
10245: . S      - location where to return the Schur complement, can be `NULL`
10246: - status - the status of the Schur complement matrix, can be `NULL`

10248:   Level: advanced

10250:   Notes:
10251:   You must call `MatFactorSetSchurIS()` before calling this routine.

10253:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10255:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10256:   The caller must destroy the object when it is no longer needed.
10257:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10259:   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)

10261:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10263:   Developer Note:
10264:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10265:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10267: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10268: @*/
10269: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10270: {
10271:   PetscFunctionBegin;
10273:   if (S) PetscAssertPointer(S, 2);
10274:   if (status) PetscAssertPointer(status, 3);
10275:   if (S) {
10276:     PetscErrorCode (*f)(Mat, Mat *);

10278:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10279:     if (f) PetscCall((*f)(F, S));
10280:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10281:   }
10282:   if (status) *status = F->schur_status;
10283:   PetscFunctionReturn(PETSC_SUCCESS);
10284: }

10286: /*@
10287:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10289:   Logically Collective

10291:   Input Parameters:
10292: + F      - the factored matrix obtained by calling `MatGetFactor()`
10293: . S      - location where to return the Schur complement, can be `NULL`
10294: - status - the status of the Schur complement matrix, can be `NULL`

10296:   Level: advanced

10298:   Notes:
10299:   You must call `MatFactorSetSchurIS()` before calling this routine.

10301:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10303:   The routine returns a the Schur Complement stored within the data structures of the solver.

10305:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10307:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10309:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10311:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10313: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10314: @*/
10315: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10316: {
10317:   PetscFunctionBegin;
10319:   if (S) {
10320:     PetscAssertPointer(S, 2);
10321:     *S = F->schur;
10322:   }
10323:   if (status) {
10324:     PetscAssertPointer(status, 3);
10325:     *status = F->schur_status;
10326:   }
10327:   PetscFunctionReturn(PETSC_SUCCESS);
10328: }

10330: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10331: {
10332:   Mat S = F->schur;

10334:   PetscFunctionBegin;
10335:   switch (F->schur_status) {
10336:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10337:   case MAT_FACTOR_SCHUR_INVERTED:
10338:     if (S) {
10339:       S->ops->solve             = NULL;
10340:       S->ops->matsolve          = NULL;
10341:       S->ops->solvetranspose    = NULL;
10342:       S->ops->matsolvetranspose = NULL;
10343:       S->ops->solveadd          = NULL;
10344:       S->ops->solvetransposeadd = NULL;
10345:       S->factortype             = MAT_FACTOR_NONE;
10346:       PetscCall(PetscFree(S->solvertype));
10347:     }
10348:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10349:     break;
10350:   default:
10351:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10352:   }
10353:   PetscFunctionReturn(PETSC_SUCCESS);
10354: }

10356: /*@
10357:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10359:   Logically Collective

10361:   Input Parameters:
10362: + F      - the factored matrix obtained by calling `MatGetFactor()`
10363: . S      - location where the Schur complement is stored
10364: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10366:   Level: advanced

10368: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10369: @*/
10370: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10371: {
10372:   PetscFunctionBegin;
10374:   if (S) {
10376:     *S = NULL;
10377:   }
10378:   F->schur_status = status;
10379:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10380:   PetscFunctionReturn(PETSC_SUCCESS);
10381: }

10383: /*@
10384:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10386:   Logically Collective

10388:   Input Parameters:
10389: + F   - the factored matrix obtained by calling `MatGetFactor()`
10390: . rhs - location where the right-hand side of the Schur complement system is stored
10391: - sol - location where the solution of the Schur complement system has to be returned

10393:   Level: advanced

10395:   Notes:
10396:   The sizes of the vectors should match the size of the Schur complement

10398:   Must be called after `MatFactorSetSchurIS()`

10400: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10401: @*/
10402: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10403: {
10404:   PetscFunctionBegin;
10411:   PetscCheckSameComm(F, 1, rhs, 2);
10412:   PetscCheckSameComm(F, 1, sol, 3);
10413:   PetscCall(MatFactorFactorizeSchurComplement(F));
10414:   switch (F->schur_status) {
10415:   case MAT_FACTOR_SCHUR_FACTORED:
10416:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10417:     break;
10418:   case MAT_FACTOR_SCHUR_INVERTED:
10419:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10420:     break;
10421:   default:
10422:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10423:   }
10424:   PetscFunctionReturn(PETSC_SUCCESS);
10425: }

10427: /*@
10428:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10430:   Logically Collective

10432:   Input Parameters:
10433: + F   - the factored matrix obtained by calling `MatGetFactor()`
10434: . rhs - location where the right-hand side of the Schur complement system is stored
10435: - sol - location where the solution of the Schur complement system has to be returned

10437:   Level: advanced

10439:   Notes:
10440:   The sizes of the vectors should match the size of the Schur complement

10442:   Must be called after `MatFactorSetSchurIS()`

10444: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10445: @*/
10446: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10447: {
10448:   PetscFunctionBegin;
10455:   PetscCheckSameComm(F, 1, rhs, 2);
10456:   PetscCheckSameComm(F, 1, sol, 3);
10457:   PetscCall(MatFactorFactorizeSchurComplement(F));
10458:   switch (F->schur_status) {
10459:   case MAT_FACTOR_SCHUR_FACTORED:
10460:     PetscCall(MatSolve(F->schur, rhs, sol));
10461:     break;
10462:   case MAT_FACTOR_SCHUR_INVERTED:
10463:     PetscCall(MatMult(F->schur, rhs, sol));
10464:     break;
10465:   default:
10466:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10467:   }
10468:   PetscFunctionReturn(PETSC_SUCCESS);
10469: }

10471: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10472: #if PetscDefined(HAVE_CUDA)
10473: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10474: #endif

10476: /* Schur status updated in the interface */
10477: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10478: {
10479:   Mat S = F->schur;

10481:   PetscFunctionBegin;
10482:   if (S) {
10483:     PetscMPIInt size;
10484:     PetscBool   isdense, isdensecuda;

10486:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10487:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10488:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10489:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10490:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10491:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10492:     if (isdense) {
10493:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10494:     } else if (isdensecuda) {
10495: #if PetscDefined(HAVE_CUDA)
10496:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10497: #endif
10498:     }
10499:     // HIP??????????????
10500:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10501:   }
10502:   PetscFunctionReturn(PETSC_SUCCESS);
10503: }

10505: /*@
10506:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10508:   Logically Collective

10510:   Input Parameter:
10511: . F - the factored matrix obtained by calling `MatGetFactor()`

10513:   Level: advanced

10515:   Notes:
10516:   Must be called after `MatFactorSetSchurIS()`.

10518:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10520: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10521: @*/
10522: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10523: {
10524:   PetscFunctionBegin;
10527:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10528:   PetscCall(MatFactorFactorizeSchurComplement(F));
10529:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10530:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10531:   PetscFunctionReturn(PETSC_SUCCESS);
10532: }

10534: /*@
10535:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10537:   Logically Collective

10539:   Input Parameter:
10540: . F - the factored matrix obtained by calling `MatGetFactor()`

10542:   Level: advanced

10544:   Note:
10545:   Must be called after `MatFactorSetSchurIS()`

10547: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10548: @*/
10549: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10550: {
10551:   MatFactorInfo info;

10553:   PetscFunctionBegin;
10556:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10557:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10558:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10559:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10560:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10561:   } else {
10562:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10563:   }
10564:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10565:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10566:   PetscFunctionReturn(PETSC_SUCCESS);
10567: }

10569: /*@
10570:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10572:   Neighbor-wise Collective

10574:   Input Parameters:
10575: + A     - the matrix
10576: . P     - the projection matrix
10577: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10578: - 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
10579:           if the result is a dense matrix this is irrelevant

10581:   Output Parameter:
10582: . C - the product matrix

10584:   Level: intermediate

10586:   Notes:
10587:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10589:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10590:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10592:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10594:   Developer Note:
10595:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10597: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10598: @*/
10599: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10600: {
10601:   PetscFunctionBegin;
10602:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10603:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10605:   if (scall == MAT_INITIAL_MATRIX) {
10606:     PetscCall(MatProductCreate(A, P, NULL, C));
10607:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10608:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10609:     PetscCall(MatProductSetFill(*C, fill));

10611:     (*C)->product->api_user = PETSC_TRUE;
10612:     PetscCall(MatProductSetFromOptions(*C));
10613:     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);
10614:     PetscCall(MatProductSymbolic(*C));
10615:   } else { /* scall == MAT_REUSE_MATRIX */
10616:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10617:   }

10619:   PetscCall(MatProductNumeric(*C));
10620:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10621:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10622:     (*C)->spd = A->spd;
10623:   }
10624:   PetscFunctionReturn(PETSC_SUCCESS);
10625: }

10627: /*@
10628:   MatRARt - Creates the matrix product $C = R * A * R^T$

10630:   Neighbor-wise Collective

10632:   Input Parameters:
10633: + A     - the matrix
10634: . R     - the projection matrix
10635: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10636: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10637:           if the result is a dense matrix this is irrelevant

10639:   Output Parameter:
10640: . C - the product matrix

10642:   Level: intermediate

10644:   Notes:
10645:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10647:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10648:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10650:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10651:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10652:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10653:   We recommend using `MatPtAP()` when possible.

10655:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10657: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10658: @*/
10659: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10660: {
10661:   PetscFunctionBegin;
10662:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10663:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10665:   if (scall == MAT_INITIAL_MATRIX) {
10666:     PetscCall(MatProductCreate(A, R, NULL, C));
10667:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10668:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10669:     PetscCall(MatProductSetFill(*C, fill));

10671:     (*C)->product->api_user = PETSC_TRUE;
10672:     PetscCall(MatProductSetFromOptions(*C));
10673:     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);
10674:     PetscCall(MatProductSymbolic(*C));
10675:   } else { /* scall == MAT_REUSE_MATRIX */
10676:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10677:   }

10679:   PetscCall(MatProductNumeric(*C));
10680:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10681:   PetscFunctionReturn(PETSC_SUCCESS);
10682: }

10684: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10685: {
10686:   PetscBool flg = PETSC_TRUE;

10688:   PetscFunctionBegin;
10689:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10690:   if (scall == MAT_INITIAL_MATRIX) {
10691:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10692:     PetscCall(MatProductCreate(A, B, NULL, C));
10693:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10694:     PetscCall(MatProductSetFill(*C, fill));
10695:   } else { /* scall == MAT_REUSE_MATRIX */
10696:     Mat_Product *product = (*C)->product;

10698:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10699:     if (flg && product && product->type != ptype) {
10700:       PetscCall(MatProductClear(*C));
10701:       product = NULL;
10702:     }
10703:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10704:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10705:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10706:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10707:       product        = (*C)->product;
10708:       product->fill  = fill;
10709:       product->clear = PETSC_TRUE;
10710:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10711:       flg = PETSC_FALSE;
10712:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10713:     }
10714:   }
10715:   if (flg) {
10716:     (*C)->product->api_user = PETSC_TRUE;
10717:     PetscCall(MatProductSetType(*C, ptype));
10718:     PetscCall(MatProductSetFromOptions(*C));
10719:     PetscCall(MatProductSymbolic(*C));
10720:   }
10721:   PetscCall(MatProductNumeric(*C));
10722:   PetscFunctionReturn(PETSC_SUCCESS);
10723: }

10725: /*@
10726:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10728:   Neighbor-wise Collective

10730:   Input Parameters:
10731: + A     - the left matrix
10732: . B     - the right matrix
10733: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10734: - 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
10735:           if the result is a dense matrix this is irrelevant

10737:   Output Parameter:
10738: . C - the product matrix

10740:   Notes:
10741:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10743:   `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
10744:   call to this function with `MAT_INITIAL_MATRIX`.

10746:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10748:   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`,
10749:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10751:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10753:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10754:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10756:   Example of Usage:
10757: .vb
10758:      MatProductCreate(A,B,NULL,&C);
10759:      MatProductSetType(C,MATPRODUCT_AB);
10760:      MatProductSymbolic(C);
10761:      MatProductNumeric(C); // compute C=A * B
10762:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10763:      MatProductNumeric(C);
10764:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10765:      MatProductNumeric(C);
10766: .ve

10768:   Level: intermediate

10770: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10771: @*/
10772: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10773: {
10774:   PetscFunctionBegin;
10775:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10776:   PetscFunctionReturn(PETSC_SUCCESS);
10777: }

10779: /*@
10780:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10782:   Neighbor-wise Collective

10784:   Input Parameters:
10785: + A     - the left matrix
10786: . B     - the right matrix
10787: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10788: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10790:   Output Parameter:
10791: . C - the product matrix

10793:   Options Database Key:
10794: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10795:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10796:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10798:   Level: intermediate

10800:   Notes:
10801:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10803:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10805:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10806:   actually needed.

10808:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10809:   and for pairs of `MATMPIDENSE` matrices.

10811:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10812:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10814:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10816: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10817: @*/
10818: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10819: {
10820:   PetscFunctionBegin;
10821:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10822:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10823:   PetscFunctionReturn(PETSC_SUCCESS);
10824: }

10826: /*@
10827:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10829:   Neighbor-wise Collective

10831:   Input Parameters:
10832: + A     - the left matrix
10833: . B     - the right matrix
10834: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10835: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10837:   Output Parameter:
10838: . C - the product matrix

10840:   Level: intermediate

10842:   Notes:
10843:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10845:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10847:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10848:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10850:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10851:   actually needed.

10853:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10854:   which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.

10856:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10858: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10859: @*/
10860: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10861: {
10862:   PetscFunctionBegin;
10863:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10864:   PetscFunctionReturn(PETSC_SUCCESS);
10865: }

10867: /*@
10868:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10870:   Neighbor-wise Collective

10872:   Input Parameters:
10873: + A     - the left matrix
10874: . B     - the middle matrix
10875: . C     - the right matrix
10876: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10877: - 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
10878:           if the result is a dense matrix this is irrelevant

10880:   Output Parameter:
10881: . D - the product matrix

10883:   Level: intermediate

10885:   Notes:
10886:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10888:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10890:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10891:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10893:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10894:   actually needed.

10896:   If you have many matrices with the same non-zero structure to multiply, you
10897:   should use `MAT_REUSE_MATRIX` in all calls but the first

10899:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10901: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10902: @*/
10903: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10904: {
10905:   PetscFunctionBegin;
10906:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10907:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10909:   if (scall == MAT_INITIAL_MATRIX) {
10910:     PetscCall(MatProductCreate(A, B, C, D));
10911:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10912:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10913:     PetscCall(MatProductSetFill(*D, fill));

10915:     (*D)->product->api_user = PETSC_TRUE;
10916:     PetscCall(MatProductSetFromOptions(*D));
10917:     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,
10918:                ((PetscObject)C)->type_name);
10919:     PetscCall(MatProductSymbolic(*D));
10920:   } else { /* user may change input matrices when REUSE */
10921:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10922:   }
10923:   PetscCall(MatProductNumeric(*D));
10924:   PetscFunctionReturn(PETSC_SUCCESS);
10925: }

10927: /*@
10928:   MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.

10930:   Collective

10932:   Input Parameters:
10933: + mat      - the matrix
10934: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10935: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10936: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10938:   Output Parameter:
10939: . matredundant - redundant matrix

10941:   Level: advanced

10943:   Notes:
10944:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10945:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10947:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10948:   calling it.

10950:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10952: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10953: @*/
10954: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10955: {
10956:   MPI_Comm       comm;
10957:   PetscMPIInt    size;
10958:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10959:   Mat_Redundant *redund     = NULL;
10960:   PetscSubcomm   psubcomm   = NULL;
10961:   MPI_Comm       subcomm_in = subcomm;
10962:   Mat           *matseq;
10963:   IS             isrow, iscol;
10964:   PetscBool      newsubcomm = PETSC_FALSE;

10966:   PetscFunctionBegin;
10968:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10969:     PetscAssertPointer(*matredundant, 5);
10971:   }

10973:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10974:   if (size == 1 || nsubcomm == 1) {
10975:     if (reuse == MAT_INITIAL_MATRIX) {
10976:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10977:     } else {
10978:       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");
10979:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10980:     }
10981:     PetscFunctionReturn(PETSC_SUCCESS);
10982:   }

10984:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10985:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10986:   MatCheckPreallocated(mat, 1);

10988:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10989:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10990:     /* create psubcomm, then get subcomm */
10991:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10992:     PetscCallMPI(MPI_Comm_size(comm, &size));
10993:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10995:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10996:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10997:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10998:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10999:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
11000:     newsubcomm = PETSC_TRUE;
11001:     PetscCall(PetscSubcommDestroy(&psubcomm));
11002:   }

11004:   /* get isrow, iscol and a local sequential matrix matseq[0] */
11005:   if (reuse == MAT_INITIAL_MATRIX) {
11006:     mloc_sub = PETSC_DECIDE;
11007:     nloc_sub = PETSC_DECIDE;
11008:     if (bs < 1) {
11009:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
11010:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
11011:     } else {
11012:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
11013:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
11014:     }
11015:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
11016:     rstart = rend - mloc_sub;
11017:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
11018:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
11019:     PetscCall(ISSetIdentity(iscol));
11020:   } else { /* reuse == MAT_REUSE_MATRIX */
11021:     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");
11022:     /* retrieve subcomm */
11023:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
11024:     redund = (*matredundant)->redundant;
11025:     isrow  = redund->isrow;
11026:     iscol  = redund->iscol;
11027:     matseq = redund->matseq;
11028:   }
11029:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

11031:   /* get matredundant over subcomm */
11032:   if (reuse == MAT_INITIAL_MATRIX) {
11033:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

11035:     /* create a supporting struct and attach it to C for reuse */
11036:     PetscCall(PetscNew(&redund));
11037:     (*matredundant)->redundant = redund;
11038:     redund->isrow              = isrow;
11039:     redund->iscol              = iscol;
11040:     redund->matseq             = matseq;
11041:     if (newsubcomm) {
11042:       redund->subcomm = subcomm;
11043:     } else {
11044:       redund->subcomm = MPI_COMM_NULL;
11045:     }
11046:   } else {
11047:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
11048:   }
11049: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
11050:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
11051:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
11052:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
11053:   }
11054: #endif
11055:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
11056:   PetscFunctionReturn(PETSC_SUCCESS);
11057: }

11059: /*@
11060:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
11061:   a given `Mat`. Each submatrix can span multiple procs.

11063:   Collective

11065:   Input Parameters:
11066: + mat     - the matrix
11067: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
11068: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11070:   Output Parameter:
11071: . subMat - parallel sub-matrices each spanning a given `subcomm`

11073:   Level: advanced

11075:   Notes:
11076:   The submatrix partition across processes is dictated by `subComm` a
11077:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
11078:   is not restricted to be grouped with consecutive original MPI processes.

11080:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11081:   map directly to the layout of the original matrix [wrt the local
11082:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
11083:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11084:   the `subMat`. However the offDiagMat looses some columns - and this is
11085:   reconstructed with `MatSetValues()`

11087:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11089: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11090: @*/
11091: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11092: {
11093:   PetscMPIInt commsize, subCommSize;

11095:   PetscFunctionBegin;
11096:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11097:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11098:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11100:   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");
11101:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11102:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11103:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11104:   PetscFunctionReturn(PETSC_SUCCESS);
11105: }

11107: /*@
11108:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11110:   Not Collective

11112:   Input Parameters:
11113: + mat   - matrix to extract local submatrix from
11114: . isrow - local row indices for submatrix
11115: - iscol - local column indices for submatrix

11117:   Output Parameter:
11118: . submat - the submatrix

11120:   Level: intermediate

11122:   Notes:
11123:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11125:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11126:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11128:   `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11129:   `MatSetValuesBlockedLocal()` will also be implemented.

11131:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11132:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11134: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11135: @*/
11136: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11137: {
11138:   PetscFunctionBegin;
11142:   PetscCheckSameComm(isrow, 2, iscol, 3);
11143:   PetscAssertPointer(submat, 4);
11144:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11146:   if (mat->ops->getlocalsubmatrix) {
11147:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11148:   } else {
11149:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11150:   }
11151:   (*submat)->assembled = mat->assembled;
11152:   PetscFunctionReturn(PETSC_SUCCESS);
11153: }

11155: /*@
11156:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11158:   Not Collective

11160:   Input Parameters:
11161: + mat    - matrix to extract local submatrix from
11162: . isrow  - local row indices for submatrix
11163: . iscol  - local column indices for submatrix
11164: - submat - the submatrix

11166:   Level: intermediate

11168: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11169: @*/
11170: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11171: {
11172:   PetscFunctionBegin;
11176:   PetscCheckSameComm(isrow, 2, iscol, 3);
11177:   PetscAssertPointer(submat, 4);

11180:   if (mat->ops->restorelocalsubmatrix) {
11181:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11182:   } else {
11183:     PetscCall(MatDestroy(submat));
11184:   }
11185:   *submat = NULL;
11186:   PetscFunctionReturn(PETSC_SUCCESS);
11187: }

11189: /*@
11190:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11192:   Collective

11194:   Input Parameter:
11195: . mat - the matrix

11197:   Output Parameter:
11198: . is - if any rows have zero diagonals this contains the list of them

11200:   Level: developer

11202: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11203: @*/
11204: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11205: {
11206:   PetscFunctionBegin;
11209:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11210:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11212:   if (!mat->ops->findzerodiagonals) {
11213:     Vec                diag;
11214:     const PetscScalar *a;
11215:     PetscInt          *rows;
11216:     PetscInt           rStart, rEnd, r, nrow = 0;

11218:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11219:     PetscCall(MatGetDiagonal(mat, diag));
11220:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11221:     PetscCall(VecGetArrayRead(diag, &a));
11222:     for (r = 0; r < rEnd - rStart; ++r)
11223:       if (a[r] == 0.0) ++nrow;
11224:     PetscCall(PetscMalloc1(nrow, &rows));
11225:     nrow = 0;
11226:     for (r = 0; r < rEnd - rStart; ++r)
11227:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11228:     PetscCall(VecRestoreArrayRead(diag, &a));
11229:     PetscCall(VecDestroy(&diag));
11230:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11231:   } else {
11232:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11233:   }
11234:   PetscFunctionReturn(PETSC_SUCCESS);
11235: }

11237: /*@
11238:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11240:   Collective

11242:   Input Parameter:
11243: . mat - the matrix

11245:   Output Parameter:
11246: . is - contains the list of rows with off block diagonal entries

11248:   Level: developer

11250: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11251: @*/
11252: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11253: {
11254:   PetscFunctionBegin;
11257:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11258:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11260:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11261:   PetscFunctionReturn(PETSC_SUCCESS);
11262: }

11264: /*@
11265:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11267:   Collective; No Fortran Support

11269:   Input Parameter:
11270: . mat - the matrix

11272:   Output Parameter:
11273: . values - the block inverses in column major order (FORTRAN-like)

11275:   Level: advanced

11277:   Notes:
11278:   The size of the blocks is determined by the block size of the matrix.

11280:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11282:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11284: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11285: @*/
11286: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11287: {
11288:   PetscFunctionBegin;
11290:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11291:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11292:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11293:   PetscFunctionReturn(PETSC_SUCCESS);
11294: }

11296: /*@
11297:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11299:   Collective; No Fortran Support

11301:   Input Parameters:
11302: + mat     - the matrix
11303: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11304: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11306:   Output Parameter:
11307: . values - the block inverses in column major order (FORTRAN-like)

11309:   Level: advanced

11311:   Notes:
11312:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11314:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11316: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11317: @*/
11318: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11319: {
11320:   PetscFunctionBegin;
11322:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11323:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11324:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11325:   PetscFunctionReturn(PETSC_SUCCESS);
11326: }

11328: /*@
11329:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11331:   Collective

11333:   Input Parameters:
11334: + A - the matrix
11335: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.

11337:   Level: advanced

11339:   Note:
11340:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11342: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11343: @*/
11344: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11345: {
11346:   const PetscScalar *vals;
11347:   PetscInt          *dnnz;
11348:   PetscInt           m, rstart, rend, bs, i, j;

11350:   PetscFunctionBegin;
11351:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11352:   PetscCall(MatGetBlockSize(A, &bs));
11353:   PetscCall(MatGetLocalSize(A, &m, NULL));
11354:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11355:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11356:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11357:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11358:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11359:   PetscCall(PetscFree(dnnz));
11360:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11361:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11362:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11363:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11364:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11365:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11366:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11367:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11368:   PetscFunctionReturn(PETSC_SUCCESS);
11369: }

11371: /*@
11372:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11373:   via `MatTransposeColoringCreate()`.

11375:   Collective

11377:   Input Parameter:
11378: . c - coloring context

11380:   Level: intermediate

11382: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11383: @*/
11384: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11385: {
11386:   MatTransposeColoring matcolor = *c;

11388:   PetscFunctionBegin;
11389:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11390:   if (--((PetscObject)matcolor)->refct > 0) {
11391:     matcolor = NULL;
11392:     PetscFunctionReturn(PETSC_SUCCESS);
11393:   }

11395:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11396:   PetscCall(PetscFree(matcolor->rows));
11397:   PetscCall(PetscFree(matcolor->den2sp));
11398:   PetscCall(PetscFree(matcolor->colorforcol));
11399:   PetscCall(PetscFree(matcolor->columns));
11400:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11401:   PetscCall(PetscHeaderDestroy(c));
11402:   PetscFunctionReturn(PETSC_SUCCESS);
11403: }

11405: /*@
11406:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11407:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11408:   `MatTransposeColoring` to sparse `B`.

11410:   Collective

11412:   Input Parameters:
11413: + coloring - coloring context created with `MatTransposeColoringCreate()`
11414: - B        - sparse matrix

11416:   Output Parameter:
11417: . Btdense - dense matrix $B^T$

11419:   Level: developer

11421:   Note:
11422:   These are used internally for some implementations of `MatRARt()`

11424: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11425: @*/
11426: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11427: {
11428:   PetscFunctionBegin;

11433:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11434:   PetscFunctionReturn(PETSC_SUCCESS);
11435: }

11437: /*@
11438:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11439:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11440:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11441:   $C_{sp}$ from $C_{den}$.

11443:   Collective

11445:   Input Parameters:
11446: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11447: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11449:   Output Parameter:
11450: . Csp - sparse matrix

11452:   Level: developer

11454:   Note:
11455:   These are used internally for some implementations of `MatRARt()`

11457: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11458: @*/
11459: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11460: {
11461:   PetscFunctionBegin;

11466:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11467:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11468:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11469:   PetscFunctionReturn(PETSC_SUCCESS);
11470: }

11472: /*@
11473:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11475:   Collective

11477:   Input Parameters:
11478: + mat        - the matrix product C
11479: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11481:   Output Parameter:
11482: . color - the new coloring context

11484:   Level: intermediate

11486: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11487:           `MatTransColoringApplyDenToSp()`
11488: @*/
11489: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11490: {
11491:   MatTransposeColoring c;
11492:   MPI_Comm             comm;

11494:   PetscFunctionBegin;
11495:   PetscAssertPointer(color, 3);

11497:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11498:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11499:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11500:   c->ctype = iscoloring->ctype;
11501:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11502:   *color = c;
11503:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11504:   PetscFunctionReturn(PETSC_SUCCESS);
11505: }

11507: /*@
11508:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11509:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11511:   Not Collective

11513:   Input Parameter:
11514: . mat - the matrix

11516:   Output Parameter:
11517: . state - the current state

11519:   Level: intermediate

11521:   Notes:
11522:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11523:   different matrices

11525:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11527:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11529: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11530: @*/
11531: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11532: {
11533:   PetscFunctionBegin;
11535:   *state = mat->nonzerostate;
11536:   PetscFunctionReturn(PETSC_SUCCESS);
11537: }

11539: /*@
11540:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11541:   matrices from each process

11543:   Collective

11545:   Input Parameters:
11546: + comm   - the communicators the parallel matrix will live on
11547: . seqmat - the input sequential matrices
11548: . n      - number of local columns (or `PETSC_DECIDE`)
11549: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11551:   Output Parameter:
11552: . mpimat - the parallel matrix generated

11554:   Level: developer

11556:   Note:
11557:   The number of columns of the matrix in EACH process MUST be the same.

11559: .seealso: [](ch_matrices), `Mat`
11560: @*/
11561: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11562: {
11563:   PetscMPIInt size;

11565:   PetscFunctionBegin;
11566:   PetscCallMPI(MPI_Comm_size(comm, &size));
11567:   if (size == 1) {
11568:     if (reuse == MAT_INITIAL_MATRIX) {
11569:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11570:     } else {
11571:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11572:     }
11573:     PetscFunctionReturn(PETSC_SUCCESS);
11574:   }

11576:   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");

11578:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11579:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11580:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11581:   PetscFunctionReturn(PETSC_SUCCESS);
11582: }

11584: /*@
11585:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11587:   Collective

11589:   Input Parameters:
11590: + A - the matrix to create subdomains from
11591: - N - requested number of subdomains

11593:   Output Parameters:
11594: + n   - number of subdomains resulting on this MPI process
11595: - iss - `IS` list with indices of subdomains on this MPI process

11597:   Level: advanced

11599:   Note:
11600:   The number of subdomains must be smaller than the communicator size

11602: .seealso: [](ch_matrices), `Mat`, `IS`
11603: @*/
11604: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11605: {
11606:   MPI_Comm    comm, subcomm;
11607:   PetscMPIInt size, rank, color;
11608:   PetscInt    rstart, rend, k;

11610:   PetscFunctionBegin;
11611:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11612:   PetscCallMPI(MPI_Comm_size(comm, &size));
11613:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11614:   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);
11615:   *n    = 1;
11616:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11617:   color = rank / k;
11618:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11619:   PetscCall(PetscMalloc1(1, iss));
11620:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11621:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11622:   PetscCallMPI(MPI_Comm_free(&subcomm));
11623:   PetscFunctionReturn(PETSC_SUCCESS);
11624: }

11626: /*@
11627:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11629:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11630:   If they are not the same, uses `MatMatMatMult()`.

11632:   Once the coarse grid problem is constructed, correct for interpolation operators
11633:   that are not of full rank, which can legitimately happen in the case of non-nested
11634:   geometric multigrid.

11636:   Input Parameters:
11637: + restrct     - restriction operator
11638: . dA          - fine grid matrix
11639: . interpolate - interpolation operator
11640: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11641: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11643:   Output Parameter:
11644: . A - the Galerkin coarse matrix

11646:   Options Database Key:
11647: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11649:   Level: developer

11651:   Note:
11652:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11654: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11655: @*/
11656: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11657: {
11658:   IS  zerorows;
11659:   Vec diag;

11661:   PetscFunctionBegin;
11662:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11663:   /* Construct the coarse grid matrix */
11664:   if (interpolate == restrct) {
11665:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11666:   } else {
11667:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11668:   }

11670:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11671:      This can legitimately happen in the case of non-nested geometric multigrid.
11672:      In that event, we set the rows of the matrix to the rows of the identity,
11673:      ignoring the equations (as the RHS will also be zero). */

11675:   PetscCall(MatFindZeroRows(*A, &zerorows));

11677:   if (zerorows != NULL) { /* if there are any zero rows */
11678:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11679:     PetscCall(MatGetDiagonal(*A, diag));
11680:     PetscCall(VecISSet(diag, zerorows, 1.0));
11681:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11682:     PetscCall(VecDestroy(&diag));
11683:     PetscCall(ISDestroy(&zerorows));
11684:   }
11685:   PetscFunctionReturn(PETSC_SUCCESS);
11686: }

11688: /*@
11689:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11691:   Logically Collective

11693:   Input Parameters:
11694: + mat - the matrix
11695: . op  - the name of the operation
11696: - f   - the function that provides the operation

11698:   Level: developer

11700:   Example Usage:
11701: .vb
11702:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11704:   PetscCall(MatCreateXXX(comm, ..., &A));
11705:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11706: .ve

11708:   Notes:
11709:   See the file `include/petscmat.h` for a complete list of matrix
11710:   operations, which all have the form MATOP_<OPERATION>, where
11711:   <OPERATION> is the name (in all capital letters) of the
11712:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11714:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11715:   sequence as the usual matrix interface routines, since they
11716:   are intended to be accessed via the usual matrix interface
11717:   routines, e.g.,
11718: .vb
11719:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11720: .ve

11722:   In particular each function MUST return `PETSC_SUCCESS` on success and
11723:   nonzero on failure.

11725:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11727: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11728: @*/
11729: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11730: {
11731:   PetscFunctionBegin;
11734:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11735: #if !PetscDefined(USE_COMPLEX)
11736:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11737:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11738:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11739: #endif
11740:   ((PetscErrorCodeFn **)mat->ops)[op] = f;
11741:   PetscFunctionReturn(PETSC_SUCCESS);
11742: }

11744: /*@
11745:   MatGetOperation - Gets a matrix operation for any matrix type.

11747:   Not Collective

11749:   Input Parameters:
11750: + mat - the matrix
11751: - op  - the name of the operation

11753:   Output Parameter:
11754: . f - the function that provides the operation

11756:   Level: developer

11758:   Example Usage:
11759: .vb
11760:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11762:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11763: .ve

11765:   Notes:
11766:   See the file `include/petscmat.h` for a complete list of matrix
11767:   operations, which all have the form MATOP_<OPERATION>, where
11768:   <OPERATION> is the name (in all capital letters) of the
11769:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11771:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11773: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11774: @*/
11775: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11776: {
11777:   PetscFunctionBegin;
11779:   PetscAssertPointer(f, 3);
11780: #if !PetscDefined(USE_COMPLEX)
11781:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11782:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11783:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11784: #endif
11785:   *f = ((PetscErrorCodeFn **)mat->ops)[op];
11786:   PetscFunctionReturn(PETSC_SUCCESS);
11787: }

11789: /*@
11790:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11792:   Not Collective

11794:   Input Parameters:
11795: + mat - the matrix
11796: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11798:   Output Parameter:
11799: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11801:   Level: advanced

11803:   Note:
11804:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11806: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11807: @*/
11808: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11809: {
11810:   PetscFunctionBegin;
11812:   PetscAssertPointer(has, 3);
11813: #if !PetscDefined(USE_COMPLEX)
11814:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11815:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11816:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11817: #endif
11818:   if (op == MATOP_ADOT || op == MATOP_ANORM) {
11819:     /* MatADot() and MatANorm() fall back to MatMult() when the type has no method */
11820:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11821:     else PetscCall(MatHasOperation(mat, MATOP_MULT, has));
11822:     PetscFunctionReturn(PETSC_SUCCESS);
11823:   }
11824:   if (mat->ops->hasoperation) {
11825:     PetscUseTypeMethod(mat, hasoperation, op, has);
11826:   } else {
11827:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11828:     else {
11829:       *has = PETSC_FALSE;
11830:       if (op == MATOP_CREATE_SUBMATRIX) {
11831:         PetscMPIInt size;

11833:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11834:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11835:       }
11836:     }
11837:   }
11838:   PetscFunctionReturn(PETSC_SUCCESS);
11839: }

11841: /*@
11842:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11844:   Collective

11846:   Input Parameter:
11847: . mat - the matrix

11849:   Output Parameter:
11850: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11852:   Level: beginner

11854: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11855: @*/
11856: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11857: {
11858:   PetscFunctionBegin;
11861:   PetscAssertPointer(cong, 2);
11862:   if (!mat->rmap || !mat->cmap) {
11863:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11864:     PetscFunctionReturn(PETSC_SUCCESS);
11865:   }
11866:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11867:     PetscCall(PetscLayoutSetUp(mat->rmap));
11868:     PetscCall(PetscLayoutSetUp(mat->cmap));
11869:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11870:     if (*cong) mat->congruentlayouts = 1;
11871:     else mat->congruentlayouts = 0;
11872:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11873:   PetscFunctionReturn(PETSC_SUCCESS);
11874: }

11876: /*@
11877:   MatFlag - set infinity into the local part of the matrix on any subset of MPI processes

11879:   Logically Collective

11881:   Input Parameters:
11882: + A   - the matrix, can be `NULL` but only if on all processes
11883: - flg - indicates if this processes portion of the matrix should be set to infinity

11885:   Level: developer

11887:   Notes:
11888:   This is used to flag a block of solutions that a linear solver failed to compute, as `VecFlag()` does for a single solution.

11890:   The state of `A` is increased on all processes, whether or not their portion is flagged, so an outer solver that tracks it detects the failure even when the entries were already infinite.

11892:   Only the dense types (`MATSEQDENSE`, `MATMPIDENSE`, and their device variants) currently implement this operation.

11894: .seealso: [](ch_matrices), `Mat`, `VecFlag()`, `MatZeroEntries()`, `MatSetValues()`
11895: @*/
11896: PetscErrorCode MatFlag(Mat A, PetscInt flg)
11897: {
11898:   PetscFunctionBegin;
11899:   if (!A) PetscFunctionReturn(PETSC_SUCCESS);
11902:   MatCheckPreallocated(A, 1);
11903:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
11904:   if (flg) PetscUseTypeMethod(A, setinf);
11905:   PetscFunctionReturn(PETSC_SUCCESS);
11906: }

11908: /*@
11909:   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
11910:   and possibly removes small values from the graph structure.

11912:   Collective

11914:   Input Parameters:
11915: + A       - the matrix
11916: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11917: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11918: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with $|entries| \le filter$
11919: . num_idx - size of `index` array
11920: - index   - array of block indices to use for graph strength of connection weight

11922:   Output Parameter:
11923: . graph - the resulting graph

11925:   Level: advanced

11927: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11928: @*/
11929: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11930: {
11931:   PetscFunctionBegin;
11935:   PetscAssertPointer(graph, 7);
11936:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11937:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11938:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11939:   PetscFunctionReturn(PETSC_SUCCESS);
11940: }

11942: /*@
11943:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11944:   meaning the same memory is used for the matrix, and no new memory is allocated.

11946:   Collective

11948:   Input Parameters:
11949: + A    - the matrix
11950: - 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

11952:   Level: intermediate

11954:   Developer Note:
11955:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11956:   of the arrays in the data structure may be no longer needed to represent the matrix.

11958: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11959: @*/
11960: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11961: {
11962:   PetscFunctionBegin;
11964:   PetscUseTypeMethod(A, eliminatezeros, keep);
11965:   PetscFunctionReturn(PETSC_SUCCESS);
11966: }

11968: /*@
11969:   MatGetCurrentMemType - Get the memory location of the matrix

11971:   Not Collective, but the result will be the same on all MPI processes

11973:   Input Parameter:
11974: . A - the matrix whose memory type we are checking

11976:   Output Parameter:
11977: . m - the memory type, see `PetscMemType`

11979:   Level: intermediate

11981: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11982: @*/
11983: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11984: {
11985:   PetscFunctionBegin;
11987:   PetscAssertPointer(m, 2);
11988:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11989:   else *m = PETSC_MEMTYPE_HOST;
11990:   PetscFunctionReturn(PETSC_SUCCESS);
11991: }