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:   MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.

400:   Collective

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

405:   Output Parameter:
406: . trace - the sum of the diagonal entries

408:   Level: advanced

410: .seealso: [](ch_matrices), `Mat`
411: @*/
412: PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
413: {
414:   Vec diag;

416:   PetscFunctionBegin;
418:   PetscAssertPointer(trace, 2);
419:   PetscCall(MatCreateVecs(mat, &diag, NULL));
420:   PetscCall(MatGetDiagonal(mat, diag));
421:   PetscCall(VecSum(diag, trace));
422:   PetscCall(VecDestroy(&diag));
423:   PetscFunctionReturn(PETSC_SUCCESS);
424: }

426: /*@
427:   MatRealPart - Zeros out the imaginary part of the matrix

429:   Logically Collective

431:   Input Parameter:
432: . mat - the matrix

434:   Level: advanced

436: .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
437: @*/
438: PetscErrorCode MatRealPart(Mat mat)
439: {
440:   PetscFunctionBegin;
443:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
444:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
445:   MatCheckPreallocated(mat, 1);
446:   PetscUseTypeMethod(mat, realpart);
447:   PetscFunctionReturn(PETSC_SUCCESS);
448: }

450: /*@C
451:   MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix

453:   Collective

455:   Input Parameter:
456: . mat - the matrix

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

462:   Level: advanced

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

467: .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
468: @*/
469: PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
470: {
471:   PetscFunctionBegin;
474:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
475:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
476:   if (mat->ops->getghosts) PetscUseTypeMethod(mat, getghosts, nghosts, ghosts);
477:   else {
478:     if (nghosts) *nghosts = 0;
479:     if (ghosts) *ghosts = NULL;
480:   }
481:   PetscFunctionReturn(PETSC_SUCCESS);
482: }

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

487:   Logically Collective

489:   Input Parameter:
490: . mat - the matrix

492:   Level: advanced

494: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
495: @*/
496: PetscErrorCode MatImaginaryPart(Mat mat)
497: {
498:   PetscFunctionBegin;
501:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
502:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
503:   MatCheckPreallocated(mat, 1);
504:   PetscUseTypeMethod(mat, imaginarypart);
505:   PetscFunctionReturn(PETSC_SUCCESS);
506: }

508: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
509: /*@C
510:   MatGetRow - Gets a row of a matrix.  You MUST call `MatRestoreRow()`
511:   for each row that you get to ensure that your application does
512:   not bleed memory.

514:   Not Collective

516:   Input Parameters:
517: + mat - the matrix
518: - row - the row to get

520:   Output Parameters:
521: + ncols - if not `NULL`, the number of nonzeros in `row`
522: . cols  - if not `NULL`, the column numbers
523: - vals  - if not `NULL`, the numerical values

525:   Level: advanced

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

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

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

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

542:   You can only have one call to `MatGetRow()` outstanding for a particular
543:   matrix at a time, per processor. `MatGetRow()` can only obtain rows
544:   associated with the given processor, it cannot get rows from the
545:   other processors; for that we suggest using `MatCreateSubMatrices()`, then
546:   `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
547:   is in the global number of rows.

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

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

553:   Fortran Note:
554: .vb
555:   PetscInt, pointer :: cols(:)
556:   PetscScalar, pointer :: vals(:)
557: .ve

559: .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
560: @*/
561: PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
562: {
563:   PetscInt incols;

565:   PetscFunctionBegin;
568:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
569:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
570:   MatCheckPreallocated(mat, 1);
571:   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);
572:   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
573:   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
574:   if (ncols) *ncols = incols;
575:   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
576:   PetscFunctionReturn(PETSC_SUCCESS);
577: }

579: /*@
580:   MatConjugate - replaces the matrix values with their complex conjugates

582:   Logically Collective

584:   Input Parameter:
585: . mat - the matrix

587:   Level: advanced

589: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
590: @*/
591: PetscErrorCode MatConjugate(Mat mat)
592: {
593:   PetscFunctionBegin;
595:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
596:   if (PetscDefined(USE_COMPLEX) && !(mat->symmetric == PETSC_BOOL3_TRUE && mat->hermitian == PETSC_BOOL3_TRUE)) {
597:     PetscUseTypeMethod(mat, conjugate);
598:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
599:   }
600:   PetscFunctionReturn(PETSC_SUCCESS);
601: }

603: /*@C
604:   MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.

606:   Not Collective

608:   Input Parameters:
609: + mat   - the matrix
610: . row   - the row to get
611: . ncols - the number of nonzeros
612: . cols  - the columns of the nonzeros
613: - vals  - if nonzero the column values

615:   Level: advanced

617:   Notes:
618:   This routine should be called after you have finished examining the entries.

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

624:   Fortran Note:
625: .vb
626:   PetscInt, pointer :: cols(:)
627:   PetscScalar, pointer :: vals(:)
628: .ve

630: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
631: @*/
632: PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
633: {
634:   PetscFunctionBegin;
636:   if (ncols) PetscAssertPointer(ncols, 3);
637:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
638:   PetscTryTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
639:   if (ncols) *ncols = 0;
640:   if (cols) *cols = NULL;
641:   if (vals) *vals = NULL;
642:   PetscFunctionReturn(PETSC_SUCCESS);
643: }

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

649:   Not Collective

651:   Input Parameter:
652: . mat - the matrix

654:   Level: advanced

656:   Note:
657:   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.

659: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
660: @*/
661: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
662: {
663:   PetscFunctionBegin;
666:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
667:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
668:   MatCheckPreallocated(mat, 1);
669:   PetscTryTypeMethod(mat, getrowuppertriangular);
670:   PetscFunctionReturn(PETSC_SUCCESS);
671: }

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

676:   Not Collective

678:   Input Parameter:
679: . mat - the matrix

681:   Level: advanced

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

686: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
687: @*/
688: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
689: {
690:   PetscFunctionBegin;
693:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
694:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
695:   MatCheckPreallocated(mat, 1);
696:   PetscTryTypeMethod(mat, restorerowuppertriangular);
697:   PetscFunctionReturn(PETSC_SUCCESS);
698: }

700: /*@
701:   MatSetOptionsPrefix - Sets the prefix used for searching for all
702:   `Mat` options in the database.

704:   Logically Collective

706:   Input Parameters:
707: + A      - the matrix
708: - prefix - the prefix to prepend to all option names

710:   Level: advanced

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

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

720: .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
721: @*/
722: PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
723: {
724:   PetscFunctionBegin;
726:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
727:   PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
728:   PetscFunctionReturn(PETSC_SUCCESS);
729: }

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

735:   Logically Collective

737:   Input Parameters:
738: + A      - the matrix
739: - prefix - the prefix to prepend to all option names for the factored matrix

741:   Level: developer

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

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

750: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
751: @*/
752: PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
753: {
754:   PetscFunctionBegin;
756:   if (prefix) {
757:     PetscAssertPointer(prefix, 2);
758:     PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
759:     if (prefix != A->factorprefix) {
760:       PetscCall(PetscFree(A->factorprefix));
761:       PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
762:     }
763:   } else PetscCall(PetscFree(A->factorprefix));
764:   PetscFunctionReturn(PETSC_SUCCESS);
765: }

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

771:   Logically Collective

773:   Input Parameters:
774: + A      - the matrix
775: - prefix - the prefix to prepend to all option names for the factored matrix

777:   Level: developer

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

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

786: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
787:           `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
788:           `MatSetOptionsPrefix()`
789: @*/
790: PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
791: {
792:   size_t len1, len2, new_len;

794:   PetscFunctionBegin;
796:   if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
797:   if (!A->factorprefix) {
798:     PetscCall(MatSetOptionsPrefixFactor(A, prefix));
799:     PetscFunctionReturn(PETSC_SUCCESS);
800:   }
801:   PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");

803:   PetscCall(PetscStrlen(A->factorprefix, &len1));
804:   PetscCall(PetscStrlen(prefix, &len2));
805:   new_len = len1 + len2 + 1;
806:   PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
807:   PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
808:   PetscFunctionReturn(PETSC_SUCCESS);
809: }

811: /*@
812:   MatAppendOptionsPrefix - Appends to the prefix used for searching for all
813:   matrix options in the database.

815:   Logically Collective

817:   Input Parameters:
818: + A      - the matrix
819: - prefix - the prefix to prepend to all option names

821:   Level: advanced

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

827: .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
828: @*/
829: PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
830: {
831:   PetscFunctionBegin;
833:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
834:   PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
835:   PetscFunctionReturn(PETSC_SUCCESS);
836: }

838: /*@
839:   MatGetOptionsPrefix - Gets the prefix used for searching for all
840:   matrix options in the database.

842:   Not Collective

844:   Input Parameter:
845: . A - the matrix

847:   Output Parameter:
848: . prefix - pointer to the prefix string used

850:   Level: advanced

852: .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
853: @*/
854: PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
855: {
856:   PetscFunctionBegin;
858:   PetscAssertPointer(prefix, 2);
859:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
860:   PetscFunctionReturn(PETSC_SUCCESS);
861: }

863: /*@
864:   MatGetState - Gets the state of a `Mat`. Same value as returned by `PetscObjectStateGet()`

866:   Not Collective

868:   Input Parameter:
869: . A - the matrix

871:   Output Parameter:
872: . state - the object state

874:   Level: advanced

876:   Note:
877:   Object state is an integer which gets increased every time
878:   the object is changed. By saving and later querying the object state
879:   one can determine whether information about the object is still current.

881:   See `MatGetNonzeroState()` to determine if the nonzero structure of the matrix has changed.

883: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
884: @*/
885: PetscErrorCode MatGetState(Mat A, PetscObjectState *state)
886: {
887:   PetscFunctionBegin;
889:   PetscAssertPointer(state, 2);
890:   PetscCall(PetscObjectStateGet((PetscObject)A, state));
891:   PetscFunctionReturn(PETSC_SUCCESS);
892: }

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

897:   Collective

899:   Input Parameter:
900: . A - the matrix

902:   Level: beginner

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

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

911:   Currently only supported for  `MATAIJ` matrices.

913: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
914: @*/
915: PetscErrorCode MatResetPreallocation(Mat A)
916: {
917:   PetscFunctionBegin;
920:   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
921:   PetscFunctionReturn(PETSC_SUCCESS);
922: }

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

927:   Collective

929:   Input Parameter:
930: . A - the matrix

932:   Level: intermediate

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

937:   Currently only supported for `MATAIJ` matrices.

939: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
940: @*/
941: PetscErrorCode MatResetHash(Mat A)
942: {
943:   PetscFunctionBegin;
946:   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()");
947:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
948:   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
949:   /* These flags are used to determine whether certain setups occur */
950:   A->was_assembled = PETSC_FALSE;
951:   A->assembled     = PETSC_FALSE;
952:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
953:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
954:   PetscFunctionReturn(PETSC_SUCCESS);
955: }

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

960:   Collective

962:   Input Parameter:
963: . A - the matrix

965:   Level: advanced

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

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

973: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
974: @*/
975: PetscErrorCode MatSetUp(Mat A)
976: {
977:   PetscFunctionBegin;
979:   if (!((PetscObject)A)->type_name) {
980:     PetscMPIInt size;

982:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
983:     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
984:   }
985:   if (!A->preallocated) PetscTryTypeMethod(A, setup);
986:   PetscCall(PetscLayoutSetUp(A->rmap));
987:   PetscCall(PetscLayoutSetUp(A->cmap));
988:   A->preallocated = PETSC_TRUE;
989:   PetscFunctionReturn(PETSC_SUCCESS);
990: }

992: #if defined(PETSC_HAVE_SAWS)
993: #include <petscviewersaws.h>
994: #endif

996: /*
997:    If threadsafety is on extraneous matrices may be printed

999:    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1000: */
1001: #if !defined(PETSC_HAVE_THREADSAFETY)
1002: static PetscInt insidematview = 0;
1003: #endif

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

1008:   Collective

1010:   Input Parameters:
1011: + A    - the matrix
1012: . obj  - optional additional object that provides the options prefix to use
1013: - name - command line option

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

1018:   Level: intermediate

1020: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1021: @*/
1022: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1023: {
1024:   PetscFunctionBegin;
1026: #if !defined(PETSC_HAVE_THREADSAFETY)
1027:   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1028: #endif
1029:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1030:   PetscFunctionReturn(PETSC_SUCCESS);
1031: }

1033: /*@
1034:   MatView - display information about a matrix in a variety ways

1036:   Collective on viewer

1038:   Input Parameters:
1039: + mat    - the matrix
1040: - viewer - visualization context

1042:   Options Database Keys:
1043: + -mat_view ::ascii_info         - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1044: . -mat_view ::ascii_info_detail  - Prints more detailed info
1045: . -mat_view                      - Prints matrix in ASCII format
1046: . -mat_view ::ascii_matlab       - Prints matrix in MATLAB format
1047: . -mat_view draw                 - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1048: . -display name                  - Sets display name (default is host)
1049: . -draw_pause sec                - Sets number of seconds to pause after display
1050: . -mat_view socket               - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1051: . -viewer_socket_machine machine - -
1052: . -viewer_socket_port port       - -
1053: . -mat_view binary               - save matrix to file in binary format
1054: - -viewer_binary_filename name   - -

1056:   Level: beginner

1058:   Notes:
1059:   The available visualization contexts include
1060: +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1061: .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1062: .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1063: -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure

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

1071:   The user can call `PetscViewerPushFormat()` to specify the output
1072:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1073:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
1074: +    `PETSC_VIEWER_DEFAULT`           - default, prints matrix contents
1075: .    `PETSC_VIEWER_ASCII_MATLAB`      - prints matrix contents in MATLAB format
1076: .    `PETSC_VIEWER_ASCII_DENSE`       - prints entire matrix including zeros
1077: .    `PETSC_VIEWER_ASCII_COMMON`      - prints matrix contents, using a sparse  format common among all matrix types
1078: .    `PETSC_VIEWER_ASCII_IMPL`        - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1079: .    `PETSC_VIEWER_ASCII_INFO`        - prints basic information about the matrix size and structure (not the matrix entries)
1080: -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)

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

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

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

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

1093:   One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1094:   and then use the following mouse functions.
1095: .vb
1096:   left mouse: zoom in
1097:   middle mouse: zoom out
1098:   right mouse: continue with the simulation
1099: .ve

1101: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1102:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1103: @*/
1104: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1105: {
1106:   PetscInt          rows, cols, rbs, cbs;
1107:   PetscBool         isascii, isstring, issaws;
1108:   PetscViewerFormat format;
1109:   PetscMPIInt       size;

1111:   PetscFunctionBegin;
1114:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

1117:   PetscCall(PetscViewerGetFormat(viewer, &format));
1118:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1119:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

1121: #if !defined(PETSC_HAVE_THREADSAFETY)
1122:   insidematview++;
1123: #endif
1124:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1125:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1126:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1127:   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");

1129:   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1130:   if (isascii) {
1131:     if (!mat->preallocated) {
1132:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1133: #if !defined(PETSC_HAVE_THREADSAFETY)
1134:       insidematview--;
1135: #endif
1136:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1137:       PetscFunctionReturn(PETSC_SUCCESS);
1138:     }
1139:     if (!mat->assembled) {
1140:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1141: #if !defined(PETSC_HAVE_THREADSAFETY)
1142:       insidematview--;
1143: #endif
1144:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1145:       PetscFunctionReturn(PETSC_SUCCESS);
1146:     }
1147:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1148:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1149:       MatNullSpace nullsp, transnullsp;

1151:       PetscCall(PetscViewerASCIIPushTab(viewer));
1152:       PetscCall(MatGetSize(mat, &rows, &cols));
1153:       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1154:       if (rbs != 1 || cbs != 1) {
1155:         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" : ""));
1156:         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1157:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1158:       if (mat->factortype) {
1159:         MatSolverType solver;
1160:         PetscCall(MatFactorGetSolverType(mat, &solver));
1161:         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1162:       }
1163:       if (mat->ops->getinfo) {
1164:         PetscBool is_constant_or_diagonal;

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

1171:           PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1172:           PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1173:           if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1174:         }
1175:       }
1176:       PetscCall(MatGetNullSpace(mat, &nullsp));
1177:       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1178:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1179:       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1180:       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1181:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1182:       PetscCall(PetscViewerASCIIPushTab(viewer));
1183:       PetscCall(MatProductView(mat, viewer));
1184:       PetscCall(PetscViewerASCIIPopTab(viewer));
1185:       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1186:         IS tmp;

1188:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1189:         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1190:         PetscCall(PetscViewerASCIIPushTab(viewer));
1191:         PetscCall(ISView(tmp, viewer));
1192:         PetscCall(PetscViewerASCIIPopTab(viewer));
1193:         PetscCall(ISDestroy(&tmp));
1194:       }
1195:     }
1196:   } else if (issaws) {
1197: #if defined(PETSC_HAVE_SAWS)
1198:     PetscMPIInt rank;

1200:     PetscCall(PetscObjectName((PetscObject)mat));
1201:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1202:     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1203: #endif
1204:   } else if (isstring) {
1205:     const char *type;
1206:     PetscCall(MatGetType(mat, &type));
1207:     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1208:     PetscTryTypeMethod(mat, view, viewer);
1209:   }
1210:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1211:     PetscCall(PetscViewerASCIIPushTab(viewer));
1212:     PetscUseTypeMethod(mat, viewnative, viewer);
1213:     PetscCall(PetscViewerASCIIPopTab(viewer));
1214:   } else if (mat->ops->view) {
1215:     PetscCall(PetscViewerASCIIPushTab(viewer));
1216:     PetscUseTypeMethod(mat, view, viewer);
1217:     PetscCall(PetscViewerASCIIPopTab(viewer));
1218:   }
1219:   if (isascii) {
1220:     PetscCall(PetscViewerGetFormat(viewer, &format));
1221:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1222:   }
1223:   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1224: #if !defined(PETSC_HAVE_THREADSAFETY)
1225:   insidematview--;
1226: #endif
1227:   PetscFunctionReturn(PETSC_SUCCESS);
1228: }

1230: #if defined(PETSC_USE_DEBUG)
1231: #include <../src/sys/totalview/tv_data_display.h>
1232: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1233: {
1234:   TV_add_row("Local rows", "int", &mat->rmap->n);
1235:   TV_add_row("Local columns", "int", &mat->cmap->n);
1236:   TV_add_row("Global rows", "int", &mat->rmap->N);
1237:   TV_add_row("Global columns", "int", &mat->cmap->N);
1238:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1239:   return TV_format_OK;
1240: }
1241: #endif

1243: /*@
1244:   MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1245:   with `MatView()`.  The matrix format is determined from the options database.
1246:   Generates a parallel MPI matrix if the communicator has more than one
1247:   processor.  The default matrix type is `MATAIJ`.

1249:   Collective

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

1256:   Options Database Key:
1257: . -matload_block_size bs - set block size

1259:   Level: beginner

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

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

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

1274:   In parallel, each processor can load a subset of rows (or the
1275:   entire matrix).  This routine is especially useful when a large
1276:   matrix is stored on disk and only part of it is desired on each
1277:   processor.  For example, a parallel solver may access only some of
1278:   the rows from each processor.  The algorithm used here reads
1279:   relatively small blocks of data rather than reading the entire
1280:   matrix and then subsetting it.

1282:   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1283:   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1284:   or the sequence like
1285: .vb
1286:     `PetscViewer` v;
1287:     `PetscViewerCreate`(`PETSC_COMM_WORLD`,&v);
1288:     `PetscViewerSetType`(v,`PETSCVIEWERBINARY`);
1289:     `PetscViewerSetFromOptions`(v);
1290:     `PetscViewerFileSetMode`(v,`FILE_MODE_READ`);
1291:     `PetscViewerFileSetName`(v,"datafile");
1292: .ve
1293:   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1294: .vb
1295:   -viewer_type {binary, hdf5}
1296: .ve

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

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

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

1311: .vb
1312:     PetscInt    MAT_FILE_CLASSID
1313:     PetscInt    number of rows
1314:     PetscInt    number of columns
1315:     PetscInt    total number of nonzeros
1316:     PetscInt    *number nonzeros in each row
1317:     PetscInt    *column indices of all nonzeros (starting index is zero)
1318:     PetscScalar *values of all nonzeros
1319: .ve
1320:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1321:   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
1322:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

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

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

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

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

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

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

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

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

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

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

1362: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1363:  @*/
1364: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1365: {
1366:   PetscBool flg;

1368:   PetscFunctionBegin;

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

1374:   flg = PETSC_FALSE;
1375:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1376:   if (flg) {
1377:     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1378:     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1379:   }
1380:   flg = PETSC_FALSE;
1381:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1382:   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));

1384:   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1385:   PetscUseTypeMethod(mat, load, viewer);
1386:   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1387:   PetscFunctionReturn(PETSC_SUCCESS);
1388: }

1390: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1391: {
1392:   Mat_Redundant *redund = *redundant;

1394:   PetscFunctionBegin;
1395:   if (redund) {
1396:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1397:       PetscCall(ISDestroy(&redund->isrow));
1398:       PetscCall(ISDestroy(&redund->iscol));
1399:       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1400:     } else {
1401:       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1402:       PetscCall(PetscFree(redund->sbuf_j));
1403:       PetscCall(PetscFree(redund->sbuf_a));
1404:       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1405:         PetscCall(PetscFree(redund->rbuf_j[i]));
1406:         PetscCall(PetscFree(redund->rbuf_a[i]));
1407:       }
1408:       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1409:     }

1411:     PetscCall(PetscCommDestroy(&redund->subcomm));
1412:     PetscCall(PetscFree(redund));
1413:   }
1414:   PetscFunctionReturn(PETSC_SUCCESS);
1415: }

1417: /*@
1418:   MatDestroy - Frees space taken by a matrix.

1420:   Collective

1422:   Input Parameter:
1423: . A - the matrix

1425:   Level: beginner

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

1433: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1434: @*/
1435: PetscErrorCode MatDestroy(Mat *A)
1436: {
1437:   PetscFunctionBegin;
1438:   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1440:   if (--((PetscObject)*A)->refct > 0) {
1441:     *A = NULL;
1442:     PetscFunctionReturn(PETSC_SUCCESS);
1443:   }

1445:   /* if memory was published with SAWs then destroy it */
1446:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1447:   PetscTryTypeMethod(*A, destroy);

1449:   PetscCall(PetscFree((*A)->factorprefix));
1450:   PetscCall(PetscFree((*A)->defaultvectype));
1451:   PetscCall(PetscFree((*A)->defaultrandtype));
1452:   PetscCall(PetscFree((*A)->bsizes));
1453:   PetscCall(PetscFree((*A)->solvertype));
1454:   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1455:   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1456:   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1457:   PetscCall(MatProductClear(*A));
1458:   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1459:   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1460:   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1461:   PetscCall(MatDestroy(&(*A)->schur));
1462:   PetscCall(VecDestroy(&(*A)->dot_vec));
1463:   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1464:   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1465:   PetscCall(PetscHeaderDestroy(A));
1466:   PetscFunctionReturn(PETSC_SUCCESS);
1467: }

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

1475:   Not Collective

1477:   Input Parameters:
1478: + mat  - the matrix
1479: . m    - the number of rows
1480: . idxm - the global indices of the rows
1481: . n    - the number of columns
1482: . idxn - the global indices of the columns
1483: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1484:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1485: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

1487:   Level: beginner

1489:   Notes:
1490:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1491:   options cannot be mixed without intervening calls to the assembly
1492:   routines.

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

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

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

1506:   Fortran Notes:
1507:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1508: .vb
1509:   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1510: .ve

1512:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1514:   Developer Note:
1515:   This is labeled with C so does not automatically generate Fortran stubs and interfaces
1516:   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

1518: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1519:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1520: @*/
1521: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1522: {
1523:   PetscFunctionBeginHot;
1526:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1527:   PetscAssertPointer(idxm, 3);
1528:   PetscAssertPointer(idxn, 5);
1529:   MatCheckPreallocated(mat, 1);

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

1534:   if (PetscDefined(USE_DEBUG)) {
1535:     PetscInt i, j;

1537:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1538:     if (v) {
1539:       for (i = 0; i < m; i++) {
1540:         for (j = 0; j < n; j++) {
1541:           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1542: #if defined(PETSC_USE_COMPLEX)
1543:             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]);
1544: #else
1545:             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]);
1546: #endif
1547:         }
1548:       }
1549:     }
1550:     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);
1551:     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);
1552:   }

1554:   if (mat->assembled) {
1555:     mat->was_assembled = PETSC_TRUE;
1556:     mat->assembled     = PETSC_FALSE;
1557:   }
1558:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1559:   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1560:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1561:   PetscFunctionReturn(PETSC_SUCCESS);
1562: }

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

1570:   Not Collective

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

1580:   Level: beginner

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

1585:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1586:   options cannot be mixed without intervening calls to the assembly
1587:   routines.

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

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

1597:   Fortran Note:
1598:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

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

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

1606: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1607:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1608: @*/
1609: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1610: {
1611:   PetscInt        m, n;
1612:   const PetscInt *rows, *cols;

1614:   PetscFunctionBeginHot;
1616:   PetscCall(ISGetIndices(ism, &rows));
1617:   PetscCall(ISGetIndices(isn, &cols));
1618:   PetscCall(ISGetLocalSize(ism, &m));
1619:   PetscCall(ISGetLocalSize(isn, &n));
1620:   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1621:   PetscCall(ISRestoreIndices(ism, &rows));
1622:   PetscCall(ISRestoreIndices(isn, &cols));
1623:   PetscFunctionReturn(PETSC_SUCCESS);
1624: }

1626: /*@
1627:   MatSetValuesRowLocal - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1628:   values into a matrix

1630:   Not Collective

1632:   Input Parameters:
1633: + mat - the matrix
1634: . row - the (block) row to set
1635: - v   - a one-dimensional array that contains the values. For `MATBAIJ` they are implicitly stored as a two-dimensional array, by default in row-major order.
1636:         See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

1638:   Level: intermediate

1640:   Notes:
1641:   The values, `v`, are column-oriented (for the block version) and sorted

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

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

1647:   `row` must belong to this MPI process

1649:   Fortran Note:
1650:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1652: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1653:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`
1654: @*/
1655: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1656: {
1657:   PetscInt globalrow;

1659:   PetscFunctionBegin;
1662:   PetscAssertPointer(v, 3);
1663:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1664:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1665:   PetscFunctionReturn(PETSC_SUCCESS);
1666: }

1668: /*@
1669:   MatSetValuesRow - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1670:   values into a matrix

1672:   Not Collective

1674:   Input Parameters:
1675: + mat - the matrix
1676: . row - the (block) row to set
1677: - v   - a logically two-dimensional (column major) array of values for  block matrices with blocksize larger than one, otherwise a one dimensional array of values

1679:   Level: advanced

1681:   Notes:
1682:   The values, `v`, are column-oriented for the block version.

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

1686:   THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually `MatSetValues()` is used.

1688:   `row` must belong to this process

1690: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1691:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1692: @*/
1693: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1694: {
1695:   PetscFunctionBeginHot;
1698:   MatCheckPreallocated(mat, 1);
1699:   PetscAssertPointer(v, 3);
1700:   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1701:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1702:   mat->insertmode = INSERT_VALUES;

1704:   if (mat->assembled) {
1705:     mat->was_assembled = PETSC_TRUE;
1706:     mat->assembled     = PETSC_FALSE;
1707:   }
1708:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1709:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1710:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1711:   PetscFunctionReturn(PETSC_SUCCESS);
1712: }

1714: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1715: /*@
1716:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1717:   Using structured grid indexing

1719:   Not Collective

1721:   Input Parameters:
1722: + mat  - the matrix
1723: . m    - number of rows being entered
1724: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1725: . n    - number of columns being entered
1726: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1727: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1728:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1729: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values

1731:   Level: beginner

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

1736:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1737:   options cannot be mixed without intervening calls to the assembly
1738:   routines.

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

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

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

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

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

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

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

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

1767:   Fortran Note:
1768:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

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

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

1783:   PetscFunctionBegin;
1784:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1787:   PetscAssertPointer(idxm, 3);
1788:   PetscAssertPointer(idxn, 5);

1790:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1791:     jdxm = buf;
1792:     jdxn = buf + m;
1793:   } else {
1794:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1795:     jdxm = bufm;
1796:     jdxn = bufn;
1797:   }
1798:   for (i = 0; i < m; i++) {
1799:     for (j = 0; j < 3 - sdim; j++) dxm++;
1800:     tmp = *dxm++ - starts[0];
1801:     for (j = 0; j < dim - 1; j++) {
1802:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1803:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1804:     }
1805:     if (mat->stencil.noc) dxm++;
1806:     jdxm[i] = tmp;
1807:   }
1808:   for (i = 0; i < n; i++) {
1809:     for (j = 0; j < 3 - sdim; j++) dxn++;
1810:     tmp = *dxn++ - starts[0];
1811:     for (j = 0; j < dim - 1; j++) {
1812:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1813:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1814:     }
1815:     if (mat->stencil.noc) dxn++;
1816:     jdxn[i] = tmp;
1817:   }
1818:   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1819:   PetscCall(PetscFree2(bufm, bufn));
1820:   PetscFunctionReturn(PETSC_SUCCESS);
1821: }

1823: /*@
1824:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1825:   Using structured grid indexing

1827:   Not Collective

1829:   Input Parameters:
1830: + mat  - the matrix
1831: . m    - number of rows being entered
1832: . idxm - grid coordinates for matrix rows being entered
1833: . n    - number of columns being entered
1834: . idxn - grid coordinates for matrix columns being entered
1835: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1836:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1837: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values

1839:   Level: beginner

1841:   Notes:
1842:   By default the values, `v`, are row-oriented and unsorted.
1843:   See `MatSetOption()` for other options.

1845:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1846:   options cannot be mixed without intervening calls to the assembly
1847:   routines.

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

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

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

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

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

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

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

1873:   Fortran Notes:
1874:   `idxm` and `idxn` should be declared as
1875: .vb
1876:     MatStencil idxm(4,m),idxn(4,n)
1877: .ve
1878:   and the values inserted using
1879: .vb
1880:     idxm(MatStencil_i,1) = i
1881:     idxm(MatStencil_j,1) = j
1882:     idxm(MatStencil_k,1) = k
1883:    etc
1884: .ve

1886:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1888: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1889:           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1890:           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1891: @*/
1892: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1893: {
1894:   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1895:   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1896:   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1898:   PetscFunctionBegin;
1899:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1902:   PetscAssertPointer(idxm, 3);
1903:   PetscAssertPointer(idxn, 5);
1904:   PetscAssertPointer(v, 6);

1906:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1907:     jdxm = buf;
1908:     jdxn = buf + m;
1909:   } else {
1910:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1911:     jdxm = bufm;
1912:     jdxn = bufn;
1913:   }
1914:   for (i = 0; i < m; i++) {
1915:     for (j = 0; j < 3 - sdim; j++) dxm++;
1916:     tmp = *dxm++ - starts[0];
1917:     for (j = 0; j < sdim - 1; j++) {
1918:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1919:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1920:     }
1921:     dxm++;
1922:     jdxm[i] = tmp;
1923:   }
1924:   for (i = 0; i < n; i++) {
1925:     for (j = 0; j < 3 - sdim; j++) dxn++;
1926:     tmp = *dxn++ - starts[0];
1927:     for (j = 0; j < sdim - 1; j++) {
1928:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1929:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1930:     }
1931:     dxn++;
1932:     jdxn[i] = tmp;
1933:   }
1934:   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1935:   PetscCall(PetscFree2(bufm, bufn));
1936:   PetscFunctionReturn(PETSC_SUCCESS);
1937: }

1939: /*@
1940:   MatSetStencil - Sets the grid information for setting values into a matrix via
1941:   `MatSetValuesStencil()`

1943:   Not Collective

1945:   Input Parameters:
1946: + mat    - the matrix
1947: . dim    - dimension of the grid 1, 2, or 3
1948: . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1949: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1950: - dof    - number of degrees of freedom per node

1952:   Level: beginner

1954:   Notes:
1955:   Inspired by the structured grid interface to the HYPRE package
1956:   (www.llnl.gov/CASC/hyper)

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

1961: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1962:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1963: @*/
1964: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1965: {
1966:   PetscFunctionBegin;
1968:   PetscAssertPointer(dims, 3);
1969:   PetscAssertPointer(starts, 4);

1971:   mat->stencil.dim = dim + (dof > 1);
1972:   for (PetscInt i = 0; i < dim; i++) {
1973:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
1974:     mat->stencil.starts[i] = starts[dim - i - 1];
1975:   }
1976:   mat->stencil.dims[dim]   = dof;
1977:   mat->stencil.starts[dim] = 0;
1978:   mat->stencil.noc         = (PetscBool)(dof == 1);
1979:   PetscFunctionReturn(PETSC_SUCCESS);
1980: }

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

1985:   Not Collective

1987:   Input Parameters:
1988: + mat  - the matrix
1989: . m    - the number of block rows
1990: . idxm - the global block indices
1991: . n    - the number of block columns
1992: . idxn - the global block indices
1993: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1994:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1995: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

1997:   Level: intermediate

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

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

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

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

2014:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2015:   options cannot be mixed without intervening calls to the assembly
2016:   routines.

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

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

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

2032:   Example:
2033: .vb
2034:    Suppose m=n=2 and block size(bs) = 2 The array is

2036:    1  2  | 3  4
2037:    5  6  | 7  8
2038:    - - - | - - -
2039:    9  10 | 11 12
2040:    13 14 | 15 16

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

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

2049:   Fortran Notes:
2050:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2051: .vb
2052:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2053: .ve

2055:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2057: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2058: @*/
2059: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2060: {
2061:   PetscFunctionBeginHot;
2064:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2065:   PetscAssertPointer(idxm, 3);
2066:   PetscAssertPointer(idxn, 5);
2067:   MatCheckPreallocated(mat, 1);
2068:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2069:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2070:   if (PetscDefined(USE_DEBUG)) {
2071:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2072:     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2073:   }
2074:   if (PetscDefined(USE_DEBUG)) {
2075:     PetscInt rbs, cbs, M, N, i;
2076:     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2077:     PetscCall(MatGetSize(mat, &M, &N));
2078:     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);
2079:     for (i = 0; i < n; i++)
2080:       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);
2081:   }
2082:   if (mat->assembled) {
2083:     mat->was_assembled = PETSC_TRUE;
2084:     mat->assembled     = PETSC_FALSE;
2085:   }
2086:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2087:   if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2088:   else {
2089:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2090:     PetscInt i, j, bs, cbs;

2092:     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2093:     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2094:       iidxm = buf;
2095:       iidxn = buf + m * bs;
2096:     } else {
2097:       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2098:       iidxm = bufr;
2099:       iidxn = bufc;
2100:     }
2101:     for (i = 0; i < m; i++) {
2102:       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2103:     }
2104:     if (m != n || bs != cbs || idxm != idxn) {
2105:       for (i = 0; i < n; i++) {
2106:         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2107:       }
2108:     } else iidxn = iidxm;
2109:     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2110:     PetscCall(PetscFree2(bufr, bufc));
2111:   }
2112:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2113:   PetscFunctionReturn(PETSC_SUCCESS);
2114: }

2116: /*@
2117:   MatGetValues - Gets a block of local values from a matrix.

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

2121:   Input Parameters:
2122: + mat  - the matrix
2123: . v    - a logically two-dimensional array for storing the values
2124: . m    - the number of rows
2125: . idxm - the  global indices of the rows
2126: . n    - the number of columns
2127: - idxn - the global indices of the columns

2129:   Level: advanced

2131:   Notes:
2132:   The user must allocate space (m*n `PetscScalar`s) for the values, `v`.
2133:   The values, `v`, are then returned in a row-oriented format,
2134:   analogous to that used by default in `MatSetValues()`.

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

2139:   `MatGetValues()` requires that the matrix has been assembled
2140:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2141:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2142:   without intermediate matrix assembly.

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

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

2151: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2152: @*/
2153: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2154: {
2155:   PetscFunctionBegin;
2158:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2159:   PetscAssertPointer(idxm, 3);
2160:   PetscAssertPointer(idxn, 5);
2161:   PetscAssertPointer(v, 6);
2162:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2163:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2164:   MatCheckPreallocated(mat, 1);

2166:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2167:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2168:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2169:   PetscFunctionReturn(PETSC_SUCCESS);
2170: }

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

2176:   Not Collective

2178:   Input Parameters:
2179: + mat  - the matrix
2180: . nrow - number of rows
2181: . irow - the row local indices
2182: . ncol - number of columns
2183: - icol - the column local indices

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

2189:   Level: advanced

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

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

2199: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2200:           `MatSetValuesLocal()`, `MatGetValues()`
2201: @*/
2202: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2203: {
2204:   PetscFunctionBeginHot;
2207:   MatCheckPreallocated(mat, 1);
2208:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2209:   PetscAssertPointer(irow, 3);
2210:   PetscAssertPointer(icol, 5);
2211:   if (PetscDefined(USE_DEBUG)) {
2212:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2213:     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2214:   }
2215:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2216:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2217:   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2218:   else {
2219:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2220:     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2221:       irowm = buf;
2222:       icolm = buf + nrow;
2223:     } else {
2224:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2225:       irowm = bufr;
2226:       icolm = bufc;
2227:     }
2228:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2229:     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2230:     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2231:     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2232:     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2233:     PetscCall(PetscFree2(bufr, bufc));
2234:   }
2235:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2236:   PetscFunctionReturn(PETSC_SUCCESS);
2237: }

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

2243:   Not Collective

2245:   Input Parameters:
2246: + mat  - the matrix
2247: . nb   - the number of blocks
2248: . bs   - the number of rows (and columns) in each block
2249: . rows - a concatenation of the rows for each block
2250: - v    - a concatenation of logically two-dimensional arrays of values

2252:   Level: advanced

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

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

2259: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2260:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2261: @*/
2262: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2263: {
2264:   PetscFunctionBegin;
2267:   PetscAssertPointer(rows, 4);
2268:   PetscAssertPointer(v, 5);
2269:   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

2271:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2272:   for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2273:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2274:   PetscFunctionReturn(PETSC_SUCCESS);
2275: }

2277: /*@
2278:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2279:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2280:   using a local (per-processor) numbering.

2282:   Not Collective

2284:   Input Parameters:
2285: + x        - the matrix
2286: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2287: - cmapping - column mapping

2289:   Level: intermediate

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

2294: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2295: @*/
2296: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2297: {
2298:   PetscFunctionBegin;
2303:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2304:   else {
2305:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2306:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2307:   }
2308:   PetscFunctionReturn(PETSC_SUCCESS);
2309: }

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

2314:   Not Collective

2316:   Input Parameter:
2317: . A - the matrix

2319:   Output Parameters:
2320: + rmapping - row mapping
2321: - cmapping - column mapping

2323:   Level: advanced

2325: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2326: @*/
2327: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2328: {
2329:   PetscFunctionBegin;
2332:   if (rmapping) {
2333:     PetscAssertPointer(rmapping, 2);
2334:     *rmapping = A->rmap->mapping;
2335:   }
2336:   if (cmapping) {
2337:     PetscAssertPointer(cmapping, 3);
2338:     *cmapping = A->cmap->mapping;
2339:   }
2340:   PetscFunctionReturn(PETSC_SUCCESS);
2341: }

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

2346:   Logically Collective

2348:   Input Parameters:
2349: + A    - the matrix
2350: . rmap - row layout
2351: - cmap - column layout

2353:   Level: advanced

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

2358: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2359: @*/
2360: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2361: {
2362:   PetscFunctionBegin;
2364:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2365:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2366:   PetscFunctionReturn(PETSC_SUCCESS);
2367: }

2369: /*@
2370:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2372:   Not Collective

2374:   Input Parameter:
2375: . A - the matrix

2377:   Output Parameters:
2378: + rmap - row layout
2379: - cmap - column layout

2381:   Level: advanced

2383: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2384: @*/
2385: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2386: {
2387:   PetscFunctionBegin;
2390:   if (rmap) {
2391:     PetscAssertPointer(rmap, 2);
2392:     *rmap = A->rmap;
2393:   }
2394:   if (cmap) {
2395:     PetscAssertPointer(cmap, 3);
2396:     *cmap = A->cmap;
2397:   }
2398:   PetscFunctionReturn(PETSC_SUCCESS);
2399: }

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

2405:   Not Collective

2407:   Input Parameters:
2408: + mat  - the matrix
2409: . nrow - number of rows
2410: . irow - the row local indices
2411: . ncol - number of columns
2412: . icol - the column local indices
2413: . y    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2414:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2415: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2417:   Level: intermediate

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

2422:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2423:   options cannot be mixed without intervening calls to the assembly
2424:   routines.

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

2429:   Fortran Notes:
2430:   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2431: .vb
2432:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2433: .ve

2435:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2437: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2438:           `MatGetValuesLocal()`
2439: @*/
2440: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2441: {
2442:   PetscFunctionBeginHot;
2445:   MatCheckPreallocated(mat, 1);
2446:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2447:   PetscAssertPointer(irow, 3);
2448:   PetscAssertPointer(icol, 5);
2449:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2450:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2451:   if (PetscDefined(USE_DEBUG)) {
2452:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2453:     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2454:   }

2456:   if (mat->assembled) {
2457:     mat->was_assembled = PETSC_TRUE;
2458:     mat->assembled     = PETSC_FALSE;
2459:   }
2460:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2461:   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, y, addv);
2462:   else {
2463:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2464:     const PetscInt *irowm, *icolm;

2466:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2467:       bufr  = buf;
2468:       bufc  = buf + nrow;
2469:       irowm = bufr;
2470:       icolm = bufc;
2471:     } else {
2472:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2473:       irowm = bufr;
2474:       icolm = bufc;
2475:     }
2476:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2477:     else irowm = irow;
2478:     if (mat->cmap->mapping) {
2479:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2480:       else icolm = irowm;
2481:     } else icolm = icol;
2482:     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, y, addv));
2483:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2484:   }
2485:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2486:   PetscFunctionReturn(PETSC_SUCCESS);
2487: }

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

2493:   Not Collective

2495:   Input Parameters:
2496: + mat  - the matrix
2497: . nrow - number of rows
2498: . irow - the row local indices
2499: . ncol - number of columns
2500: . icol - the column local indices
2501: . y    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2502:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2503: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2505:   Level: intermediate

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

2511:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2512:   options cannot be mixed without intervening calls to the assembly
2513:   routines.

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

2518:   Fortran Notes:
2519:   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2520: .vb
2521:   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2522: .ve

2524:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2526: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2527:           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2528: @*/
2529: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2530: {
2531:   PetscFunctionBeginHot;
2534:   MatCheckPreallocated(mat, 1);
2535:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2536:   PetscAssertPointer(irow, 3);
2537:   PetscAssertPointer(icol, 5);
2538:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2539:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2540:   if (PetscDefined(USE_DEBUG)) {
2541:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2542:     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);
2543:   }

2545:   if (mat->assembled) {
2546:     mat->was_assembled = PETSC_TRUE;
2547:     mat->assembled     = PETSC_FALSE;
2548:   }
2549:   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2550:     PetscInt irbs, rbs;
2551:     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2552:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2553:     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2554:   }
2555:   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2556:     PetscInt icbs, cbs;
2557:     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2558:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2559:     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2560:   }
2561:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2562:   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, y, addv);
2563:   else {
2564:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2565:     const PetscInt *irowm, *icolm;

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

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

2593:   Collective

2595:   Input Parameters:
2596: + mat - the matrix
2597: - x   - the vector to be multiplied

2599:   Output Parameter:
2600: . y - the result

2602:   Level: developer

2604:   Note:
2605:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2606:   call `MatMultDiagonalBlock`(A,y,y).

2608: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2609: @*/
2610: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2611: {
2612:   PetscFunctionBegin;

2618:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2619:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2620:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2621:   MatCheckPreallocated(mat, 1);

2623:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2624:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2625:   PetscFunctionReturn(PETSC_SUCCESS);
2626: }

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

2631:   Neighbor-wise Collective

2633:   Input Parameters:
2634: + mat - the matrix
2635: - x   - the vector to be multiplied

2637:   Output Parameter:
2638: . y - the result

2640:   Level: beginner

2642:   Note:
2643:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2644:   call `MatMult`(A,y,y).

2646: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2647: @*/
2648: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2649: {
2650:   PetscFunctionBegin;
2654:   VecCheckAssembled(x);
2656:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2657:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2658:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2659:   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);
2660:   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);
2661:   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);
2662:   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);
2663:   PetscCall(VecSetErrorIfLocked(y, 3));
2664:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2665:   MatCheckPreallocated(mat, 1);

2667:   PetscCall(VecLockReadPush(x));
2668:   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2669:   PetscUseTypeMethod(mat, mult, x, y);
2670:   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2671:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2672:   PetscCall(VecLockReadPop(x));
2673:   PetscFunctionReturn(PETSC_SUCCESS);
2674: }

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

2679:   Neighbor-wise Collective

2681:   Input Parameters:
2682: + mat - the matrix
2683: - x   - the vector to be multiplied

2685:   Output Parameter:
2686: . y - the result

2688:   Level: beginner

2690:   Notes:
2691:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2692:   call `MatMultTranspose`(A,y,y).

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

2697: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2698: @*/
2699: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2700: {
2701:   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;

2703:   PetscFunctionBegin;
2707:   VecCheckAssembled(x);

2710:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2711:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2712:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2713:   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);
2714:   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);
2715:   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);
2716:   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);
2717:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2718:   MatCheckPreallocated(mat, 1);

2720:   if (!mat->ops->multtranspose) {
2721:     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2722:     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);
2723:   } else op = mat->ops->multtranspose;
2724:   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2725:   PetscCall(VecLockReadPush(x));
2726:   PetscCall((*op)(mat, x, y));
2727:   PetscCall(VecLockReadPop(x));
2728:   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2729:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2730:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2731:   PetscFunctionReturn(PETSC_SUCCESS);
2732: }

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

2737:   Neighbor-wise Collective

2739:   Input Parameters:
2740: + mat - the matrix
2741: - x   - the vector to be multiplied

2743:   Output Parameter:
2744: . y - the result

2746:   Level: beginner

2748:   Notes:
2749:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2750:   call `MatMultHermitianTranspose`(A,y,y).

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

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

2756: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2757: @*/
2758: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2759: {
2760:   PetscFunctionBegin;

2766:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2767:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2768:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2769:   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);
2770:   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);
2771:   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);
2772:   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);
2773:   MatCheckPreallocated(mat, 1);

2775:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2776: #if defined(PETSC_USE_COMPLEX)
2777:   if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2778:     PetscCall(VecLockReadPush(x));
2779:     if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2780:     else PetscUseTypeMethod(mat, mult, x, y);
2781:     PetscCall(VecLockReadPop(x));
2782:   } else {
2783:     Vec w;
2784:     PetscCall(VecDuplicate(x, &w));
2785:     PetscCall(VecCopy(x, w));
2786:     PetscCall(VecConjugate(w));
2787:     PetscCall(MatMultTranspose(mat, w, y));
2788:     PetscCall(VecDestroy(&w));
2789:     PetscCall(VecConjugate(y));
2790:   }
2791:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2792: #else
2793:   PetscCall(MatMultTranspose(mat, x, y));
2794: #endif
2795:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2796:   PetscFunctionReturn(PETSC_SUCCESS);
2797: }

2799: /*@
2800:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2802:   Neighbor-wise Collective

2804:   Input Parameters:
2805: + mat - the matrix
2806: . v1  - the vector to be multiplied by `mat`
2807: - v2  - the vector to be added to the result

2809:   Output Parameter:
2810: . v3 - the result

2812:   Level: beginner

2814:   Note:
2815:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2816:   call `MatMultAdd`(A,v1,v2,v1).

2818: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2819: @*/
2820: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2821: {
2822:   PetscFunctionBegin;

2829:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2830:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2831:   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);
2832:   /* 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);
2833:      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); */
2834:   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);
2835:   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);
2836:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2837:   MatCheckPreallocated(mat, 1);

2839:   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2840:   PetscCall(VecLockReadPush(v1));
2841:   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2842:   PetscCall(VecLockReadPop(v1));
2843:   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2844:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2845:   PetscFunctionReturn(PETSC_SUCCESS);
2846: }

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

2851:   Neighbor-wise Collective

2853:   Input Parameters:
2854: + mat - the matrix
2855: . v1  - the vector to be multiplied by the transpose of the matrix
2856: - v2  - the vector to be added to the result

2858:   Output Parameter:
2859: . v3 - the result

2861:   Level: beginner

2863:   Note:
2864:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2865:   call `MatMultTransposeAdd`(A,v1,v2,v1).

2867: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2868: @*/
2869: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2870: {
2871:   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;

2873:   PetscFunctionBegin;

2880:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2881:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2882:   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);
2883:   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);
2884:   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);
2885:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2886:   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2887:   MatCheckPreallocated(mat, 1);

2889:   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2890:   PetscCall(VecLockReadPush(v1));
2891:   PetscCall((*op)(mat, v1, v2, v3));
2892:   PetscCall(VecLockReadPop(v1));
2893:   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2894:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2895:   PetscFunctionReturn(PETSC_SUCCESS);
2896: }

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

2901:   Neighbor-wise Collective

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

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

2911:   Level: beginner

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

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

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

2936:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2937:   PetscCall(VecLockReadPush(v1));
2938:   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2939:   else {
2940:     Vec w, z;
2941:     PetscCall(VecDuplicate(v1, &w));
2942:     PetscCall(VecCopy(v1, w));
2943:     PetscCall(VecConjugate(w));
2944:     PetscCall(VecDuplicate(v3, &z));
2945:     PetscCall(MatMultTranspose(mat, w, z));
2946:     PetscCall(VecDestroy(&w));
2947:     PetscCall(VecConjugate(z));
2948:     if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
2949:     else PetscCall(VecAXPY(v3, 1.0, z));
2950:     PetscCall(VecDestroy(&z));
2951:   }
2952:   PetscCall(VecLockReadPop(v1));
2953:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2954:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2955:   PetscFunctionReturn(PETSC_SUCCESS);
2956: }

2958: PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
2959: {
2960:   PetscFunctionBegin;
2961:   if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, &mat->dot_vec, NULL));
2962:   PetscCall(MatMult(mat, x, mat->dot_vec));
2963:   PetscCall(VecDot(mat->dot_vec, y, val));
2964:   PetscFunctionReturn(PETSC_SUCCESS);
2965: }

2967: PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
2968: {
2969:   PetscScalar sval;

2971:   PetscFunctionBegin;
2972:   PetscCall(MatADot_Default(mat, x, x, &sval));
2973:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
2974:   PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) < 100 * PETSC_MACHINE_EPSILON, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
2975:   *val = PetscSqrtReal(PetscRealPart(sval));
2976:   PetscFunctionReturn(PETSC_SUCCESS);
2977: }

2979: /*@
2980:   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)
2981:   positive definite.

2983:   Collective

2985:   Input Parameters:
2986: + mat - matrix used to define the inner product
2987: . x   - first vector
2988: - y   - second vector

2990:   Output Parameter:
2991: . val - the dot product with respect to `A`

2993:   Level: intermediate

2995:   Note:
2996:   For complex vectors, `MatADot()` computes
2997: $$
2998:   val = (x,y)_A = y^H A x,
2999: $$
3000:   where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3001:   inner product where the SECOND argument gets the complex conjugate.

3003: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3004: @*/
3005: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3006: {
3007:   PetscFunctionBegin;
3011:   VecCheckAssembled(x);
3013:   VecCheckAssembled(y);
3016:   PetscAssertPointer(val, 4);
3017:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3018:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3019:   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);
3020:   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);
3021:   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);
3022:   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);
3023:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3024:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3025:   MatCheckPreallocated(mat, 1);

3027:   PetscCall(VecLockReadPush(x));
3028:   PetscCall(VecLockReadPush(y));
3029:   PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3030:   PetscUseTypeMethod(mat, adot, x, y, val);
3031:   PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3032:   PetscCall(VecLockReadPop(y));
3033:   PetscCall(VecLockReadPop(x));
3034:   PetscFunctionReturn(PETSC_SUCCESS);
3035: }

3037: /*@
3038:   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)
3039:   positive definite.

3041:   Collective

3043:   Input Parameters:
3044: + mat - matrix used to define norm
3045: - x   - the vector to compute the norm of

3047:   Output Parameter:
3048: . val - the norm with respect to `A`

3050:   Level: intermediate

3052:   Note:
3053:   For complex vectors, `MatANorm()` computes
3054: $$
3055:   val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3056: $$
3057:   where $x^H$ denotes the conjugate transpose of `x`.

3059: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3060: @*/
3061: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3062: {
3063:   PetscFunctionBegin;
3067:   VecCheckAssembled(x);
3069:   PetscAssertPointer(val, 3);
3070:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3071:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3072:   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);
3073:   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);
3074:   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);
3075:   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);
3076:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3077:   MatCheckPreallocated(mat, 1);

3079:   PetscCall(VecLockReadPush(x));
3080:   PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3081:   PetscUseTypeMethod(mat, anorm, x, val);
3082:   PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3083:   PetscCall(VecLockReadPop(x));
3084:   PetscFunctionReturn(PETSC_SUCCESS);
3085: }

3087: /*@
3088:   MatGetFactorType - gets the type of factorization a matrix is

3090:   Not Collective

3092:   Input Parameter:
3093: . mat - the matrix

3095:   Output Parameter:
3096: . 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`

3098:   Level: intermediate

3100: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3101:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3102: @*/
3103: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3104: {
3105:   PetscFunctionBegin;
3108:   PetscAssertPointer(t, 2);
3109:   *t = mat->factortype;
3110:   PetscFunctionReturn(PETSC_SUCCESS);
3111: }

3113: /*@
3114:   MatSetFactorType - sets the type of factorization a matrix is

3116:   Logically Collective

3118:   Input Parameters:
3119: + mat - the matrix
3120: - 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`

3122:   Level: intermediate

3124: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3125:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3126: @*/
3127: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3128: {
3129:   PetscFunctionBegin;
3132:   mat->factortype = t;
3133:   PetscFunctionReturn(PETSC_SUCCESS);
3134: }

3136: /*@
3137:   MatGetInfo - Returns information about matrix storage (number of
3138:   nonzeros, memory, etc.).

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

3142:   Input Parameters:
3143: + mat  - the matrix
3144: - flag - flag indicating the type of parameters to be returned (`MAT_LOCAL` - local matrix, `MAT_GLOBAL_MAX` - maximum over all processors, `MAT_GLOBAL_SUM` - sum over all processors)

3146:   Output Parameter:
3147: . info - matrix information context

3149:   Options Database Key:
3150: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`

3152:   Level: intermediate

3154:   Notes:
3155:   The `MatInfo` context contains a variety of matrix data, including
3156:   number of nonzeros allocated and used, number of mallocs during
3157:   matrix assembly, etc.  Additional information for factored matrices
3158:   is provided (such as the fill ratio, number of mallocs during
3159:   factorization, etc.).

3161:   Example:
3162:   See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3163:   data within the `MatInfo` context.  For example,
3164: .vb
3165:       MatInfo info;
3166:       Mat     A;
3167:       double  mal, nz_a, nz_u;

3169:       MatGetInfo(A, MAT_LOCAL, &info);
3170:       mal  = info.mallocs;
3171:       nz_a = info.nz_allocated;
3172: .ve

3174: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3175: @*/
3176: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3177: {
3178:   PetscFunctionBegin;
3181:   PetscAssertPointer(info, 3);
3182:   MatCheckPreallocated(mat, 1);
3183:   PetscUseTypeMethod(mat, getinfo, flag, info);
3184:   PetscFunctionReturn(PETSC_SUCCESS);
3185: }

3187: /*
3188:    This is used by external packages where it is not easy to get the info from the actual
3189:    matrix factorization.
3190: */
3191: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3192: {
3193:   PetscFunctionBegin;
3194:   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3195:   PetscFunctionReturn(PETSC_SUCCESS);
3196: }

3198: /*@
3199:   MatLUFactor - Performs in-place LU factorization of matrix.

3201:   Collective

3203:   Input Parameters:
3204: + mat  - the matrix
3205: . row  - row permutation
3206: . col  - column permutation
3207: - info - options for factorization, includes
3208: .vb
3209:           fill - expected fill as ratio of original fill.
3210:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3211:                    Run with the option -info to determine an optimal value to use
3212: .ve

3214:   Level: developer

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

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

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

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

3230: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3231:           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3232: @*/
3233: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3234: {
3235:   MatFactorInfo tinfo;

3237:   PetscFunctionBegin;
3241:   if (info) PetscAssertPointer(info, 4);
3243:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3244:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3245:   MatCheckPreallocated(mat, 1);
3246:   if (!info) {
3247:     PetscCall(MatFactorInfoInitialize(&tinfo));
3248:     info = &tinfo;
3249:   }

3251:   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3252:   PetscUseTypeMethod(mat, lufactor, row, col, info);
3253:   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3254:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3255:   PetscFunctionReturn(PETSC_SUCCESS);
3256: }

3258: /*@
3259:   MatILUFactor - Performs in-place ILU factorization of matrix.

3261:   Collective

3263:   Input Parameters:
3264: + mat  - the matrix
3265: . row  - row permutation
3266: . col  - column permutation
3267: - info - structure containing
3268: .vb
3269:       levels - number of levels of fill.
3270:       expected fill - as ratio of original fill.
3271:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3272:                 missing diagonal entries)
3273: .ve

3275:   Level: developer

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

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

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

3289: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3290: @*/
3291: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3292: {
3293:   PetscFunctionBegin;
3297:   PetscAssertPointer(info, 4);
3299:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3300:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3301:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3302:   MatCheckPreallocated(mat, 1);

3304:   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3305:   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3306:   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3307:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3308:   PetscFunctionReturn(PETSC_SUCCESS);
3309: }

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

3315:   Collective

3317:   Input Parameters:
3318: + fact - the factor matrix obtained with `MatGetFactor()`
3319: . mat  - the matrix
3320: . row  - the row permutation
3321: . col  - the column permutation
3322: - info - options for factorization, includes
3323: .vb
3324:           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3325:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3326: .ve

3328:   Level: developer

3330:   Notes:
3331:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

3340: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3341: @*/
3342: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3343: {
3344:   MatFactorInfo tinfo;

3346:   PetscFunctionBegin;
3351:   if (info) PetscAssertPointer(info, 5);
3354:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3355:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3356:   MatCheckPreallocated(mat, 2);
3357:   if (!info) {
3358:     PetscCall(MatFactorInfoInitialize(&tinfo));
3359:     info = &tinfo;
3360:   }

3362:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3363:   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3364:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3365:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3366:   PetscFunctionReturn(PETSC_SUCCESS);
3367: }

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

3373:   Collective

3375:   Input Parameters:
3376: + fact - the factor matrix obtained with `MatGetFactor()`
3377: . mat  - the matrix
3378: - info - options for factorization

3380:   Level: developer

3382:   Notes:
3383:   See `MatLUFactor()` for in-place factorization.  See
3384:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

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

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

3393: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3394: @*/
3395: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3396: {
3397:   MatFactorInfo tinfo;

3399:   PetscFunctionBegin;
3404:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3405:   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,
3406:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3408:   MatCheckPreallocated(mat, 2);
3409:   if (!info) {
3410:     PetscCall(MatFactorInfoInitialize(&tinfo));
3411:     info = &tinfo;
3412:   }

3414:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3415:   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3416:   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3417:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3418:   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3419:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3420:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3421:   PetscFunctionReturn(PETSC_SUCCESS);
3422: }

3424: /*@
3425:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3426:   symmetric matrix.

3428:   Collective

3430:   Input Parameters:
3431: + mat  - the matrix
3432: . perm - row and column permutations
3433: - info - expected fill as ratio of original fill

3435:   Level: developer

3437:   Notes:
3438:   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3439:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

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

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

3448: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3449:           `MatGetOrdering()`
3450: @*/
3451: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3452: {
3453:   MatFactorInfo tinfo;

3455:   PetscFunctionBegin;
3458:   if (info) PetscAssertPointer(info, 3);
3460:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3461:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3462:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3463:   MatCheckPreallocated(mat, 1);
3464:   if (!info) {
3465:     PetscCall(MatFactorInfoInitialize(&tinfo));
3466:     info = &tinfo;
3467:   }

3469:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3470:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3471:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3472:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3473:   PetscFunctionReturn(PETSC_SUCCESS);
3474: }

3476: /*@
3477:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3478:   of a symmetric matrix.

3480:   Collective

3482:   Input Parameters:
3483: + fact - the factor matrix obtained with `MatGetFactor()`
3484: . mat  - the matrix
3485: . perm - row and column permutations
3486: - info - options for factorization, includes
3487: .vb
3488:           fill - expected fill as ratio of original fill.
3489:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3490:                    Run with the option -info to determine an optimal value to use
3491: .ve

3493:   Level: developer

3495:   Notes:
3496:   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3497:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

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

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

3506: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3507:           `MatGetOrdering()`
3508: @*/
3509: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3510: {
3511:   MatFactorInfo tinfo;

3513:   PetscFunctionBegin;
3517:   if (info) PetscAssertPointer(info, 4);
3520:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3521:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3522:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3523:   MatCheckPreallocated(mat, 2);
3524:   if (!info) {
3525:     PetscCall(MatFactorInfoInitialize(&tinfo));
3526:     info = &tinfo;
3527:   }

3529:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3530:   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3531:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3532:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3533:   PetscFunctionReturn(PETSC_SUCCESS);
3534: }

3536: /*@
3537:   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3538:   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3539:   `MatCholeskyFactorSymbolic()`.

3541:   Collective

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

3548:   Level: developer

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

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

3558: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3559: @*/
3560: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3561: {
3562:   MatFactorInfo tinfo;

3564:   PetscFunctionBegin;
3569:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3570:   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,
3571:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3572:   MatCheckPreallocated(mat, 2);
3573:   if (!info) {
3574:     PetscCall(MatFactorInfoInitialize(&tinfo));
3575:     info = &tinfo;
3576:   }

3578:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3579:   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3580:   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3581:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3582:   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3583:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3584:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3585:   PetscFunctionReturn(PETSC_SUCCESS);
3586: }

3588: /*@
3589:   MatQRFactor - Performs in-place QR factorization of matrix.

3591:   Collective

3593:   Input Parameters:
3594: + mat  - the matrix
3595: . col  - column permutation
3596: - info - options for factorization, includes
3597: .vb
3598:           fill - expected fill as ratio of original fill.
3599:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3600:                    Run with the option -info to determine an optimal value to use
3601: .ve

3603:   Level: developer

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

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

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

3616: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3617:           `MatSetUnfactored()`
3618: @*/
3619: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3620: {
3621:   PetscFunctionBegin;
3624:   if (info) PetscAssertPointer(info, 3);
3626:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3627:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3628:   MatCheckPreallocated(mat, 1);
3629:   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3630:   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3631:   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3632:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3633:   PetscFunctionReturn(PETSC_SUCCESS);
3634: }

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

3640:   Collective

3642:   Input Parameters:
3643: + fact - the factor matrix obtained with `MatGetFactor()`
3644: . mat  - the matrix
3645: . col  - column permutation
3646: - info - options for factorization, includes
3647: .vb
3648:           fill - expected fill as ratio of original fill.
3649:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3650:                    Run with the option -info to determine an optimal value to use
3651: .ve

3653:   Level: developer

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

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

3663: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3664: @*/
3665: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3666: {
3667:   MatFactorInfo tinfo;

3669:   PetscFunctionBegin;
3673:   if (info) PetscAssertPointer(info, 4);
3676:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3677:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3678:   MatCheckPreallocated(mat, 2);
3679:   if (!info) {
3680:     PetscCall(MatFactorInfoInitialize(&tinfo));
3681:     info = &tinfo;
3682:   }

3684:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3685:   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3686:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3687:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3688:   PetscFunctionReturn(PETSC_SUCCESS);
3689: }

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

3695:   Collective

3697:   Input Parameters:
3698: + fact - the factor matrix obtained with `MatGetFactor()`
3699: . mat  - the matrix
3700: - info - options for factorization

3702:   Level: developer

3704:   Notes:
3705:   See `MatQRFactor()` for in-place factorization.

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

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

3714: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3715: @*/
3716: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3717: {
3718:   MatFactorInfo tinfo;

3720:   PetscFunctionBegin;
3725:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3726:   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,
3727:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3729:   MatCheckPreallocated(mat, 2);
3730:   if (!info) {
3731:     PetscCall(MatFactorInfoInitialize(&tinfo));
3732:     info = &tinfo;
3733:   }

3735:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3736:   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3737:   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3738:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3739:   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3740:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3741:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3742:   PetscFunctionReturn(PETSC_SUCCESS);
3743: }

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

3748:   Neighbor-wise Collective

3750:   Input Parameters:
3751: + mat - the factored matrix
3752: - b   - the right-hand-side vector

3754:   Output Parameter:
3755: . x - the result vector

3757:   Level: developer

3759:   Notes:
3760:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3761:   call `MatSolve`(A,x,x).

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

3767: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3768: @*/
3769: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3770: {
3771:   PetscFunctionBegin;
3776:   PetscCheckSameComm(mat, 1, b, 2);
3777:   PetscCheckSameComm(mat, 1, x, 3);
3778:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3779:   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);
3780:   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);
3781:   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);
3782:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3783:   MatCheckPreallocated(mat, 1);

3785:   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3786:   PetscCall(VecFlag(x, mat->factorerrortype));
3787:   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3788:   else PetscUseTypeMethod(mat, solve, b, x);
3789:   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3790:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3791:   PetscFunctionReturn(PETSC_SUCCESS);
3792: }

3794: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3795: {
3796:   Vec      b, x;
3797:   PetscInt N;
3798:   PetscErrorCode (*f)(Mat, Vec, Vec);
3799:   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;

3801:   PetscFunctionBegin;
3802:   if (A->factorerrortype) {
3803:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3804:     PetscCall(MatSetInf(X));
3805:     PetscFunctionReturn(PETSC_SUCCESS);
3806:   }
3807:   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3808:   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3809:   PetscCall(MatBoundToCPU(A, &Abound));
3810:   if (!Abound) {
3811:     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3812:     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3813:   }
3814: #if PetscDefined(HAVE_CUDA)
3815:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3816:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3817: #elif PetscDefined(HAVE_HIP)
3818:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3819:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3820: #endif
3821:   PetscCall(MatGetSize(B, NULL, &N));
3822:   for (PetscInt i = 0; i < N; i++) {
3823:     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3824:     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3825:     PetscCall((*f)(A, b, x));
3826:     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3827:     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3828:   }
3829:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3830:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3831:   PetscFunctionReturn(PETSC_SUCCESS);
3832: }

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

3837:   Neighbor-wise Collective

3839:   Input Parameters:
3840: + A - the factored matrix
3841: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3843:   Output Parameter:
3844: . X - the result matrix (dense matrix)

3846:   Level: developer

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

3852: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3853: @*/
3854: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3855: {
3856:   PetscFunctionBegin;
3861:   PetscCheckSameComm(A, 1, B, 2);
3862:   PetscCheckSameComm(A, 1, X, 3);
3863:   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);
3864:   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);
3865:   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");
3866:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3867:   MatCheckPreallocated(A, 1);

3869:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3870:   if (!A->ops->matsolve) {
3871:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3872:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3873:   } else PetscUseTypeMethod(A, matsolve, B, X);
3874:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3875:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3876:   PetscFunctionReturn(PETSC_SUCCESS);
3877: }

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

3882:   Neighbor-wise Collective

3884:   Input Parameters:
3885: + A - the factored matrix
3886: - B - the right-hand-side matrix  (`MATDENSE` matrix)

3888:   Output Parameter:
3889: . X - the result matrix (dense matrix)

3891:   Level: developer

3893:   Note:
3894:   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3895:   call `MatMatSolveTranspose`(A,X,X).

3897: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3898: @*/
3899: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3900: {
3901:   PetscFunctionBegin;
3906:   PetscCheckSameComm(A, 1, B, 2);
3907:   PetscCheckSameComm(A, 1, X, 3);
3908:   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3909:   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);
3910:   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);
3911:   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);
3912:   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");
3913:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3914:   MatCheckPreallocated(A, 1);

3916:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3917:   if (!A->ops->matsolvetranspose) {
3918:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3919:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3920:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3921:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3922:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3923:   PetscFunctionReturn(PETSC_SUCCESS);
3924: }

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

3929:   Neighbor-wise Collective

3931:   Input Parameters:
3932: + A  - the factored matrix
3933: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

3935:   Output Parameter:
3936: . X - the result matrix (dense matrix)

3938:   Level: developer

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

3944: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3945: @*/
3946: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3947: {
3948:   PetscFunctionBegin;
3953:   PetscCheckSameComm(A, 1, Bt, 2);
3954:   PetscCheckSameComm(A, 1, X, 3);

3956:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3957:   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);
3958:   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);
3959:   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");
3960:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3961:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3962:   MatCheckPreallocated(A, 1);

3964:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3965:   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3966:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3967:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3968:   PetscFunctionReturn(PETSC_SUCCESS);
3969: }

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

3975:   Neighbor-wise Collective

3977:   Input Parameters:
3978: + mat - the factored matrix
3979: - b   - the right-hand-side vector

3981:   Output Parameter:
3982: . x - the result vector

3984:   Level: developer

3986:   Notes:
3987:   `MatSolve()` should be used for most applications, as it performs
3988:   a forward solve followed by a backward solve.

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

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

3999: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4000: @*/
4001: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4002: {
4003:   PetscFunctionBegin;
4008:   PetscCheckSameComm(mat, 1, b, 2);
4009:   PetscCheckSameComm(mat, 1, x, 3);
4010:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4011:   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);
4012:   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);
4013:   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);
4014:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4015:   MatCheckPreallocated(mat, 1);

4017:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4018:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4019:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4020:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4021:   PetscFunctionReturn(PETSC_SUCCESS);
4022: }

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

4028:   Neighbor-wise Collective

4030:   Input Parameters:
4031: + mat - the factored matrix
4032: - b   - the right-hand-side vector

4034:   Output Parameter:
4035: . x - the result vector

4037:   Level: developer

4039:   Notes:
4040:   `MatSolve()` should be used for most applications, as it performs
4041:   a forward solve followed by a backward solve.

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

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

4052: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4053: @*/
4054: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4055: {
4056:   PetscFunctionBegin;
4061:   PetscCheckSameComm(mat, 1, b, 2);
4062:   PetscCheckSameComm(mat, 1, x, 3);
4063:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4064:   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);
4065:   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);
4066:   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);
4067:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4068:   MatCheckPreallocated(mat, 1);

4070:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4071:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4072:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4073:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4074:   PetscFunctionReturn(PETSC_SUCCESS);
4075: }

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

4080:   Neighbor-wise Collective

4082:   Input Parameters:
4083: + mat - the factored matrix
4084: . b   - the right-hand-side vector
4085: - y   - the vector to be added to

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

4090:   Level: developer

4092:   Note:
4093:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4094:   call `MatSolveAdd`(A,x,y,x).

4096: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4097: @*/
4098: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4099: {
4100:   PetscScalar one = 1.0;
4101:   Vec         tmp;

4103:   PetscFunctionBegin;
4109:   PetscCheckSameComm(mat, 1, b, 2);
4110:   PetscCheckSameComm(mat, 1, y, 3);
4111:   PetscCheckSameComm(mat, 1, x, 4);
4112:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4113:   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);
4114:   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);
4115:   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);
4116:   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);
4117:   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);
4118:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4119:   MatCheckPreallocated(mat, 1);

4121:   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4122:   PetscCall(VecFlag(x, mat->factorerrortype));
4123:   if (mat->factorerrortype) {
4124:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4125:   } else if (mat->ops->solveadd) {
4126:     PetscUseTypeMethod(mat, solveadd, b, y, x);
4127:   } else {
4128:     /* do the solve then the add manually */
4129:     if (x != y) {
4130:       PetscCall(MatSolve(mat, b, x));
4131:       PetscCall(VecAXPY(x, one, y));
4132:     } else {
4133:       PetscCall(VecDuplicate(x, &tmp));
4134:       PetscCall(VecCopy(x, tmp));
4135:       PetscCall(MatSolve(mat, b, x));
4136:       PetscCall(VecAXPY(x, one, tmp));
4137:       PetscCall(VecDestroy(&tmp));
4138:     }
4139:   }
4140:   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4141:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4142:   PetscFunctionReturn(PETSC_SUCCESS);
4143: }

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

4148:   Neighbor-wise Collective

4150:   Input Parameters:
4151: + mat - the factored matrix
4152: - b   - the right-hand-side vector

4154:   Output Parameter:
4155: . x - the result vector

4157:   Level: developer

4159:   Notes:
4160:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4161:   call `MatSolveTranspose`(A,x,x).

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

4167: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4168: @*/
4169: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4170: {
4171:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

4173:   PetscFunctionBegin;
4178:   PetscCheckSameComm(mat, 1, b, 2);
4179:   PetscCheckSameComm(mat, 1, x, 3);
4180:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4181:   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);
4182:   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);
4183:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4184:   MatCheckPreallocated(mat, 1);
4185:   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4186:   PetscCall(VecFlag(x, mat->factorerrortype));
4187:   if (mat->factorerrortype) {
4188:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4189:   } else {
4190:     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4191:     PetscCall((*f)(mat, b, x));
4192:   }
4193:   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4194:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4195:   PetscFunctionReturn(PETSC_SUCCESS);
4196: }

4198: /*@
4199:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4200:   factored matrix.

4202:   Neighbor-wise Collective

4204:   Input Parameters:
4205: + mat - the factored matrix
4206: . b   - the right-hand-side vector
4207: - y   - the vector to be added to

4209:   Output Parameter:
4210: . x - the result vector

4212:   Level: developer

4214:   Note:
4215:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4216:   call `MatSolveTransposeAdd`(A,x,y,x).

4218: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4219: @*/
4220: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4221: {
4222:   PetscScalar one = 1.0;
4223:   Vec         tmp;
4224:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

4226:   PetscFunctionBegin;
4232:   PetscCheckSameComm(mat, 1, b, 2);
4233:   PetscCheckSameComm(mat, 1, y, 3);
4234:   PetscCheckSameComm(mat, 1, x, 4);
4235:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4236:   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);
4237:   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);
4238:   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);
4239:   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);
4240:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4241:   MatCheckPreallocated(mat, 1);

4243:   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4244:   PetscCall(VecFlag(x, mat->factorerrortype));
4245:   if (mat->factorerrortype) {
4246:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4247:   } else if (f) {
4248:     PetscCall((*f)(mat, b, y, x));
4249:   } else {
4250:     /* do the solve then the add manually */
4251:     if (x != y) {
4252:       PetscCall(MatSolveTranspose(mat, b, x));
4253:       PetscCall(VecAXPY(x, one, y));
4254:     } else {
4255:       PetscCall(VecDuplicate(x, &tmp));
4256:       PetscCall(VecCopy(x, tmp));
4257:       PetscCall(MatSolveTranspose(mat, b, x));
4258:       PetscCall(VecAXPY(x, one, tmp));
4259:       PetscCall(VecDestroy(&tmp));
4260:     }
4261:   }
4262:   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4263:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4264:   PetscFunctionReturn(PETSC_SUCCESS);
4265: }

4267: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4268: /*@
4269:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4271:   Neighbor-wise Collective

4273:   Input Parameters:
4274: + mat   - the matrix
4275: . b     - the right-hand side
4276: . omega - the relaxation factor
4277: . flag  - flag indicating the type of SOR (see below)
4278: . shift - diagonal shift
4279: . its   - the number of iterations
4280: - lits  - the number of local iterations

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

4285:   SOR Flags:
4286: +     `SOR_FORWARD_SWEEP` - forward SOR
4287: .     `SOR_BACKWARD_SWEEP` - backward SOR
4288: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4289: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4290: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4291: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4292: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4293: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4294: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4296:   Level: developer

4298:   Notes:
4299:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4300:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4301:   on each processor.

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

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

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

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

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

4318: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4319: @*/
4320: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4321: {
4322:   PetscFunctionBegin;
4327:   PetscCheckSameComm(mat, 1, b, 2);
4328:   PetscCheckSameComm(mat, 1, x, 8);
4329:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4330:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4331:   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);
4332:   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);
4333:   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);
4334:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4335:   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4336:   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");

4338:   MatCheckPreallocated(mat, 1);
4339:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4340:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4341:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4342:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4343:   PetscFunctionReturn(PETSC_SUCCESS);
4344: }

4346: /*
4347:       Default matrix copy routine.
4348: */
4349: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4350: {
4351:   PetscInt           i, rstart = 0, rend = 0, nz;
4352:   const PetscInt    *cwork;
4353:   const PetscScalar *vwork;

4355:   PetscFunctionBegin;
4356:   if (B->assembled) PetscCall(MatZeroEntries(B));
4357:   if (str == SAME_NONZERO_PATTERN) {
4358:     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4359:     for (i = rstart; i < rend; i++) {
4360:       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4361:       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4362:       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4363:     }
4364:   } else {
4365:     PetscCall(MatAYPX(B, 0.0, A, str));
4366:   }
4367:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4368:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4369:   PetscFunctionReturn(PETSC_SUCCESS);
4370: }

4372: /*@
4373:   MatCopy - Copies a matrix to another matrix.

4375:   Collective

4377:   Input Parameters:
4378: + A   - the matrix
4379: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4381:   Output Parameter:
4382: . B - where the copy is put

4384:   Level: intermediate

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

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

4393: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4394: @*/
4395: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4396: {
4397:   PetscInt i;

4399:   PetscFunctionBegin;
4404:   PetscCheckSameComm(A, 1, B, 2);
4405:   MatCheckPreallocated(B, 2);
4406:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4407:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4408:   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,
4409:              A->cmap->N, B->cmap->N);
4410:   MatCheckPreallocated(A, 1);
4411:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4413:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4414:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4415:   else PetscCall(MatCopy_Basic(A, B, str));

4417:   B->stencil.dim = A->stencil.dim;
4418:   B->stencil.noc = A->stencil.noc;
4419:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4420:     B->stencil.dims[i]   = A->stencil.dims[i];
4421:     B->stencil.starts[i] = A->stencil.starts[i];
4422:   }

4424:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4425:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4426:   PetscFunctionReturn(PETSC_SUCCESS);
4427: }

4429: /*@
4430:   MatConvert - Converts a matrix to another matrix, either of the same
4431:   or different type.

4433:   Collective

4435:   Input Parameters:
4436: + mat     - the matrix
4437: . newtype - new matrix type.  Use `MATSAME` to create a new matrix of the
4438:             same type as the original matrix.
4439: - reuse   - denotes if the destination matrix is to be created or reused.
4440:             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
4441:             `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).

4443:   Output Parameter:
4444: . M - pointer to place new matrix

4446:   Level: intermediate

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

4453:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4454:   the MPI communicator of the generated matrix is always the same as the communicator
4455:   of the input matrix.

4457: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4458: @*/
4459: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4460: {
4461:   PetscBool  sametype, issame, flg;
4462:   PetscBool3 issymmetric, ishermitian, isspd;
4463:   char       convname[256], mtype[256];
4464:   Mat        B;

4466:   PetscFunctionBegin;
4469:   PetscAssertPointer(M, 4);
4470:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4471:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4472:   MatCheckPreallocated(mat, 1);

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

4477:   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4478:   PetscCall(PetscStrcmp(newtype, "same", &issame));
4479:   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4480:   if (reuse == MAT_REUSE_MATRIX) {
4482:     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4483:   }

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

4490:   /* Cache Mat options because some converters use MatHeaderReplace() */
4491:   issymmetric = mat->symmetric;
4492:   ishermitian = mat->hermitian;
4493:   isspd       = mat->spd;

4495:   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4496:     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4497:     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4498:   } else {
4499:     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4500:     const char *prefix[3]                                 = {"seq", "mpi", ""};
4501:     PetscInt    i;
4502:     /*
4503:        Order of precedence:
4504:        0) See if newtype is a superclass of the current matrix.
4505:        1) See if a specialized converter is known to the current matrix.
4506:        2) See if a specialized converter is known to the desired matrix class.
4507:        3) See if a good general converter is registered for the desired class
4508:           (as of 6/27/03 only MATMPIADJ falls into this category).
4509:        4) See if a good general converter is known for the current matrix.
4510:        5) Use a really basic converter.
4511:     */

4513:     /* 0) See if newtype is a superclass of the current matrix.
4514:           i.e mat is mpiaij and newtype is aij */
4515:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4516:       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4517:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4518:       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4519:       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4520:       if (flg) {
4521:         if (reuse == MAT_INPLACE_MATRIX) {
4522:           PetscCall(PetscInfo(mat, "Early return\n"));
4523:           PetscFunctionReturn(PETSC_SUCCESS);
4524:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4525:           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4526:           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4527:           PetscFunctionReturn(PETSC_SUCCESS);
4528:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4529:           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4530:           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4531:           PetscFunctionReturn(PETSC_SUCCESS);
4532:         }
4533:       }
4534:     }
4535:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4536:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4537:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4538:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4539:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4540:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4541:       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4542:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4543:       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4544:       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4545:       if (conv) goto foundconv;
4546:     }

4548:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4549:     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4550:     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4551:     PetscCall(MatSetType(B, newtype));
4552:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4553:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4554:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4555:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4556:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4557:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4558:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4559:       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4560:       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4561:       if (conv) {
4562:         PetscCall(MatDestroy(&B));
4563:         goto foundconv;
4564:       }
4565:     }

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

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

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

4582:   foundconv:
4583:     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4584:     PetscCall((*conv)(mat, newtype, reuse, M));
4585:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4586:       /* the block sizes must be same if the mappings are copied over */
4587:       (*M)->rmap->bs = mat->rmap->bs;
4588:       (*M)->cmap->bs = mat->cmap->bs;
4589:       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4590:       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4591:       (*M)->rmap->mapping = mat->rmap->mapping;
4592:       (*M)->cmap->mapping = mat->cmap->mapping;
4593:     }
4594:     (*M)->stencil.dim = mat->stencil.dim;
4595:     (*M)->stencil.noc = mat->stencil.noc;
4596:     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4597:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4598:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4599:     }
4600:     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4601:   }
4602:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));

4604:   /* Reset Mat options */
4605:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4606:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4607:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4608:   PetscFunctionReturn(PETSC_SUCCESS);
4609: }

4611: /*@
4612:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4614:   Not Collective

4616:   Input Parameter:
4617: . mat - the matrix, must be a factored matrix

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

4622:   Level: intermediate

4624: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4625: @*/
4626: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4627: {
4628:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4630:   PetscFunctionBegin;
4633:   PetscAssertPointer(type, 2);
4634:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4635:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4636:   if (conv) PetscCall((*conv)(mat, type));
4637:   else *type = MATSOLVERPETSC;
4638:   PetscFunctionReturn(PETSC_SUCCESS);
4639: }

4641: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4642: struct _MatSolverTypeForSpecifcType {
4643:   MatType mtype;
4644:   /* no entry for MAT_FACTOR_NONE */
4645:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4646:   MatSolverTypeForSpecifcType next;
4647: };

4649: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4650: struct _MatSolverTypeHolder {
4651:   char                       *name;
4652:   MatSolverTypeForSpecifcType handlers;
4653:   MatSolverTypeHolder         next;
4654: };

4656: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4658: /*@C
4659:   MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type

4661:   Logically Collective, No Fortran Support

4663:   Input Parameters:
4664: + package      - name of the package, for example `petsc` or `superlu`
4665: . mtype        - the matrix type that works with this package
4666: . ftype        - the type of factorization supported by the package
4667: - createfactor - routine that will create the factored matrix ready to be used

4669:   Level: developer

4671: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4672:   `MatGetFactor()`
4673: @*/
4674: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4675: {
4676:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4677:   PetscBool                   flg;
4678:   MatSolverTypeForSpecifcType inext, iprev = NULL;

4680:   PetscFunctionBegin;
4681:   PetscCall(MatInitializePackage());
4682:   if (!next) {
4683:     PetscCall(PetscNew(&MatSolverTypeHolders));
4684:     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4685:     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4686:     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4687:     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4688:     PetscFunctionReturn(PETSC_SUCCESS);
4689:   }
4690:   while (next) {
4691:     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4692:     if (flg) {
4693:       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4694:       inext = next->handlers;
4695:       while (inext) {
4696:         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4697:         if (flg) {
4698:           inext->createfactor[(int)ftype - 1] = createfactor;
4699:           PetscFunctionReturn(PETSC_SUCCESS);
4700:         }
4701:         iprev = inext;
4702:         inext = inext->next;
4703:       }
4704:       PetscCall(PetscNew(&iprev->next));
4705:       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4706:       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4707:       PetscFunctionReturn(PETSC_SUCCESS);
4708:     }
4709:     prev = next;
4710:     next = next->next;
4711:   }
4712:   PetscCall(PetscNew(&prev->next));
4713:   PetscCall(PetscStrallocpy(package, &prev->next->name));
4714:   PetscCall(PetscNew(&prev->next->handlers));
4715:   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4716:   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4717:   PetscFunctionReturn(PETSC_SUCCESS);
4718: }

4720: /*@C
4721:   MatSolverTypeGet - Gets the function that creates the factor matrix if it exist

4723:   Input Parameters:
4724: + 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
4725: . ftype - the type of factorization supported by the type
4726: - mtype - the matrix type that works with this type

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

4733:   Calling sequence of `createfactor`:
4734: + A     - the matrix providing the factor matrix
4735: . ftype - the `MatFactorType` of the factor requested
4736: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4738:   Level: developer

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

4745: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4746:           `MatInitializePackage()`
4747: @*/
4748: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4749: {
4750:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4751:   PetscBool                   flg;
4752:   MatSolverTypeForSpecifcType inext;

4754:   PetscFunctionBegin;
4755:   if (foundtype) *foundtype = PETSC_FALSE;
4756:   if (foundmtype) *foundmtype = PETSC_FALSE;
4757:   if (createfactor) *createfactor = NULL;

4759:   if (type) {
4760:     while (next) {
4761:       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4762:       if (flg) {
4763:         if (foundtype) *foundtype = PETSC_TRUE;
4764:         inext = next->handlers;
4765:         while (inext) {
4766:           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4767:           if (flg) {
4768:             if (foundmtype) *foundmtype = PETSC_TRUE;
4769:             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4770:             PetscFunctionReturn(PETSC_SUCCESS);
4771:           }
4772:           inext = inext->next;
4773:         }
4774:       }
4775:       next = next->next;
4776:     }
4777:   } else {
4778:     while (next) {
4779:       inext = next->handlers;
4780:       while (inext) {
4781:         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4782:         if (flg && inext->createfactor[(int)ftype - 1]) {
4783:           if (foundtype) *foundtype = PETSC_TRUE;
4784:           if (foundmtype) *foundmtype = PETSC_TRUE;
4785:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4786:           PetscFunctionReturn(PETSC_SUCCESS);
4787:         }
4788:         inext = inext->next;
4789:       }
4790:       next = next->next;
4791:     }
4792:     /* try with base classes inext->mtype */
4793:     next = MatSolverTypeHolders;
4794:     while (next) {
4795:       inext = next->handlers;
4796:       while (inext) {
4797:         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4798:         if (flg && inext->createfactor[(int)ftype - 1]) {
4799:           if (foundtype) *foundtype = PETSC_TRUE;
4800:           if (foundmtype) *foundmtype = PETSC_TRUE;
4801:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4802:           PetscFunctionReturn(PETSC_SUCCESS);
4803:         }
4804:         inext = inext->next;
4805:       }
4806:       next = next->next;
4807:     }
4808:   }
4809:   PetscFunctionReturn(PETSC_SUCCESS);
4810: }

4812: PetscErrorCode MatSolverTypeDestroy(void)
4813: {
4814:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4815:   MatSolverTypeForSpecifcType inext, iprev;

4817:   PetscFunctionBegin;
4818:   while (next) {
4819:     PetscCall(PetscFree(next->name));
4820:     inext = next->handlers;
4821:     while (inext) {
4822:       PetscCall(PetscFree(inext->mtype));
4823:       iprev = inext;
4824:       inext = inext->next;
4825:       PetscCall(PetscFree(iprev));
4826:     }
4827:     prev = next;
4828:     next = next->next;
4829:     PetscCall(PetscFree(prev));
4830:   }
4831:   MatSolverTypeHolders = NULL;
4832:   PetscFunctionReturn(PETSC_SUCCESS);
4833: }

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

4838:   Logically Collective

4840:   Input Parameter:
4841: . mat - the matrix

4843:   Output Parameter:
4844: . flg - `PETSC_TRUE` if uses the ordering

4846:   Level: developer

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

4852: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4853: @*/
4854: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4855: {
4856:   PetscFunctionBegin;
4857:   *flg = mat->canuseordering;
4858:   PetscFunctionReturn(PETSC_SUCCESS);
4859: }

4861: /*@
4862:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4864:   Logically Collective

4866:   Input Parameters:
4867: + mat   - the matrix obtained with `MatGetFactor()`
4868: - ftype - the factorization type to be used

4870:   Output Parameter:
4871: . otype - the preferred ordering type

4873:   Level: developer

4875: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4876: @*/
4877: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4878: {
4879:   PetscFunctionBegin;
4880:   *otype = mat->preferredordering[ftype];
4881:   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4882:   PetscFunctionReturn(PETSC_SUCCESS);
4883: }

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

4889:   Collective

4891:   Input Parameters:
4892: + mat   - the matrix
4893: . 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
4894:           the other criteria is returned
4895: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

4905:   Level: intermediate

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

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

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

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

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

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

4930: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
4931:           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
4932:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
4933:           `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4934:           `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
4935: @*/
4936: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
4937: {
4938:   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
4939:   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);

4941:   PetscFunctionBegin;

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

4948:   PetscCall(MatIsShell(mat, &shell));
4949:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
4950:   if (hasop) {
4951:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
4952:     PetscFunctionReturn(PETSC_SUCCESS);
4953:   }

4955:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
4956:   if (!foundtype) {
4957:     if (type) {
4958:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate solver type %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s", type, MatFactorTypes[ftype],
4959:               ((PetscObject)mat)->type_name, type);
4960:     } else {
4961:       SETERRQ(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);
4962:     }
4963:   }
4964:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
4965:   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);

4967:   PetscCall((*conv)(mat, ftype, f));
4968:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
4969:   PetscFunctionReturn(PETSC_SUCCESS);
4970: }

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

4975:   Not Collective

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

4982:   Output Parameter:
4983: . flg - PETSC_TRUE if the factorization is available

4985:   Level: intermediate

4987:   Notes:
4988:   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4989:   such as pastix, superlu, mumps etc.

4991:   PETSc must have been ./configure to use the external solver, using the option --download-package

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

4996: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
4997:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
4998: @*/
4999: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5000: {
5001:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5003:   PetscFunctionBegin;
5005:   PetscAssertPointer(flg, 4);

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

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

5013:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5014:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5015:   PetscFunctionReturn(PETSC_SUCCESS);
5016: }

5018: /*@
5019:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5021:   Collective

5023:   Input Parameters:
5024: + mat - the matrix
5025: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5026:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5028:   Output Parameter:
5029: . M - pointer to place new matrix

5031:   Level: intermediate

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

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

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

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

5044: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5045: @*/
5046: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5047: {
5048:   Mat               B;
5049:   VecType           vtype;
5050:   PetscInt          i;
5051:   PetscObject       dm, container_h, container_d;
5052:   PetscErrorCodeFn *viewf;

5054:   PetscFunctionBegin;
5057:   PetscAssertPointer(M, 3);
5058:   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5059:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5060:   MatCheckPreallocated(mat, 1);

5062:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5063:   PetscUseTypeMethod(mat, duplicate, op, M);
5064:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5065:   B = *M;

5067:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5068:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5069:   PetscCall(MatGetVecType(mat, &vtype));
5070:   PetscCall(MatSetVecType(B, vtype));

5072:   B->stencil.dim = mat->stencil.dim;
5073:   B->stencil.noc = mat->stencil.noc;
5074:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5075:     B->stencil.dims[i]   = mat->stencil.dims[i];
5076:     B->stencil.starts[i] = mat->stencil.starts[i];
5077:   }

5079:   B->nooffproczerorows = mat->nooffproczerorows;
5080:   B->nooffprocentries  = mat->nooffprocentries;

5082:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5083:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5084:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5085:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5086:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5087:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5088:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5089:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5090:   PetscFunctionReturn(PETSC_SUCCESS);
5091: }

5093: /*@
5094:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5096:   Logically Collective

5098:   Input Parameter:
5099: . mat - the matrix

5101:   Output Parameter:
5102: . v - the diagonal of the matrix

5104:   Level: intermediate

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

5111:   Currently only correct in parallel for square matrices.

5113: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5114: @*/
5115: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5116: {
5117:   PetscFunctionBegin;
5121:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5122:   MatCheckPreallocated(mat, 1);
5123:   if (PetscDefined(USE_DEBUG)) {
5124:     PetscInt nv, row, col, ndiag;

5126:     PetscCall(VecGetLocalSize(v, &nv));
5127:     PetscCall(MatGetLocalSize(mat, &row, &col));
5128:     ndiag = PetscMin(row, col);
5129:     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);
5130:   }

5132:   PetscUseTypeMethod(mat, getdiagonal, v);
5133:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5134:   PetscFunctionReturn(PETSC_SUCCESS);
5135: }

5137: /*@
5138:   MatGetRowMin - Gets the minimum value (of the real part) of each
5139:   row of the matrix

5141:   Logically Collective

5143:   Input Parameter:
5144: . mat - the matrix

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

5150:   Level: intermediate

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

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

5158: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5159:           `MatGetRowMax()`
5160: @*/
5161: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5162: {
5163:   PetscFunctionBegin;
5167:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5169:   if (!mat->cmap->N) {
5170:     PetscCall(VecSet(v, PETSC_MAX_REAL));
5171:     if (idx) {
5172:       PetscInt i, m = mat->rmap->n;
5173:       for (i = 0; i < m; i++) idx[i] = -1;
5174:     }
5175:   } else {
5176:     MatCheckPreallocated(mat, 1);
5177:   }
5178:   PetscUseTypeMethod(mat, getrowmin, v, idx);
5179:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5180:   PetscFunctionReturn(PETSC_SUCCESS);
5181: }

5183: /*@
5184:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5185:   row of the matrix

5187:   Logically Collective

5189:   Input Parameter:
5190: . mat - the matrix

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

5196:   Level: intermediate

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

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

5204: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5205: @*/
5206: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5207: {
5208:   PetscFunctionBegin;
5212:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5213:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

5215:   if (!mat->cmap->N) {
5216:     PetscCall(VecSet(v, 0.0));
5217:     if (idx) {
5218:       PetscInt i, m = mat->rmap->n;
5219:       for (i = 0; i < m; i++) idx[i] = -1;
5220:     }
5221:   } else {
5222:     MatCheckPreallocated(mat, 1);
5223:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5224:     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5225:   }
5226:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5227:   PetscFunctionReturn(PETSC_SUCCESS);
5228: }

5230: /*@
5231:   MatGetRowMax - Gets the maximum value (of the real part) of each
5232:   row of the matrix

5234:   Logically Collective

5236:   Input Parameter:
5237: . mat - the matrix

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

5243:   Level: intermediate

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

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

5251: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5252: @*/
5253: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5254: {
5255:   PetscFunctionBegin;
5259:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5261:   if (!mat->cmap->N) {
5262:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5263:     if (idx) {
5264:       PetscInt i, m = mat->rmap->n;
5265:       for (i = 0; i < m; i++) idx[i] = -1;
5266:     }
5267:   } else {
5268:     MatCheckPreallocated(mat, 1);
5269:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5270:   }
5271:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5272:   PetscFunctionReturn(PETSC_SUCCESS);
5273: }

5275: /*@
5276:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5277:   row of the matrix

5279:   Logically Collective

5281:   Input Parameter:
5282: . mat - the matrix

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

5288:   Level: intermediate

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

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

5296: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5297: @*/
5298: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5299: {
5300:   PetscFunctionBegin;
5304:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5306:   if (!mat->cmap->N) {
5307:     PetscCall(VecSet(v, 0.0));
5308:     if (idx) {
5309:       PetscInt i, m = mat->rmap->n;
5310:       for (i = 0; i < m; i++) idx[i] = -1;
5311:     }
5312:   } else {
5313:     MatCheckPreallocated(mat, 1);
5314:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5315:     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5316:   }
5317:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5318:   PetscFunctionReturn(PETSC_SUCCESS);
5319: }

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

5324:   Logically Collective

5326:   Input Parameter:
5327: . mat - the matrix

5329:   Output Parameter:
5330: . v - the vector for storing the sum

5332:   Level: intermediate

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

5336: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5337: @*/
5338: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5339: {
5340:   PetscFunctionBegin;
5344:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5346:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5347:   else {
5348:     MatCheckPreallocated(mat, 1);
5349:     PetscUseTypeMethod(mat, getrowsumabs, v);
5350:   }
5351:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5352:   PetscFunctionReturn(PETSC_SUCCESS);
5353: }

5355: /*@
5356:   MatGetRowSum - Gets the sum of each row of the matrix

5358:   Logically or Neighborhood Collective

5360:   Input Parameter:
5361: . mat - the matrix

5363:   Output Parameter:
5364: . v - the vector for storing the sum of rows

5366:   Level: intermediate

5368:   Note:
5369:   This code is slow since it is not currently specialized for different formats

5371: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5372: @*/
5373: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5374: {
5375:   Vec ones;

5377:   PetscFunctionBegin;
5381:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5382:   MatCheckPreallocated(mat, 1);
5383:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5384:   PetscCall(VecSet(ones, 1.));
5385:   PetscCall(MatMult(mat, ones, v));
5386:   PetscCall(VecDestroy(&ones));
5387:   PetscFunctionReturn(PETSC_SUCCESS);
5388: }

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

5394:   Collective

5396:   Input Parameter:
5397: . mat - the matrix to provide the transpose

5399:   Output Parameter:
5400: . 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

5402:   Level: advanced

5404:   Note:
5405:   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
5406:   routine allows bypassing that call.

5408: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5409: @*/
5410: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5411: {
5412:   MatParentState *rb = NULL;

5414:   PetscFunctionBegin;
5415:   PetscCall(PetscNew(&rb));
5416:   rb->id    = ((PetscObject)mat)->id;
5417:   rb->state = 0;
5418:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5419:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5420:   PetscFunctionReturn(PETSC_SUCCESS);
5421: }

5423: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5424: {
5425:   PetscContainer  rB                        = NULL;
5426:   MatParentState *rb                        = NULL;
5427:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

5429:   PetscFunctionBegin;
5432:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5433:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5434:   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5435:   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5436:   MatCheckPreallocated(mat, 1);
5437:   if (reuse == MAT_REUSE_MATRIX) {
5438:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5439:     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5440:     PetscCall(PetscContainerGetPointer(rB, &rb));
5441:     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5442:     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5443:   }

5445:   if (conjugate) {
5446:     f = mat->ops->hermitiantranspose;
5447:     if (f) PetscCall((*f)(mat, reuse, B));
5448:   }
5449:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5450:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5451:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5452:       PetscUseTypeMethod(mat, transpose, reuse, B);
5453:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5454:     }
5455:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5456:     if (conjugate) PetscCall(MatConjugate(*B));
5457:   }

5459:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5460:   if (reuse != MAT_INPLACE_MATRIX) {
5461:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5462:     PetscCall(PetscContainerGetPointer(rB, &rb));
5463:     rb->state        = ((PetscObject)mat)->state;
5464:     rb->nonzerostate = mat->nonzerostate;
5465:   }
5466:   PetscFunctionReturn(PETSC_SUCCESS);
5467: }

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

5472:   Collective

5474:   Input Parameters:
5475: + mat   - the matrix to transpose
5476: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5478:   Output Parameter:
5479: . B - the transpose of the matrix

5481:   Level: intermediate

5483:   Notes:
5484:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

5498: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5499:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5500: @*/
5501: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5502: {
5503:   PetscFunctionBegin;
5504:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5505:   PetscFunctionReturn(PETSC_SUCCESS);
5506: }

5508: /*@
5509:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5511:   Collective

5513:   Input Parameter:
5514: . A - the matrix to transpose

5516:   Output Parameter:
5517: . 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
5518:       numerical portion.

5520:   Level: intermediate

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

5525: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5526: @*/
5527: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5528: {
5529:   PetscFunctionBegin;
5532:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5533:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5534:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5535:   PetscUseTypeMethod(A, transposesymbolic, B);
5536:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5538:   PetscCall(MatTransposeSetPrecursor(A, *B));
5539:   PetscFunctionReturn(PETSC_SUCCESS);
5540: }

5542: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5543: {
5544:   PetscContainer  rB;
5545:   MatParentState *rb;

5547:   PetscFunctionBegin;
5550:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5551:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5552:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5553:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5554:   PetscCall(PetscContainerGetPointer(rB, &rb));
5555:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5556:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5557:   PetscFunctionReturn(PETSC_SUCCESS);
5558: }

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

5564:   Collective

5566:   Input Parameters:
5567: + A   - the matrix to test
5568: . B   - the matrix to test against, this can equal the first parameter
5569: - tol - tolerance, differences between entries smaller than this are counted as zero

5571:   Output Parameter:
5572: . flg - the result

5574:   Level: intermediate

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

5580: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5581: @*/
5582: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5583: {
5584:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5586:   PetscFunctionBegin;
5589:   PetscAssertPointer(flg, 4);
5590:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5591:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5592:   *flg = PETSC_FALSE;
5593:   if (f && g) {
5594:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5595:     PetscCall((*f)(A, B, tol, flg));
5596:   } else {
5597:     MatType mattype;

5599:     PetscCall(MatGetType(f ? B : A, &mattype));
5600:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5601:   }
5602:   PetscFunctionReturn(PETSC_SUCCESS);
5603: }

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

5608:   Collective

5610:   Input Parameters:
5611: + mat   - the matrix to transpose and complex conjugate
5612: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5614:   Output Parameter:
5615: . B - the Hermitian transpose

5617:   Level: intermediate

5619: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5620: @*/
5621: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5622: {
5623:   PetscFunctionBegin;
5624:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_TRUE));
5625:   PetscFunctionReturn(PETSC_SUCCESS);
5626: }

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

5631:   Collective

5633:   Input Parameters:
5634: + A   - the matrix to test
5635: . B   - the matrix to test against, this can equal the first parameter
5636: - tol - tolerance, differences between entries smaller than this are counted as zero

5638:   Output Parameter:
5639: . flg - the result

5641:   Level: intermediate

5643:   Notes:
5644:   Only available for `MATAIJ` matrices.

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

5650: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5651: @*/
5652: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5653: {
5654:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5656:   PetscFunctionBegin;
5659:   PetscAssertPointer(flg, 4);
5660:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5661:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5662:   if (f && g) {
5663:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5664:     PetscCall((*f)(A, B, tol, flg));
5665:   } else {
5666:     MatType mattype;

5668:     PetscCall(MatGetType(f ? B : A, &mattype));
5669:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5670:   }
5671:   PetscFunctionReturn(PETSC_SUCCESS);
5672: }

5674: /*@
5675:   MatPermute - Creates a new matrix with rows and columns permuted from the
5676:   original.

5678:   Collective

5680:   Input Parameters:
5681: + mat - the matrix to permute
5682: . row - row permutation, each processor supplies only the permutation for its rows
5683: - col - column permutation, each processor supplies only the permutation for its columns

5685:   Output Parameter:
5686: . B - the permuted matrix

5688:   Level: advanced

5690:   Note:
5691:   The index sets map from row/col of permuted matrix to row/col of original matrix.
5692:   The index sets should be on the same communicator as mat and have the same local sizes.

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

5699: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5700: @*/
5701: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5702: {
5703:   PetscFunctionBegin;
5708:   PetscAssertPointer(B, 4);
5709:   PetscCheckSameComm(mat, 1, row, 2);
5710:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5711:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5712:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5713:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5714:   MatCheckPreallocated(mat, 1);

5716:   if (mat->ops->permute) {
5717:     PetscUseTypeMethod(mat, permute, row, col, B);
5718:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5719:   } else {
5720:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5721:   }
5722:   PetscFunctionReturn(PETSC_SUCCESS);
5723: }

5725: /*@
5726:   MatEqual - Compares two matrices.

5728:   Collective

5730:   Input Parameters:
5731: + A - the first matrix
5732: - B - the second matrix

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

5737:   Level: intermediate

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

5743: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5744: @*/
5745: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5746: {
5747:   PetscFunctionBegin;
5752:   PetscAssertPointer(flg, 3);
5753:   PetscCheckSameComm(A, 1, B, 2);
5754:   MatCheckPreallocated(A, 1);
5755:   MatCheckPreallocated(B, 2);
5756:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5757:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5758:   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,
5759:              B->cmap->N);
5760:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5761:   else PetscCall(MatMultEqual(A, B, 10, flg));
5762:   PetscFunctionReturn(PETSC_SUCCESS);
5763: }

5765: /*@
5766:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5767:   matrices that are stored as vectors.  Either of the two scaling
5768:   matrices can be `NULL`.

5770:   Collective

5772:   Input Parameters:
5773: + mat - the matrix to be scaled
5774: . l   - the left scaling vector (or `NULL`)
5775: - r   - the right scaling vector (or `NULL`)

5777:   Level: intermediate

5779:   Note:
5780:   `MatDiagonalScale()` computes $A = LAR$, where
5781:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5782:   The L scales the rows of the matrix, the R scales the columns of the matrix.

5784: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5785: @*/
5786: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5787: {
5788:   PetscBool flg = PETSC_FALSE;

5790:   PetscFunctionBegin;
5793:   if (l) {
5795:     PetscCheckSameComm(mat, 1, l, 2);
5796:   }
5797:   if (r) {
5799:     PetscCheckSameComm(mat, 1, r, 3);
5800:   }
5801:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5802:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5803:   MatCheckPreallocated(mat, 1);
5804:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5806:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5807:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5808:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5809:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5810:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5811:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5812:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5813:       if (!flg) {
5814:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5815:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format, left and right scaling vectors must be the same");
5816:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5817:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5818:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5819:       }
5820:     }
5821:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5822:       flg = PETSC_FALSE;
5823:       if (l && r) {
5824:         Vec conjugate;

5826:         PetscCall(VecDuplicate(l, &conjugate));
5827:         PetscCall(VecCopy(l, conjugate));
5828:         PetscCall(VecConjugate(conjugate));
5829:         PetscCall(VecEqual(conjugate, r, &flg));
5830:         PetscCall(VecDestroy(&conjugate));
5831:       }
5832:       if (!flg) {
5833:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5834:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format and Hermitian matrix, left and right scaling vectors must be conjugate one of the other");
5835:         mat->hermitian = PETSC_BOOL3_FALSE;
5836:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5837:       }
5838:     }
5839:   }
5840:   PetscFunctionReturn(PETSC_SUCCESS);
5841: }

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

5846:   Logically Collective

5848:   Input Parameters:
5849: + mat - the matrix to be scaled
5850: - a   - the scaling value

5852:   Level: intermediate

5854: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5855: @*/
5856: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5857: {
5858:   PetscFunctionBegin;
5861:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5862:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5864:   MatCheckPreallocated(mat, 1);

5866:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5867:   if (a != (PetscScalar)1.0) {
5868:     PetscUseTypeMethod(mat, scale, a);
5869:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5870:   }
5871:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5872:   PetscFunctionReturn(PETSC_SUCCESS);
5873: }

5875: /*@
5876:   MatNorm - Calculates various norms of a matrix.

5878:   Collective

5880:   Input Parameters:
5881: + mat  - the matrix
5882: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

5884:   Output Parameter:
5885: . nrm - the resulting norm

5887:   Level: intermediate

5889: .seealso: [](ch_matrices), `Mat`
5890: @*/
5891: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5892: {
5893:   PetscFunctionBegin;
5896:   PetscAssertPointer(nrm, 3);

5898:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5899:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5900:   MatCheckPreallocated(mat, 1);

5902:   PetscUseTypeMethod(mat, norm, type, nrm);
5903:   PetscFunctionReturn(PETSC_SUCCESS);
5904: }

5906: /*
5907:      This variable is used to prevent counting of MatAssemblyBegin() that
5908:    are called from within a MatAssemblyEnd().
5909: */
5910: static PetscInt MatAssemblyEnd_InUse = 0;
5911: /*@
5912:   MatAssemblyBegin - Begins assembling the matrix.  This routine should
5913:   be called after completing all calls to `MatSetValues()`.

5915:   Collective

5917:   Input Parameters:
5918: + mat  - the matrix
5919: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

5921:   Level: beginner

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

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

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

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

5939: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
5940: @*/
5941: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
5942: {
5943:   PetscFunctionBegin;
5946:   MatCheckPreallocated(mat, 1);
5947:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
5948:   if (mat->assembled) {
5949:     mat->was_assembled = PETSC_TRUE;
5950:     mat->assembled     = PETSC_FALSE;
5951:   }

5953:   if (!MatAssemblyEnd_InUse) {
5954:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
5955:     PetscTryTypeMethod(mat, assemblybegin, type);
5956:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
5957:   } else PetscTryTypeMethod(mat, assemblybegin, type);
5958:   PetscFunctionReturn(PETSC_SUCCESS);
5959: }

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

5965:   Not Collective

5967:   Input Parameter:
5968: . mat - the matrix

5970:   Output Parameter:
5971: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

5973:   Level: advanced

5975: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
5976: @*/
5977: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
5978: {
5979:   PetscFunctionBegin;
5981:   PetscAssertPointer(assembled, 2);
5982:   *assembled = mat->assembled;
5983:   PetscFunctionReturn(PETSC_SUCCESS);
5984: }

5986: /*@
5987:   MatAssemblyEnd - Completes assembling the matrix.  This routine should
5988:   be called after `MatAssemblyBegin()`.

5990:   Collective

5992:   Input Parameters:
5993: + mat  - the matrix
5994: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

5996:   Options Database Key:
5997: . -mat_view [viewertype][:...] - option name and values. See `MatViewFromOptions()`/`PetscObjectViewFromOptions()` for the possible arguments

5999:   Level: beginner

6001: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6002:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`
6003: @*/
6004: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6005: {
6006:   static PetscInt inassm = 0;
6007:   PetscBool       flg    = PETSC_FALSE;

6009:   PetscFunctionBegin;

6013:   inassm++;
6014:   MatAssemblyEnd_InUse++;
6015:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6016:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6017:     PetscTryTypeMethod(mat, assemblyend, type);
6018:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6019:   } else PetscTryTypeMethod(mat, assemblyend, type);

6021:   /* Flush assembly is not a true assembly */
6022:   if (type != MAT_FLUSH_ASSEMBLY) {
6023:     if (mat->num_ass) {
6024:       if (!mat->symmetry_eternal) {
6025:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6026:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6027:       }
6028:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6029:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6030:     }
6031:     mat->num_ass++;
6032:     mat->assembled        = PETSC_TRUE;
6033:     mat->ass_nonzerostate = mat->nonzerostate;
6034:   }

6036:   mat->insertmode = NOT_SET_VALUES;
6037:   MatAssemblyEnd_InUse--;
6038:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6039:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6040:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6042:     if (mat->checksymmetryonassembly) {
6043:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6044:       if (flg) {
6045:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6046:       } else {
6047:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6048:       }
6049:     }
6050:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6051:   }
6052:   inassm--;
6053:   PetscFunctionReturn(PETSC_SUCCESS);
6054: }

6056: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6057: /*@
6058:   MatSetOption - Sets a parameter option for a matrix. Some options
6059:   may be specific to certain storage formats.  Some options
6060:   determine how values will be inserted (or added). Sorted,
6061:   row-oriented input will generally assemble the fastest. The default
6062:   is row-oriented.

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

6066:   Input Parameters:
6067: + mat - the matrix
6068: . op  - the option, one of those listed below (and possibly others),
6069: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6071:   Options Describing Matrix Structure:
6072: + `MAT_SPD`                         - symmetric positive definite
6073: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6074: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6075: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6076: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6077: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6078: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

6080:    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6081:    do not need to be computed (usually at a high cost)

6083:    Options For Use with `MatSetValues()`:
6084:    Insert a logically dense subblock, which can be
6085: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6087:    These options reflect the data you pass in with `MatSetValues()`; it has
6088:    nothing to do with how the data is stored internally in the matrix
6089:    data structure.

6091:    When (re)assembling a matrix, we can restrict the input for
6092:    efficiency/debugging purposes.  These options include
6093: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6094: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6095: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
6096: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6097: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6098: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6099:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6100:         performance for very large process counts.
6101: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6102:         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6103:         functions, instead sending only neighbor messages.

6105:   Level: intermediate

6107:   Notes:
6108:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6110:   Some options are relevant only for particular matrix types and
6111:   are thus ignored by others.  Other options are not supported by
6112:   certain matrix types and will generate an error message if set.

6114:   If using Fortran to compute a matrix, one may need to
6115:   use the column-oriented option (or convert to the row-oriented
6116:   format).

6118:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6119:   that would generate a new entry in the nonzero structure is instead
6120:   ignored.  Thus, if memory has not already been allocated for this particular
6121:   data, then the insertion is ignored. For dense matrices, in which
6122:   the entire array is allocated, no entries are ever ignored.
6123:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6125:   `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
6126:   that would generate a new entry in the nonzero structure instead produces
6127:   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

6129:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6130:   that would generate a new entry that has not been preallocated will
6131:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6132:   only.) This is a useful flag when debugging matrix memory preallocation.
6133:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6135:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6136:   other processors should be dropped, rather than stashed.
6137:   This is useful if you know that the "owning" processor is also
6138:   always generating the correct matrix entries, so that PETSc need
6139:   not transfer duplicate entries generated on another processor.

6141:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6142:   searches during matrix assembly. When this flag is set, the hash table
6143:   is created during the first matrix assembly. This hash table is
6144:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6145:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6146:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6147:   supported by `MATMPIBAIJ` format only.

6149:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6150:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6152:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6153:   a zero location in the matrix

6155:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6157:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6158:   zero row routines and thus improves performance for very large process counts.

6160:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6161:   part of the matrix (since they should match the upper triangular part).

6163:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6164:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6165:   with finite difference schemes with non-periodic boundary conditions.

6167:   Developer Note:
6168:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6169:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6170:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6171:   not changed.

6173: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6174: @*/
6175: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6176: {
6177:   PetscFunctionBegin;
6179:   if (op > 0) {
6182:   }

6184:   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);

6186:   switch (op) {
6187:   case MAT_FORCE_DIAGONAL_ENTRIES:
6188:     mat->force_diagonals = flg;
6189:     PetscFunctionReturn(PETSC_SUCCESS);
6190:   case MAT_NO_OFF_PROC_ENTRIES:
6191:     mat->nooffprocentries = flg;
6192:     PetscFunctionReturn(PETSC_SUCCESS);
6193:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6194:     mat->assembly_subset = flg;
6195:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6196: #if !defined(PETSC_HAVE_MPIUNI)
6197:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6198: #endif
6199:       mat->stash.first_assembly_done = PETSC_FALSE;
6200:     }
6201:     PetscFunctionReturn(PETSC_SUCCESS);
6202:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6203:     mat->nooffproczerorows = flg;
6204:     PetscFunctionReturn(PETSC_SUCCESS);
6205:   case MAT_SPD:
6206:     if (flg) {
6207:       mat->spd                    = PETSC_BOOL3_TRUE;
6208:       mat->symmetric              = PETSC_BOOL3_TRUE;
6209:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6210: #if !defined(PETSC_USE_COMPLEX)
6211:       mat->hermitian = PETSC_BOOL3_TRUE;
6212: #endif
6213:     } else {
6214:       mat->spd = PETSC_BOOL3_FALSE;
6215:     }
6216:     break;
6217:   case MAT_SYMMETRIC:
6218:     mat->symmetric = PetscBoolToBool3(flg);
6219:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6220: #if !defined(PETSC_USE_COMPLEX)
6221:     mat->hermitian = PetscBoolToBool3(flg);
6222: #endif
6223:     break;
6224:   case MAT_HERMITIAN:
6225:     mat->hermitian = PetscBoolToBool3(flg);
6226:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6227: #if !defined(PETSC_USE_COMPLEX)
6228:     mat->symmetric = PetscBoolToBool3(flg);
6229: #endif
6230:     break;
6231:   case MAT_STRUCTURALLY_SYMMETRIC:
6232:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6233:     break;
6234:   case MAT_SYMMETRY_ETERNAL:
6235:     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");
6236:     mat->symmetry_eternal = flg;
6237:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6238:     break;
6239:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6240:     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");
6241:     mat->structural_symmetry_eternal = flg;
6242:     break;
6243:   case MAT_SPD_ETERNAL:
6244:     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");
6245:     mat->spd_eternal = flg;
6246:     if (flg) {
6247:       mat->structural_symmetry_eternal = PETSC_TRUE;
6248:       mat->symmetry_eternal            = PETSC_TRUE;
6249:     }
6250:     break;
6251:   case MAT_STRUCTURE_ONLY:
6252:     mat->structure_only = flg;
6253:     break;
6254:   case MAT_SORTED_FULL:
6255:     mat->sortedfull = flg;
6256:     break;
6257:   default:
6258:     break;
6259:   }
6260:   PetscTryTypeMethod(mat, setoption, op, flg);
6261:   PetscFunctionReturn(PETSC_SUCCESS);
6262: }

6264: /*@
6265:   MatGetOption - Gets a parameter option that has been set for a matrix.

6267:   Logically Collective

6269:   Input Parameters:
6270: + mat - the matrix
6271: - op  - the option, this only responds to certain options, check the code for which ones

6273:   Output Parameter:
6274: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6276:   Level: intermediate

6278:   Notes:
6279:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6281:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6282:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6284: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6285:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6286: @*/
6287: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6288: {
6289:   PetscFunctionBegin;

6293:   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);
6294:   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()");

6296:   switch (op) {
6297:   case MAT_NO_OFF_PROC_ENTRIES:
6298:     *flg = mat->nooffprocentries;
6299:     break;
6300:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6301:     *flg = mat->nooffproczerorows;
6302:     break;
6303:   case MAT_SYMMETRIC:
6304:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6305:     break;
6306:   case MAT_HERMITIAN:
6307:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6308:     break;
6309:   case MAT_STRUCTURALLY_SYMMETRIC:
6310:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6311:     break;
6312:   case MAT_SPD:
6313:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6314:     break;
6315:   case MAT_SYMMETRY_ETERNAL:
6316:     *flg = mat->symmetry_eternal;
6317:     break;
6318:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6319:     *flg = mat->symmetry_eternal;
6320:     break;
6321:   default:
6322:     break;
6323:   }
6324:   PetscFunctionReturn(PETSC_SUCCESS);
6325: }

6327: /*@
6328:   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6329:   this routine retains the old nonzero structure.

6331:   Logically Collective

6333:   Input Parameter:
6334: . mat - the matrix

6336:   Level: intermediate

6338:   Note:
6339:   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.
6340:   See the Performance chapter of the users manual for information on preallocating matrices.

6342: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6343: @*/
6344: PetscErrorCode MatZeroEntries(Mat mat)
6345: {
6346:   PetscFunctionBegin;
6349:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6350:   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");
6351:   MatCheckPreallocated(mat, 1);

6353:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6354:   PetscUseTypeMethod(mat, zeroentries);
6355:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6356:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6357:   PetscFunctionReturn(PETSC_SUCCESS);
6358: }

6360: /*@
6361:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6362:   of a set of rows and columns of a matrix.

6364:   Collective

6366:   Input Parameters:
6367: + mat     - the matrix
6368: . numRows - the number of rows/columns to zero
6369: . rows    - the global row indices
6370: . diag    - value put in the diagonal of the eliminated rows
6371: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6372: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6374:   Level: intermediate

6376:   Notes:
6377:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6379:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6380:   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

6382:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6383:   Krylov method to take advantage of the known solution on the zeroed rows.

6385:   For the parallel case, all processes that share the matrix (i.e.,
6386:   those in the communicator used for matrix creation) MUST call this
6387:   routine, regardless of whether any rows being zeroed are owned by
6388:   them.

6390:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6391:   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
6392:   missing.

6394:   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6395:   list only rows local to itself).

6397:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6399: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6400:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6401: @*/
6402: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6403: {
6404:   PetscFunctionBegin;
6407:   if (numRows) PetscAssertPointer(rows, 3);
6408:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6409:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6410:   MatCheckPreallocated(mat, 1);

6412:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6413:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6414:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6415:   PetscFunctionReturn(PETSC_SUCCESS);
6416: }

6418: /*@
6419:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6420:   of a set of rows and columns of a matrix.

6422:   Collective

6424:   Input Parameters:
6425: + mat  - the matrix
6426: . is   - the rows to zero
6427: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6428: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6429: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6431:   Level: intermediate

6433:   Note:
6434:   See `MatZeroRowsColumns()` for details on how this routine operates.

6436: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6437:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6438: @*/
6439: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6440: {
6441:   PetscInt        numRows;
6442:   const PetscInt *rows;

6444:   PetscFunctionBegin;
6449:   PetscCall(ISGetLocalSize(is, &numRows));
6450:   PetscCall(ISGetIndices(is, &rows));
6451:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6452:   PetscCall(ISRestoreIndices(is, &rows));
6453:   PetscFunctionReturn(PETSC_SUCCESS);
6454: }

6456: /*@
6457:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6458:   of a set of rows of a matrix.

6460:   Collective

6462:   Input Parameters:
6463: + mat     - the matrix
6464: . numRows - the number of rows to zero
6465: . rows    - the global row indices
6466: . diag    - value put in the diagonal of the zeroed rows
6467: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6468: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6470:   Level: intermediate

6472:   Notes:
6473:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6475:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6477:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6478:   Krylov method to take advantage of the known solution on the zeroed rows.

6480:   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)
6481:   from the matrix.

6483:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6484:   but does not release memory.  Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6485:   formats this does not alter the nonzero structure.

6487:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6488:   of the matrix is not changed the values are
6489:   merely zeroed.

6491:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6492:   formats can optionally remove the main diagonal entry from the
6493:   nonzero structure as well, by passing 0.0 as the final argument).

6495:   For the parallel case, all processes that share the matrix (i.e.,
6496:   those in the communicator used for matrix creation) MUST call this
6497:   routine, regardless of whether any rows being zeroed are owned by
6498:   them.

6500:   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6501:   list only rows local to itself).

6503:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6504:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6506: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6507:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6508: @*/
6509: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6510: {
6511:   PetscFunctionBegin;
6514:   if (numRows) PetscAssertPointer(rows, 3);
6515:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6516:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6517:   MatCheckPreallocated(mat, 1);

6519:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6520:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6521:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6522:   PetscFunctionReturn(PETSC_SUCCESS);
6523: }

6525: /*@
6526:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6527:   of a set of rows of a matrix indicated by an `IS`

6529:   Collective

6531:   Input Parameters:
6532: + mat  - the matrix
6533: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6534: . diag - value put in all diagonals of eliminated rows
6535: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6536: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6538:   Level: intermediate

6540:   Note:
6541:   See `MatZeroRows()` for details on how this routine operates.

6543: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6544:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6545: @*/
6546: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6547: {
6548:   PetscInt        numRows = 0;
6549:   const PetscInt *rows    = NULL;

6551:   PetscFunctionBegin;
6554:   if (is) {
6556:     PetscCall(ISGetLocalSize(is, &numRows));
6557:     PetscCall(ISGetIndices(is, &rows));
6558:   }
6559:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6560:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6561:   PetscFunctionReturn(PETSC_SUCCESS);
6562: }

6564: /*@
6565:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6566:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6568:   Collective

6570:   Input Parameters:
6571: + mat     - the matrix
6572: . numRows - the number of rows to remove
6573: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6574: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6575: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6576: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6578:   Level: intermediate

6580:   Notes:
6581:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6593:   Fortran Note:
6594:   `idxm` and `idxn` should be declared as
6595: .vb
6596:     MatStencil idxm(4, m)
6597: .ve
6598:   and the values inserted using
6599: .vb
6600:     idxm(MatStencil_i, 1) = i
6601:     idxm(MatStencil_j, 1) = j
6602:     idxm(MatStencil_k, 1) = k
6603:     idxm(MatStencil_c, 1) = c
6604:    etc
6605: .ve

6607: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6608:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6609: @*/
6610: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6611: {
6612:   PetscInt  dim    = mat->stencil.dim;
6613:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6614:   PetscInt *dims   = mat->stencil.dims + 1;
6615:   PetscInt *starts = mat->stencil.starts;
6616:   PetscInt *dxm    = (PetscInt *)rows;
6617:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6619:   PetscFunctionBegin;
6622:   if (numRows) PetscAssertPointer(rows, 3);

6624:   PetscCall(PetscMalloc1(numRows, &jdxm));
6625:   for (i = 0; i < numRows; ++i) {
6626:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6627:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6628:     /* Local index in X dir */
6629:     tmp = *dxm++ - starts[0];
6630:     /* Loop over remaining dimensions */
6631:     for (j = 0; j < dim - 1; ++j) {
6632:       /* If nonlocal, set index to be negative */
6633:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6634:       /* Update local index */
6635:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6636:     }
6637:     /* Skip component slot if necessary */
6638:     if (mat->stencil.noc) dxm++;
6639:     /* Local row number */
6640:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6641:   }
6642:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6643:   PetscCall(PetscFree(jdxm));
6644:   PetscFunctionReturn(PETSC_SUCCESS);
6645: }

6647: /*@
6648:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6649:   of a set of rows and columns of a matrix.

6651:   Collective

6653:   Input Parameters:
6654: + mat     - the matrix
6655: . numRows - the number of rows/columns to remove
6656: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6657: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6658: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6659: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6661:   Level: intermediate

6663:   Notes:
6664:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6676:   Fortran Note:
6677:   `idxm` and `idxn` should be declared as
6678: .vb
6679:     MatStencil idxm(4, m)
6680: .ve
6681:   and the values inserted using
6682: .vb
6683:     idxm(MatStencil_i, 1) = i
6684:     idxm(MatStencil_j, 1) = j
6685:     idxm(MatStencil_k, 1) = k
6686:     idxm(MatStencil_c, 1) = c
6687:     etc
6688: .ve

6690: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6691:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6692: @*/
6693: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6694: {
6695:   PetscInt  dim    = mat->stencil.dim;
6696:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6697:   PetscInt *dims   = mat->stencil.dims + 1;
6698:   PetscInt *starts = mat->stencil.starts;
6699:   PetscInt *dxm    = (PetscInt *)rows;
6700:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6702:   PetscFunctionBegin;
6705:   if (numRows) PetscAssertPointer(rows, 3);

6707:   PetscCall(PetscMalloc1(numRows, &jdxm));
6708:   for (i = 0; i < numRows; ++i) {
6709:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6710:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6711:     /* Local index in X dir */
6712:     tmp = *dxm++ - starts[0];
6713:     /* Loop over remaining dimensions */
6714:     for (j = 0; j < dim - 1; ++j) {
6715:       /* If nonlocal, set index to be negative */
6716:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6717:       /* Update local index */
6718:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6719:     }
6720:     /* Skip component slot if necessary */
6721:     if (mat->stencil.noc) dxm++;
6722:     /* Local row number */
6723:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6724:   }
6725:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6726:   PetscCall(PetscFree(jdxm));
6727:   PetscFunctionReturn(PETSC_SUCCESS);
6728: }

6730: /*@
6731:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6732:   of a set of rows of a matrix; using local numbering of rows.

6734:   Collective

6736:   Input Parameters:
6737: + mat     - the matrix
6738: . numRows - the number of rows to remove
6739: . rows    - the local row indices
6740: . diag    - value put in all diagonals of eliminated rows
6741: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6742: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6744:   Level: intermediate

6746:   Notes:
6747:   Before calling `MatZeroRowsLocal()`, the user must first set the
6748:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

6750:   See `MatZeroRows()` for details on how this routine operates.

6752: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6753:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6754: @*/
6755: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6756: {
6757:   PetscFunctionBegin;
6760:   if (numRows) PetscAssertPointer(rows, 3);
6761:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6762:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6763:   MatCheckPreallocated(mat, 1);

6765:   if (mat->ops->zerorowslocal) {
6766:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6767:   } else {
6768:     IS        is, newis;
6769:     PetscInt *newRows, nl = 0;

6771:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6772:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6773:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6774:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6775:     for (PetscInt i = 0; i < numRows; i++)
6776:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6777:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
6778:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6779:     PetscCall(ISDestroy(&newis));
6780:     PetscCall(ISDestroy(&is));
6781:   }
6782:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6783:   PetscFunctionReturn(PETSC_SUCCESS);
6784: }

6786: /*@
6787:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6788:   of a set of rows of a matrix; using local numbering of rows.

6790:   Collective

6792:   Input Parameters:
6793: + mat  - the matrix
6794: . is   - index set of rows to remove
6795: . diag - value put in all diagonals of eliminated rows
6796: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6797: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6799:   Level: intermediate

6801:   Notes:
6802:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
6803:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

6805:   See `MatZeroRows()` for details on how this routine operates.

6807: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6808:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6809: @*/
6810: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6811: {
6812:   PetscInt        numRows;
6813:   const PetscInt *rows;

6815:   PetscFunctionBegin;
6819:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6820:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6821:   MatCheckPreallocated(mat, 1);

6823:   PetscCall(ISGetLocalSize(is, &numRows));
6824:   PetscCall(ISGetIndices(is, &rows));
6825:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6826:   PetscCall(ISRestoreIndices(is, &rows));
6827:   PetscFunctionReturn(PETSC_SUCCESS);
6828: }

6830: /*@
6831:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6832:   of a set of rows and columns of a matrix; using local numbering of rows.

6834:   Collective

6836:   Input Parameters:
6837: + mat     - the matrix
6838: . numRows - the number of rows to remove
6839: . rows    - the global row indices
6840: . diag    - value put in all diagonals of eliminated rows
6841: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6842: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6844:   Level: intermediate

6846:   Notes:
6847:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
6848:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

6850:   See `MatZeroRowsColumns()` for details on how this routine operates.

6852: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6853:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6854: @*/
6855: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6856: {
6857:   PetscFunctionBegin;
6860:   if (numRows) PetscAssertPointer(rows, 3);
6861:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6862:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6863:   MatCheckPreallocated(mat, 1);

6865:   if (mat->ops->zerorowscolumnslocal) {
6866:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
6867:   } else {
6868:     IS        is, newis;
6869:     PetscInt *newRows, nl = 0;

6871:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6872:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6873:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6874:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6875:     for (PetscInt i = 0; i < numRows; i++)
6876:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6877:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
6878:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6879:     PetscCall(ISDestroy(&newis));
6880:     PetscCall(ISDestroy(&is));
6881:   }
6882:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6883:   PetscFunctionReturn(PETSC_SUCCESS);
6884: }

6886: /*@
6887:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6888:   of a set of rows and columns of a matrix; using local numbering of rows.

6890:   Collective

6892:   Input Parameters:
6893: + mat  - the matrix
6894: . is   - index set of rows to remove
6895: . diag - value put in all diagonals of eliminated rows
6896: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6897: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6899:   Level: intermediate

6901:   Notes:
6902:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
6903:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

6905:   See `MatZeroRowsColumns()` for details on how this routine operates.

6907: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6908:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6909: @*/
6910: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6911: {
6912:   PetscInt        numRows;
6913:   const PetscInt *rows;

6915:   PetscFunctionBegin;
6919:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6920:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6921:   MatCheckPreallocated(mat, 1);

6923:   PetscCall(ISGetLocalSize(is, &numRows));
6924:   PetscCall(ISGetIndices(is, &rows));
6925:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6926:   PetscCall(ISRestoreIndices(is, &rows));
6927:   PetscFunctionReturn(PETSC_SUCCESS);
6928: }

6930: /*@
6931:   MatGetSize - Returns the numbers of rows and columns in a matrix.

6933:   Not Collective

6935:   Input Parameter:
6936: . mat - the matrix

6938:   Output Parameters:
6939: + m - the number of global rows
6940: - n - the number of global columns

6942:   Level: beginner

6944:   Note:
6945:   Both output parameters can be `NULL` on input.

6947: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6948: @*/
6949: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6950: {
6951:   PetscFunctionBegin;
6953:   if (m) *m = mat->rmap->N;
6954:   if (n) *n = mat->cmap->N;
6955:   PetscFunctionReturn(PETSC_SUCCESS);
6956: }

6958: /*@
6959:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
6960:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

6962:   Not Collective

6964:   Input Parameter:
6965: . mat - the matrix

6967:   Output Parameters:
6968: + m - the number of local rows, use `NULL` to not obtain this value
6969: - n - the number of local columns, use `NULL` to not obtain this value

6971:   Level: beginner

6973: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
6974: @*/
6975: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
6976: {
6977:   PetscFunctionBegin;
6979:   if (m) PetscAssertPointer(m, 2);
6980:   if (n) PetscAssertPointer(n, 3);
6981:   if (m) *m = mat->rmap->n;
6982:   if (n) *n = mat->cmap->n;
6983:   PetscFunctionReturn(PETSC_SUCCESS);
6984: }

6986: /*@
6987:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
6988:   vector one multiplies this matrix by that are owned by this processor.

6990:   Not Collective, unless matrix has not been allocated, then collective

6992:   Input Parameter:
6993: . mat - the matrix

6995:   Output Parameters:
6996: + m - the global index of the first local column, use `NULL` to not obtain this value
6997: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

6999:   Level: developer

7001:   Notes:
7002:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7004:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7005:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7010:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7011:   Layouts](sec_matlayout) for details on matrix layouts.

7013: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7014:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7015: @*/
7016: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7017: {
7018:   PetscFunctionBegin;
7021:   if (m) PetscAssertPointer(m, 2);
7022:   if (n) PetscAssertPointer(n, 3);
7023:   MatCheckPreallocated(mat, 1);
7024:   if (m) *m = mat->cmap->rstart;
7025:   if (n) *n = mat->cmap->rend;
7026:   PetscFunctionReturn(PETSC_SUCCESS);
7027: }

7029: /*@
7030:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7031:   this MPI process.

7033:   Not Collective

7035:   Input Parameter:
7036: . mat - the matrix

7038:   Output Parameters:
7039: + m - the global index of the first local row, use `NULL` to not obtain this value
7040: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7042:   Level: beginner

7044:   Notes:
7045:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7047:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7048:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

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

7055:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7056:   would contain the result of a matrix vector product with this matrix. See [Matrix
7057:   Layouts](sec_matlayout) for details on matrix layouts.

7059: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7060:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7061: @*/
7062: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7063: {
7064:   PetscFunctionBegin;
7067:   if (m) PetscAssertPointer(m, 2);
7068:   if (n) PetscAssertPointer(n, 3);
7069:   MatCheckPreallocated(mat, 1);
7070:   if (m) *m = mat->rmap->rstart;
7071:   if (n) *n = mat->rmap->rend;
7072:   PetscFunctionReturn(PETSC_SUCCESS);
7073: }

7075: /*@C
7076:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7077:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7079:   Not Collective, unless matrix has not been allocated

7081:   Input Parameter:
7082: . mat - the matrix

7084:   Output Parameter:
7085: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7086:            where `size` is the number of MPI processes used by `mat`

7088:   Level: beginner

7090:   Notes:
7091:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7093:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7094:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7099:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7100:   would contain the result of a matrix vector product with this matrix. See [Matrix
7101:   Layouts](sec_matlayout) for details on matrix layouts.

7103: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7104:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7105:           `DMDAGetGhostCorners()`, `DM`
7106: @*/
7107: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7108: {
7109:   PetscFunctionBegin;
7112:   MatCheckPreallocated(mat, 1);
7113:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7114:   PetscFunctionReturn(PETSC_SUCCESS);
7115: }

7117: /*@C
7118:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7119:   vector one multiplies this vector by that are owned by each processor.

7121:   Not Collective, unless matrix has not been allocated

7123:   Input Parameter:
7124: . mat - the matrix

7126:   Output Parameter:
7127: . ranges - start of each processors portion plus one more than the total length at the end

7129:   Level: beginner

7131:   Notes:
7132:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7134:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7135:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7140:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7141:   Layouts](sec_matlayout) for details on matrix layouts.

7143: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7144:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7145:           `DMDAGetGhostCorners()`, `DM`
7146: @*/
7147: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7148: {
7149:   PetscFunctionBegin;
7152:   MatCheckPreallocated(mat, 1);
7153:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7154:   PetscFunctionReturn(PETSC_SUCCESS);
7155: }

7157: /*@
7158:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7160:   Not Collective

7162:   Input Parameter:
7163: . A - matrix

7165:   Output Parameters:
7166: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7167: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7169:   Level: intermediate

7171:   Note:
7172:   You should call `ISDestroy()` on the returned `IS`

7174:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7175:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7176:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7177:   details on matrix layouts.

7179: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7180: @*/
7181: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7182: {
7183:   PetscErrorCode (*f)(Mat, IS *, IS *);

7185:   PetscFunctionBegin;
7188:   MatCheckPreallocated(A, 1);
7189:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7190:   if (f) {
7191:     PetscCall((*f)(A, rows, cols));
7192:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7193:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7194:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7195:   }
7196:   PetscFunctionReturn(PETSC_SUCCESS);
7197: }

7199: /*@
7200:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7201:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7202:   to complete the factorization.

7204:   Collective

7206:   Input Parameters:
7207: + fact - the factorized matrix obtained with `MatGetFactor()`
7208: . mat  - the matrix
7209: . row  - row permutation
7210: . col  - column permutation
7211: - info - structure containing
7212: .vb
7213:       levels - number of levels of fill.
7214:       expected fill - as ratio of original fill.
7215:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7216:                 missing diagonal entries)
7217: .ve

7219:   Level: developer

7221:   Notes:
7222:   See [Matrix Factorization](sec_matfactor) for additional information.

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

7228:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

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

7233: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7234:           `MatGetOrdering()`, `MatFactorInfo`
7235: @*/
7236: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7237: {
7238:   PetscFunctionBegin;
7243:   PetscAssertPointer(info, 5);
7244:   PetscAssertPointer(fact, 1);
7245:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7246:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7247:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7248:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7249:   MatCheckPreallocated(mat, 2);

7251:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7252:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7253:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7254:   PetscFunctionReturn(PETSC_SUCCESS);
7255: }

7257: /*@
7258:   MatICCFactorSymbolic - Performs symbolic incomplete
7259:   Cholesky factorization for a symmetric matrix.  Use
7260:   `MatCholeskyFactorNumeric()` to complete the factorization.

7262:   Collective

7264:   Input Parameters:
7265: + fact - the factorized matrix obtained with `MatGetFactor()`
7266: . mat  - the matrix to be factored
7267: . perm - row and column permutation
7268: - info - structure containing
7269: .vb
7270:       levels - number of levels of fill.
7271:       expected fill - as ratio of original fill.
7272: .ve

7274:   Level: developer

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

7281:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

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

7286: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7287: @*/
7288: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7289: {
7290:   PetscFunctionBegin;
7294:   PetscAssertPointer(info, 4);
7295:   PetscAssertPointer(fact, 1);
7296:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7297:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7298:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7299:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7300:   MatCheckPreallocated(mat, 2);

7302:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7303:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7304:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7305:   PetscFunctionReturn(PETSC_SUCCESS);
7306: }

7308: /*@C
7309:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7310:   points to an array of valid matrices, they may be reused to store the new
7311:   submatrices.

7313:   Collective

7315:   Input Parameters:
7316: + mat   - the matrix
7317: . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7318: . irow  - index set of rows to extract
7319: . icol  - index set of columns to extract
7320: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7322:   Output Parameter:
7323: . submat - the array of submatrices

7325:   Level: advanced

7327:   Notes:
7328:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7329:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7330:   to extract a parallel submatrix.

7332:   Some matrix types place restrictions on the row and column
7333:   indices, such as that they be sorted or that they be equal to each other.

7335:   The index sets may not have duplicate entries.

7337:   When extracting submatrices from a parallel matrix, each processor can
7338:   form a different submatrix by setting the rows and columns of its
7339:   individual index sets according to the local submatrix desired.

7341:   When finished using the submatrices, the user should destroy
7342:   them with `MatDestroySubMatrices()`.

7344:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7345:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7347:   This routine creates the matrices in submat; you should NOT create them before
7348:   calling it. It also allocates the array of matrix pointers submat.

7350:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7351:   request one row/column in a block, they must request all rows/columns that are in
7352:   that block. For example, if the block size is 2 you cannot request just row 0 and
7353:   column 0.

7355:   Fortran Note:
7356: .vb
7357:   Mat, pointer :: submat(:)
7358: .ve

7360: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7361: @*/
7362: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7363: {
7364:   PetscInt  i;
7365:   PetscBool eq;

7367:   PetscFunctionBegin;
7370:   if (n) {
7371:     PetscAssertPointer(irow, 3);
7373:     PetscAssertPointer(icol, 4);
7375:   }
7376:   PetscAssertPointer(submat, 6);
7377:   if (n && scall == MAT_REUSE_MATRIX) {
7378:     PetscAssertPointer(*submat, 6);
7380:   }
7381:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7382:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7383:   MatCheckPreallocated(mat, 1);
7384:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7385:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7386:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7387:   for (i = 0; i < n; i++) {
7388:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7389:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7390:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7391: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7392:     if (mat->boundtocpu && mat->bindingpropagates) {
7393:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7394:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7395:     }
7396: #endif
7397:   }
7398:   PetscFunctionReturn(PETSC_SUCCESS);
7399: }

7401: /*@C
7402:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7404:   Collective

7406:   Input Parameters:
7407: + mat   - the matrix
7408: . n     - the number of submatrixes to be extracted
7409: . irow  - index set of rows to extract
7410: . icol  - index set of columns to extract
7411: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7413:   Output Parameter:
7414: . submat - the array of submatrices

7416:   Level: advanced

7418:   Note:
7419:   This is used by `PCGASM`

7421: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7422: @*/
7423: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7424: {
7425:   PetscInt  i;
7426:   PetscBool eq;

7428:   PetscFunctionBegin;
7431:   if (n) {
7432:     PetscAssertPointer(irow, 3);
7434:     PetscAssertPointer(icol, 4);
7436:   }
7437:   PetscAssertPointer(submat, 6);
7438:   if (n && scall == MAT_REUSE_MATRIX) {
7439:     PetscAssertPointer(*submat, 6);
7441:   }
7442:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7443:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7444:   MatCheckPreallocated(mat, 1);

7446:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7447:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7448:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7449:   for (i = 0; i < n; i++) {
7450:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7451:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7452:   }
7453:   PetscFunctionReturn(PETSC_SUCCESS);
7454: }

7456: /*@C
7457:   MatDestroyMatrices - Destroys an array of matrices

7459:   Collective

7461:   Input Parameters:
7462: + n   - the number of local matrices
7463: - mat - the matrices (this is a pointer to the array of matrices)

7465:   Level: advanced

7467:   Notes:
7468:   Frees not only the matrices, but also the array that contains the matrices

7470:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7472: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7473: @*/
7474: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7475: {
7476:   PetscInt i;

7478:   PetscFunctionBegin;
7479:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7480:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7481:   PetscAssertPointer(mat, 2);

7483:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7485:   /* memory is allocated even if n = 0 */
7486:   PetscCall(PetscFree(*mat));
7487:   PetscFunctionReturn(PETSC_SUCCESS);
7488: }

7490: /*@C
7491:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7493:   Collective

7495:   Input Parameters:
7496: + n   - the number of local matrices
7497: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7499:   Level: advanced

7501:   Note:
7502:   Frees not only the matrices, but also the array that contains the matrices

7504: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7505: @*/
7506: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7507: {
7508:   Mat mat0;

7510:   PetscFunctionBegin;
7511:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7512:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7513:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7514:   PetscAssertPointer(mat, 2);

7516:   mat0 = (*mat)[0];
7517:   if (mat0 && mat0->ops->destroysubmatrices) {
7518:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7519:   } else {
7520:     PetscCall(MatDestroyMatrices(n, mat));
7521:   }
7522:   PetscFunctionReturn(PETSC_SUCCESS);
7523: }

7525: /*@
7526:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7528:   Collective

7530:   Input Parameter:
7531: . mat - the matrix

7533:   Output Parameter:
7534: . matstruct - the sequential matrix with the nonzero structure of `mat`

7536:   Level: developer

7538: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7539: @*/
7540: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7541: {
7542:   PetscFunctionBegin;
7544:   PetscAssertPointer(matstruct, 2);

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

7550:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7551:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7552:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7553:   PetscFunctionReturn(PETSC_SUCCESS);
7554: }

7556: /*@C
7557:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7559:   Collective

7561:   Input Parameter:
7562: . mat - the matrix

7564:   Level: advanced

7566:   Note:
7567:   This is not needed, one can just call `MatDestroy()`

7569: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7570: @*/
7571: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7572: {
7573:   PetscFunctionBegin;
7574:   PetscAssertPointer(mat, 1);
7575:   PetscCall(MatDestroy(mat));
7576:   PetscFunctionReturn(PETSC_SUCCESS);
7577: }

7579: /*@
7580:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7581:   replaces the index sets by larger ones that represent submatrices with
7582:   additional overlap.

7584:   Collective

7586:   Input Parameters:
7587: + mat - the matrix
7588: . n   - the number of index sets
7589: . is  - the array of index sets (these index sets will changed during the call)
7590: - ov  - the additional overlap requested

7592:   Options Database Key:
7593: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7595:   Level: developer

7597:   Note:
7598:   The computed overlap preserves the matrix block sizes when the blocks are square.
7599:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7600:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

7602: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7603: @*/
7604: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7605: {
7606:   PetscInt i, bs, cbs;

7608:   PetscFunctionBegin;
7612:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7613:   if (n) {
7614:     PetscAssertPointer(is, 3);
7616:   }
7617:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7618:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7619:   MatCheckPreallocated(mat, 1);

7621:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7622:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7623:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7624:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7625:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7626:   if (bs == cbs) {
7627:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7628:   }
7629:   PetscFunctionReturn(PETSC_SUCCESS);
7630: }

7632: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

7634: /*@
7635:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7636:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7637:   additional overlap.

7639:   Collective

7641:   Input Parameters:
7642: + mat - the matrix
7643: . n   - the number of index sets
7644: . is  - the array of index sets (these index sets will changed during the call)
7645: - ov  - the additional overlap requested

7647:   `   Options Database Key:
7648: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7650:   Level: developer

7652: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7653: @*/
7654: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7655: {
7656:   PetscInt i;

7658:   PetscFunctionBegin;
7661:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7662:   if (n) {
7663:     PetscAssertPointer(is, 3);
7665:   }
7666:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7667:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7668:   MatCheckPreallocated(mat, 1);
7669:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7670:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7671:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7672:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7673:   PetscFunctionReturn(PETSC_SUCCESS);
7674: }

7676: /*@
7677:   MatGetBlockSize - Returns the matrix block size.

7679:   Not Collective

7681:   Input Parameter:
7682: . mat - the matrix

7684:   Output Parameter:
7685: . bs - block size

7687:   Level: intermediate

7689:   Notes:
7690:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

7692:   If the block size has not been set yet this routine returns 1.

7694: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7695: @*/
7696: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7697: {
7698:   PetscFunctionBegin;
7700:   PetscAssertPointer(bs, 2);
7701:   *bs = mat->rmap->bs;
7702:   PetscFunctionReturn(PETSC_SUCCESS);
7703: }

7705: /*@
7706:   MatGetBlockSizes - Returns the matrix block row and column sizes.

7708:   Not Collective

7710:   Input Parameter:
7711: . mat - the matrix

7713:   Output Parameters:
7714: + rbs - row block size
7715: - cbs - column block size

7717:   Level: intermediate

7719:   Notes:
7720:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7721:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7723:   If a block size has not been set yet this routine returns 1.

7725: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7726: @*/
7727: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7728: {
7729:   PetscFunctionBegin;
7731:   if (rbs) PetscAssertPointer(rbs, 2);
7732:   if (cbs) PetscAssertPointer(cbs, 3);
7733:   if (rbs) *rbs = mat->rmap->bs;
7734:   if (cbs) *cbs = mat->cmap->bs;
7735:   PetscFunctionReturn(PETSC_SUCCESS);
7736: }

7738: /*@
7739:   MatSetBlockSize - Sets the matrix block size.

7741:   Logically Collective

7743:   Input Parameters:
7744: + mat - the matrix
7745: - bs  - block size

7747:   Level: intermediate

7749:   Notes:
7750:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
7751:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7753:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
7754:   is compatible with the matrix local sizes.

7756: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7757: @*/
7758: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7759: {
7760:   PetscFunctionBegin;
7763:   PetscCall(MatSetBlockSizes(mat, bs, bs));
7764:   PetscFunctionReturn(PETSC_SUCCESS);
7765: }

7767: typedef struct {
7768:   PetscInt         n;
7769:   IS              *is;
7770:   Mat             *mat;
7771:   PetscObjectState nonzerostate;
7772:   Mat              C;
7773: } EnvelopeData;

7775: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
7776: {
7777:   EnvelopeData *edata = *(EnvelopeData **)ptr;

7779:   PetscFunctionBegin;
7780:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7781:   PetscCall(PetscFree(edata->is));
7782:   PetscCall(PetscFree(edata));
7783:   PetscFunctionReturn(PETSC_SUCCESS);
7784: }

7786: /*@
7787:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
7788:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

7790:   Collective

7792:   Input Parameter:
7793: . mat - the matrix

7795:   Level: intermediate

7797:   Notes:
7798:   There can be zeros within the blocks

7800:   The blocks can overlap between processes, including laying on more than two processes

7802: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7803: @*/
7804: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7805: {
7806:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7807:   PetscInt          *diag, *odiag, sc;
7808:   VecScatter         scatter;
7809:   PetscScalar       *seqv;
7810:   const PetscScalar *parv;
7811:   const PetscInt    *ia, *ja;
7812:   PetscBool          set, flag, done;
7813:   Mat                AA = mat, A;
7814:   MPI_Comm           comm;
7815:   PetscMPIInt        rank, size, tag;
7816:   MPI_Status         status;
7817:   PetscContainer     container;
7818:   EnvelopeData      *edata;
7819:   Vec                seq, par;
7820:   IS                 isglobal;

7822:   PetscFunctionBegin;
7824:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7825:   if (!set || !flag) {
7826:     /* TODO: only needs nonzero structure of transpose */
7827:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7828:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7829:   }
7830:   PetscCall(MatAIJGetLocalMat(AA, &A));
7831:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7832:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

7834:   PetscCall(MatGetLocalSize(mat, &n, NULL));
7835:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7836:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7837:   PetscCallMPI(MPI_Comm_size(comm, &size));
7838:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

7840:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

7842:   if (rank > 0) {
7843:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7844:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7845:   }
7846:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7847:   for (i = 0; i < n; i++) {
7848:     env = PetscMax(env, ja[ia[i + 1] - 1]);
7849:     II  = rstart + i;
7850:     if (env == II) {
7851:       starts[lblocks]  = tbs;
7852:       sizes[lblocks++] = 1 + II - tbs;
7853:       tbs              = 1 + II;
7854:     }
7855:   }
7856:   if (rank < size - 1) {
7857:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7858:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7859:   }

7861:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7862:   if (!set || !flag) PetscCall(MatDestroy(&AA));
7863:   PetscCall(MatDestroy(&A));

7865:   PetscCall(PetscNew(&edata));
7866:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7867:   edata->n = lblocks;
7868:   /* create IS needed for extracting blocks from the original matrix */
7869:   PetscCall(PetscMalloc1(lblocks, &edata->is));
7870:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

7872:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
7873:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7874:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7875:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7876:   PetscCall(MatSetType(edata->C, MATAIJ));

7878:   /* Communicate the start and end of each row, from each block to the correct rank */
7879:   /* TODO: Use PetscSF instead of VecScatter */
7880:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7881:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7882:   PetscCall(VecGetArrayWrite(seq, &seqv));
7883:   for (PetscInt i = 0; i < lblocks; i++) {
7884:     for (PetscInt j = 0; j < sizes[i]; j++) {
7885:       seqv[cnt]     = starts[i];
7886:       seqv[cnt + 1] = starts[i] + sizes[i];
7887:       cnt += 2;
7888:     }
7889:   }
7890:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7891:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7892:   sc -= cnt;
7893:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7894:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7895:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7896:   PetscCall(ISDestroy(&isglobal));
7897:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7898:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7899:   PetscCall(VecScatterDestroy(&scatter));
7900:   PetscCall(VecDestroy(&seq));
7901:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7902:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7903:   PetscCall(VecGetArrayRead(par, &parv));
7904:   cnt = 0;
7905:   PetscCall(MatGetSize(mat, NULL, &n));
7906:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7907:     PetscInt start, end, d = 0, od = 0;

7909:     start = (PetscInt)PetscRealPart(parv[cnt]);
7910:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7911:     cnt += 2;

7913:     if (start < cstart) {
7914:       od += cstart - start + n - cend;
7915:       d += cend - cstart;
7916:     } else if (start < cend) {
7917:       od += n - cend;
7918:       d += cend - start;
7919:     } else od += n - start;
7920:     if (end <= cstart) {
7921:       od -= cstart - end + n - cend;
7922:       d -= cend - cstart;
7923:     } else if (end < cend) {
7924:       od -= n - cend;
7925:       d -= cend - end;
7926:     } else od -= n - end;

7928:     odiag[i] = od;
7929:     diag[i]  = d;
7930:   }
7931:   PetscCall(VecRestoreArrayRead(par, &parv));
7932:   PetscCall(VecDestroy(&par));
7933:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7934:   PetscCall(PetscFree2(diag, odiag));
7935:   PetscCall(PetscFree2(sizes, starts));

7937:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7938:   PetscCall(PetscContainerSetPointer(container, edata));
7939:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
7940:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7941:   PetscCall(PetscObjectDereference((PetscObject)container));
7942:   PetscFunctionReturn(PETSC_SUCCESS);
7943: }

7945: /*@
7946:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

7948:   Collective

7950:   Input Parameters:
7951: + A     - the matrix
7952: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

7954:   Output Parameter:
7955: . C - matrix with inverted block diagonal of `A`

7957:   Level: advanced

7959:   Note:
7960:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

7962: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7963: @*/
7964: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7965: {
7966:   PetscContainer   container;
7967:   EnvelopeData    *edata;
7968:   PetscObjectState nonzerostate;

7970:   PetscFunctionBegin;
7971:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7972:   if (!container) {
7973:     PetscCall(MatComputeVariableBlockEnvelope(A));
7974:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7975:   }
7976:   PetscCall(PetscContainerGetPointer(container, &edata));
7977:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
7978:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
7979:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

7981:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
7982:   *C = edata->C;

7984:   for (PetscInt i = 0; i < edata->n; i++) {
7985:     Mat          D;
7986:     PetscScalar *dvalues;

7988:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
7989:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
7990:     PetscCall(MatSeqDenseInvert(D));
7991:     PetscCall(MatDenseGetArray(D, &dvalues));
7992:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
7993:     PetscCall(MatDestroy(&D));
7994:   }
7995:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
7996:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
7997:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
7998:   PetscFunctionReturn(PETSC_SUCCESS);
7999: }

8001: /*@
8002:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8004:   Not Collective

8006:   Input Parameters:
8007: + mat     - the matrix
8008: . nblocks - the number of blocks on this process, each block can only exist on a single process
8009: - bsizes  - the block sizes

8011:   Level: intermediate

8013:   Notes:
8014:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8016:   Each variable point-block set of degrees of freedom must live on a single MPI process. That is a point block cannot straddle two MPI processes.

8018: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8019:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8020: @*/
8021: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8022: {
8023:   PetscInt ncnt = 0, nlocal;

8025:   PetscFunctionBegin;
8027:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8028:   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);
8029:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8030:   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);
8031:   PetscCall(PetscFree(mat->bsizes));
8032:   mat->nblocks = nblocks;
8033:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8034:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8035:   PetscFunctionReturn(PETSC_SUCCESS);
8036: }

8038: /*@C
8039:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8041:   Not Collective; No Fortran Support

8043:   Input Parameter:
8044: . mat - the matrix

8046:   Output Parameters:
8047: + nblocks - the number of blocks on this process
8048: - bsizes  - the block sizes

8050:   Level: intermediate

8052: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8053: @*/
8054: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8055: {
8056:   PetscFunctionBegin;
8058:   if (nblocks) *nblocks = mat->nblocks;
8059:   if (bsizes) *bsizes = mat->bsizes;
8060:   PetscFunctionReturn(PETSC_SUCCESS);
8061: }

8063: /*@
8064:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8066:   Not Collective

8068:   Input Parameter:
8069: + subA  - the submatrix
8070: . A     - the original matrix
8071: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8073:   Level: developer

8075:   Notes:
8076:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8078: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8079: @*/
8080: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8081: {
8082:   const PetscInt *rows;
8083:   PetscInt        n, rStart, rEnd, Nb = 0;
8084:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8086:   PetscFunctionBegin;
8087:   // The code for block size extraction does not support an unsorted IS
8088:   if (flg) PetscCall(ISSorted(isrow, &flg));
8089:   // We don't support originally off-diagonal blocks
8090:   if (flg) {
8091:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8092:     PetscCall(ISGetLocalSize(isrow, &n));
8093:     PetscCall(ISGetIndices(isrow, &rows));
8094:     for (PetscInt i = 0; i < n && flg; ++i) {
8095:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8096:     }
8097:     PetscCall(ISRestoreIndices(isrow, &rows));
8098:   }
8099:   // quiet return if we can't extract block size
8100:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8101:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8103:   // extract block sizes
8104:   PetscCall(ISGetIndices(isrow, &rows));
8105:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8106:     PetscBool occupied = PETSC_FALSE;

8108:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8109:       const PetscInt row = gr + br;

8111:       if (i == n) break;
8112:       if (rows[i] == row) {
8113:         occupied = PETSC_TRUE;
8114:         ++i;
8115:       }
8116:       while (i < n && rows[i] < row) ++i;
8117:     }
8118:     gr += A->bsizes[b];
8119:     if (occupied) ++Nb;
8120:   }
8121:   subA->nblocks = Nb;
8122:   PetscCall(PetscFree(subA->bsizes));
8123:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8124:   PetscInt sb = 0;
8125:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8126:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8127:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8128:       const PetscInt row = gr + br;

8130:       if (i == n) break;
8131:       if (rows[i] == row) {
8132:         ++subA->bsizes[sb];
8133:         ++i;
8134:       }
8135:       while (i < n && rows[i] < row) ++i;
8136:     }
8137:     gr += A->bsizes[b];
8138:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8139:   }
8140:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8141:   PetscInt nlocal, ncnt = 0;
8142:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8143:   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);
8144:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8145:   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);
8146:   PetscCall(ISRestoreIndices(isrow, &rows));
8147:   PetscFunctionReturn(PETSC_SUCCESS);
8148: }

8150: /*@
8151:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8153:   Logically Collective

8155:   Input Parameters:
8156: + mat - the matrix
8157: . rbs - row block size
8158: - cbs - column block size

8160:   Level: intermediate

8162:   Notes:
8163:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8164:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8165:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8167:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8168:   are compatible with the matrix local sizes.

8170:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8172: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8173: @*/
8174: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8175: {
8176:   PetscFunctionBegin;
8180:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8181:   if (mat->rmap->refcnt) {
8182:     ISLocalToGlobalMapping l2g  = NULL;
8183:     PetscLayout            nmap = NULL;

8185:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8186:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8187:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8188:     mat->rmap          = nmap;
8189:     mat->rmap->mapping = l2g;
8190:   }
8191:   if (mat->cmap->refcnt) {
8192:     ISLocalToGlobalMapping l2g  = NULL;
8193:     PetscLayout            nmap = NULL;

8195:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8196:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8197:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8198:     mat->cmap          = nmap;
8199:     mat->cmap->mapping = l2g;
8200:   }
8201:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8202:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8203:   PetscFunctionReturn(PETSC_SUCCESS);
8204: }

8206: /*@
8207:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8209:   Logically Collective

8211:   Input Parameters:
8212: + mat     - the matrix
8213: . fromRow - matrix from which to copy row block size
8214: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8216:   Level: developer

8218: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8219: @*/
8220: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8221: {
8222:   PetscFunctionBegin;
8226:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8227:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8228:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8229:   PetscFunctionReturn(PETSC_SUCCESS);
8230: }

8232: /*@
8233:   MatResidual - Default routine to calculate the residual r = b - Ax

8235:   Collective

8237:   Input Parameters:
8238: + mat - the matrix
8239: . b   - the right-hand-side
8240: - x   - the approximate solution

8242:   Output Parameter:
8243: . r - location to store the residual

8245:   Level: developer

8247: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8248: @*/
8249: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8250: {
8251:   PetscFunctionBegin;
8257:   MatCheckPreallocated(mat, 1);
8258:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8259:   if (!mat->ops->residual) {
8260:     PetscCall(MatMult(mat, x, r));
8261:     PetscCall(VecAYPX(r, -1.0, b));
8262:   } else {
8263:     PetscUseTypeMethod(mat, residual, b, x, r);
8264:   }
8265:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8266:   PetscFunctionReturn(PETSC_SUCCESS);
8267: }

8269: /*@C
8270:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8272:   Collective

8274:   Input Parameters:
8275: + mat             - the matrix
8276: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8277: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8278: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8279:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8280:                  always used.

8282:   Output Parameters:
8283: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8284: . 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
8285: . ja   - the column indices, use `NULL` if not needed
8286: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8287:            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set

8289:   Level: developer

8291:   Notes:
8292:   You CANNOT change any of the ia[] or ja[] values.

8294:   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.

8296:   Fortran Notes:
8297:   Use
8298: .vb
8299:     PetscInt, pointer :: ia(:),ja(:)
8300:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8301:     ! Access the ith and jth entries via ia(i) and ja(j)
8302: .ve

8304: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8305: @*/
8306: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8307: {
8308:   PetscFunctionBegin;
8311:   if (n) PetscAssertPointer(n, 5);
8312:   if (ia) PetscAssertPointer(ia, 6);
8313:   if (ja) PetscAssertPointer(ja, 7);
8314:   if (done) PetscAssertPointer(done, 8);
8315:   MatCheckPreallocated(mat, 1);
8316:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8317:   else {
8318:     if (done) *done = PETSC_TRUE;
8319:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8320:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8321:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8322:   }
8323:   PetscFunctionReturn(PETSC_SUCCESS);
8324: }

8326: /*@C
8327:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8329:   Collective

8331:   Input Parameters:
8332: + mat             - the matrix
8333: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8334: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8335:                 symmetrized
8336: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8337:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8338:                  always used.

8340:   Output Parameters:
8341: + n    - number of columns in the (possibly compressed) matrix
8342: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8343: . ja   - the row indices
8344: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8346:   Level: developer

8348: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8349: @*/
8350: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8351: {
8352:   PetscFunctionBegin;
8355:   PetscAssertPointer(n, 5);
8356:   if (ia) PetscAssertPointer(ia, 6);
8357:   if (ja) PetscAssertPointer(ja, 7);
8358:   PetscAssertPointer(done, 8);
8359:   MatCheckPreallocated(mat, 1);
8360:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8361:   else {
8362:     *done = PETSC_TRUE;
8363:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8364:   }
8365:   PetscFunctionReturn(PETSC_SUCCESS);
8366: }

8368: /*@C
8369:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8371:   Collective

8373:   Input Parameters:
8374: + mat             - the matrix
8375: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8376: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8377: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8378:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8379:                     always used.
8380: . n               - size of (possibly compressed) matrix
8381: . ia              - the row pointers
8382: - ja              - the column indices

8384:   Output Parameter:
8385: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8387:   Level: developer

8389:   Note:
8390:   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8391:   us of the array after it has been restored. If you pass `NULL`, it will
8392:   not zero the pointers.  Use of ia or ja after `MatRestoreRowIJ()` is invalid.

8394: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8395: @*/
8396: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8397: {
8398:   PetscFunctionBegin;
8401:   if (ia) PetscAssertPointer(ia, 6);
8402:   if (ja) PetscAssertPointer(ja, 7);
8403:   if (done) PetscAssertPointer(done, 8);
8404:   MatCheckPreallocated(mat, 1);

8406:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8407:   else {
8408:     if (done) *done = PETSC_TRUE;
8409:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8410:     if (n) *n = 0;
8411:     if (ia) *ia = NULL;
8412:     if (ja) *ja = NULL;
8413:   }
8414:   PetscFunctionReturn(PETSC_SUCCESS);
8415: }

8417: /*@C
8418:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8420:   Collective

8422:   Input Parameters:
8423: + mat             - the matrix
8424: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8425: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8426: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8427:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8428:                     always used.

8430:   Output Parameters:
8431: + n    - size of (possibly compressed) matrix
8432: . ia   - the column pointers
8433: . ja   - the row indices
8434: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8436:   Level: developer

8438: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8439: @*/
8440: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8441: {
8442:   PetscFunctionBegin;
8445:   if (ia) PetscAssertPointer(ia, 6);
8446:   if (ja) PetscAssertPointer(ja, 7);
8447:   PetscAssertPointer(done, 8);
8448:   MatCheckPreallocated(mat, 1);

8450:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8451:   else {
8452:     *done = PETSC_TRUE;
8453:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8454:     if (n) *n = 0;
8455:     if (ia) *ia = NULL;
8456:     if (ja) *ja = NULL;
8457:   }
8458:   PetscFunctionReturn(PETSC_SUCCESS);
8459: }

8461: /*@
8462:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8463:   `MatGetColumnIJ()`.

8465:   Collective

8467:   Input Parameters:
8468: + mat        - the matrix
8469: . ncolors    - maximum color value
8470: . n          - number of entries in colorarray
8471: - colorarray - array indicating color for each column

8473:   Output Parameter:
8474: . iscoloring - coloring generated using colorarray information

8476:   Level: developer

8478: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8479: @*/
8480: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8481: {
8482:   PetscFunctionBegin;
8485:   PetscAssertPointer(colorarray, 4);
8486:   PetscAssertPointer(iscoloring, 5);
8487:   MatCheckPreallocated(mat, 1);

8489:   if (!mat->ops->coloringpatch) {
8490:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8491:   } else {
8492:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8493:   }
8494:   PetscFunctionReturn(PETSC_SUCCESS);
8495: }

8497: /*@
8498:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8500:   Logically Collective

8502:   Input Parameter:
8503: . mat - the factored matrix to be reset

8505:   Level: developer

8507:   Notes:
8508:   This routine should be used only with factored matrices formed by in-place
8509:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8510:   format).  This option can save memory, for example, when solving nonlinear
8511:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8512:   ILU(0) preconditioner.

8514:   One can specify in-place ILU(0) factorization by calling
8515: .vb
8516:      PCType(pc,PCILU);
8517:      PCFactorSeUseInPlace(pc);
8518: .ve
8519:   or by using the options -pc_type ilu -pc_factor_in_place

8521:   In-place factorization ILU(0) can also be used as a local
8522:   solver for the blocks within the block Jacobi or additive Schwarz
8523:   methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
8524:   for details on setting local solver options.

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

8530: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8531: @*/
8532: PetscErrorCode MatSetUnfactored(Mat mat)
8533: {
8534:   PetscFunctionBegin;
8537:   MatCheckPreallocated(mat, 1);
8538:   mat->factortype = MAT_FACTOR_NONE;
8539:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8540:   PetscUseTypeMethod(mat, setunfactored);
8541:   PetscFunctionReturn(PETSC_SUCCESS);
8542: }

8544: /*@
8545:   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8546:   as the original matrix.

8548:   Collective

8550:   Input Parameters:
8551: + mat   - the original matrix
8552: . isrow - parallel `IS` containing the rows this processor should obtain
8553: . 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.
8554: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8556:   Output Parameter:
8557: . newmat - the new submatrix, of the same type as the original matrix

8559:   Level: advanced

8561:   Notes:
8562:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8564:   Some matrix types place restrictions on the row and column indices, such
8565:   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;
8566:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.

8568:   The index sets may not have duplicate entries.

8570:   The first time this is called you should use a cll of `MAT_INITIAL_MATRIX`,
8571:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8572:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8573:   will reuse the matrix generated the first time.  You should call `MatDestroy()` on `newmat` when
8574:   you are finished using it.

8576:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8577:   the input matrix.

8579:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8581:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8582:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8584:   Example usage:
8585:   Consider the following 8x8 matrix with 34 non-zero values, that is
8586:   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8587:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8588:   as follows
8589: .vb
8590:             1  2  0  |  0  3  0  |  0  4
8591:     Proc0   0  5  6  |  7  0  0  |  8  0
8592:             9  0 10  | 11  0  0  | 12  0
8593:     -------------------------------------
8594:            13  0 14  | 15 16 17  |  0  0
8595:     Proc1   0 18  0  | 19 20 21  |  0  0
8596:             0  0  0  | 22 23  0  | 24  0
8597:     -------------------------------------
8598:     Proc2  25 26 27  |  0  0 28  | 29  0
8599:            30  0  0  | 31 32 33  |  0 34
8600: .ve

8602:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6].  The resulting submatrix is

8604: .vb
8605:             2  0  |  0  3  0  |  0
8606:     Proc0   5  6  |  7  0  0  |  8
8607:     -------------------------------
8608:     Proc1  18  0  | 19 20 21  |  0
8609:     -------------------------------
8610:     Proc2  26 27  |  0  0 28  | 29
8611:             0  0  | 31 32 33  |  0
8612: .ve

8614: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8615: @*/
8616: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8617: {
8618:   PetscMPIInt size;
8619:   Mat        *local;
8620:   IS          iscoltmp;
8621:   PetscBool   flg;

8623:   PetscFunctionBegin;
8627:   PetscAssertPointer(newmat, 5);
8630:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8631:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8632:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8634:   MatCheckPreallocated(mat, 1);
8635:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8637:   if (!iscol || isrow == iscol) {
8638:     PetscBool   stride;
8639:     PetscMPIInt grabentirematrix = 0, grab;
8640:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8641:     if (stride) {
8642:       PetscInt first, step, n, rstart, rend;
8643:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8644:       if (step == 1) {
8645:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8646:         if (rstart == first) {
8647:           PetscCall(ISGetLocalSize(isrow, &n));
8648:           if (n == rend - rstart) grabentirematrix = 1;
8649:         }
8650:       }
8651:     }
8652:     PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8653:     if (grab) {
8654:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8655:       if (cll == MAT_INITIAL_MATRIX) {
8656:         *newmat = mat;
8657:         PetscCall(PetscObjectReference((PetscObject)mat));
8658:       }
8659:       PetscFunctionReturn(PETSC_SUCCESS);
8660:     }
8661:   }

8663:   if (!iscol) {
8664:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8665:   } else {
8666:     iscoltmp = iscol;
8667:   }

8669:   /* if original matrix is on just one processor then use submatrix generated */
8670:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8671:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8672:     goto setproperties;
8673:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8674:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8675:     *newmat = *local;
8676:     PetscCall(PetscFree(local));
8677:     goto setproperties;
8678:   } else if (!mat->ops->createsubmatrix) {
8679:     /* Create a new matrix type that implements the operation using the full matrix */
8680:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8681:     switch (cll) {
8682:     case MAT_INITIAL_MATRIX:
8683:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8684:       break;
8685:     case MAT_REUSE_MATRIX:
8686:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8687:       break;
8688:     default:
8689:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8690:     }
8691:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8692:     goto setproperties;
8693:   }

8695:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8696:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8697:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

8699: setproperties:
8700:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8701:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8702:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8703:   }
8704:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8705:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8706:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8707:   PetscFunctionReturn(PETSC_SUCCESS);
8708: }

8710: /*@
8711:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8713:   Not Collective

8715:   Input Parameters:
8716: + A - the matrix we wish to propagate options from
8717: - B - the matrix we wish to propagate options to

8719:   Level: beginner

8721:   Note:
8722:   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

8724: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8725: @*/
8726: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8727: {
8728:   PetscFunctionBegin;
8731:   B->symmetry_eternal            = A->symmetry_eternal;
8732:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8733:   B->symmetric                   = A->symmetric;
8734:   B->structurally_symmetric      = A->structurally_symmetric;
8735:   B->spd                         = A->spd;
8736:   B->hermitian                   = A->hermitian;
8737:   PetscFunctionReturn(PETSC_SUCCESS);
8738: }

8740: /*@
8741:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8742:   used during the assembly process to store values that belong to
8743:   other processors.

8745:   Not Collective

8747:   Input Parameters:
8748: + mat   - the matrix
8749: . size  - the initial size of the stash.
8750: - bsize - the initial size of the block-stash(if used).

8752:   Options Database Keys:
8753: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
8754: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

8756:   Level: intermediate

8758:   Notes:
8759:   The block-stash is used for values set with `MatSetValuesBlocked()` while
8760:   the stash is used for values set with `MatSetValues()`

8762:   Run with the option -info and look for output of the form
8763:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8764:   to determine the appropriate value, MM, to use for size and
8765:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8766:   to determine the value, BMM to use for bsize

8768: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8769: @*/
8770: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8771: {
8772:   PetscFunctionBegin;
8775:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8776:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8777:   PetscFunctionReturn(PETSC_SUCCESS);
8778: }

8780: /*@
8781:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8782:   the matrix

8784:   Neighbor-wise Collective

8786:   Input Parameters:
8787: + A - the matrix
8788: . x - the vector to be multiplied by the interpolation operator
8789: - y - the vector to be added to the result

8791:   Output Parameter:
8792: . w - the resulting vector

8794:   Level: intermediate

8796:   Notes:
8797:   `w` may be the same vector as `y`.

8799:   This allows one to use either the restriction or interpolation (its transpose)
8800:   matrix to do the interpolation

8802: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8803: @*/
8804: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8805: {
8806:   PetscInt M, N, Ny;

8808:   PetscFunctionBegin;
8813:   PetscCall(MatGetSize(A, &M, &N));
8814:   PetscCall(VecGetSize(y, &Ny));
8815:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
8816:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
8817:   PetscFunctionReturn(PETSC_SUCCESS);
8818: }

8820: /*@
8821:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8822:   the matrix

8824:   Neighbor-wise Collective

8826:   Input Parameters:
8827: + A - the matrix
8828: - x - the vector to be interpolated

8830:   Output Parameter:
8831: . y - the resulting vector

8833:   Level: intermediate

8835:   Note:
8836:   This allows one to use either the restriction or interpolation (its transpose)
8837:   matrix to do the interpolation

8839: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8840: @*/
8841: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8842: {
8843:   PetscInt M, N, Ny;

8845:   PetscFunctionBegin;
8849:   PetscCall(MatGetSize(A, &M, &N));
8850:   PetscCall(VecGetSize(y, &Ny));
8851:   if (M == Ny) PetscCall(MatMult(A, x, y));
8852:   else PetscCall(MatMultTranspose(A, x, y));
8853:   PetscFunctionReturn(PETSC_SUCCESS);
8854: }

8856: /*@
8857:   MatRestrict - $y = A*x$ or $A^T*x$

8859:   Neighbor-wise Collective

8861:   Input Parameters:
8862: + A - the matrix
8863: - x - the vector to be restricted

8865:   Output Parameter:
8866: . y - the resulting vector

8868:   Level: intermediate

8870:   Note:
8871:   This allows one to use either the restriction or interpolation (its transpose)
8872:   matrix to do the restriction

8874: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8875: @*/
8876: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8877: {
8878:   PetscInt M, N, Nx;

8880:   PetscFunctionBegin;
8884:   PetscCall(MatGetSize(A, &M, &N));
8885:   PetscCall(VecGetSize(x, &Nx));
8886:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
8887:   else PetscCall(MatMult(A, x, y));
8888:   PetscFunctionReturn(PETSC_SUCCESS);
8889: }

8891: /*@
8892:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

8894:   Neighbor-wise Collective

8896:   Input Parameters:
8897: + A - the matrix
8898: . x - the input dense matrix to be multiplied
8899: - w - the input dense matrix to be added to the result

8901:   Output Parameter:
8902: . y - the output dense matrix

8904:   Level: intermediate

8906:   Note:
8907:   This allows one to use either the restriction or interpolation (its transpose)
8908:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8909:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

8911: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8912: @*/
8913: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8914: {
8915:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8916:   PetscBool trans = PETSC_TRUE;
8917:   MatReuse  reuse = MAT_INITIAL_MATRIX;

8919:   PetscFunctionBegin;
8925:   PetscCall(MatGetSize(A, &M, &N));
8926:   PetscCall(MatGetSize(x, &Mx, &Nx));
8927:   if (N == Mx) trans = PETSC_FALSE;
8928:   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);
8929:   Mo = trans ? N : M;
8930:   if (*y) {
8931:     PetscCall(MatGetSize(*y, &My, &Ny));
8932:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
8933:     else {
8934:       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);
8935:       PetscCall(MatDestroy(y));
8936:     }
8937:   }

8939:   if (w && *y == w) { /* this is to minimize changes in PCMG */
8940:     PetscBool flg;

8942:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8943:     if (w) {
8944:       PetscInt My, Ny, Mw, Nw;

8946:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8947:       PetscCall(MatGetSize(*y, &My, &Ny));
8948:       PetscCall(MatGetSize(w, &Mw, &Nw));
8949:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8950:     }
8951:     if (!w) {
8952:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8953:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8954:       PetscCall(PetscObjectDereference((PetscObject)w));
8955:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8956:   }
8957:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
8958:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
8959:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8960:   PetscFunctionReturn(PETSC_SUCCESS);
8961: }

8963: /*@
8964:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

8966:   Neighbor-wise Collective

8968:   Input Parameters:
8969: + A - the matrix
8970: - x - the input dense matrix

8972:   Output Parameter:
8973: . y - the output dense matrix

8975:   Level: intermediate

8977:   Note:
8978:   This allows one to use either the restriction or interpolation (its transpose)
8979:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8980:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

8982: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
8983: @*/
8984: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
8985: {
8986:   PetscFunctionBegin;
8987:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8988:   PetscFunctionReturn(PETSC_SUCCESS);
8989: }

8991: /*@
8992:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

8994:   Neighbor-wise Collective

8996:   Input Parameters:
8997: + A - the matrix
8998: - x - the input dense matrix

9000:   Output Parameter:
9001: . y - the output dense matrix

9003:   Level: intermediate

9005:   Note:
9006:   This allows one to use either the restriction or interpolation (its transpose)
9007:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9008:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9010: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9011: @*/
9012: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9013: {
9014:   PetscFunctionBegin;
9015:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9016:   PetscFunctionReturn(PETSC_SUCCESS);
9017: }

9019: /*@
9020:   MatGetNullSpace - retrieves the null space of a matrix.

9022:   Logically Collective

9024:   Input Parameters:
9025: + mat    - the matrix
9026: - nullsp - the null space object

9028:   Level: developer

9030: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9031: @*/
9032: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9033: {
9034:   PetscFunctionBegin;
9036:   PetscAssertPointer(nullsp, 2);
9037:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9038:   PetscFunctionReturn(PETSC_SUCCESS);
9039: }

9041: /*@C
9042:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9044:   Logically Collective

9046:   Input Parameters:
9047: + n   - the number of matrices
9048: - mat - the array of matrices

9050:   Output Parameters:
9051: . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`

9053:   Level: developer

9055:   Note:
9056:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9058: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9059:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9060: @*/
9061: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9062: {
9063:   PetscFunctionBegin;
9064:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9065:   PetscAssertPointer(mat, 2);
9066:   PetscAssertPointer(nullsp, 3);

9068:   PetscCall(PetscCalloc1(3 * n, nullsp));
9069:   for (PetscInt i = 0; i < n; i++) {
9071:     (*nullsp)[i] = mat[i]->nullsp;
9072:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9073:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9074:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9075:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9076:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9077:   }
9078:   PetscFunctionReturn(PETSC_SUCCESS);
9079: }

9081: /*@C
9082:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9084:   Logically Collective

9086:   Input Parameters:
9087: + n      - the number of matrices
9088: . mat    - the array of matrices
9089: - nullsp - an array of null spaces

9091:   Level: developer

9093:   Note:
9094:   Call `MatGetNullSpaces()` to create `nullsp`

9096: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9097:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9098: @*/
9099: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9100: {
9101:   PetscFunctionBegin;
9102:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9103:   PetscAssertPointer(mat, 2);
9104:   PetscAssertPointer(nullsp, 3);
9105:   PetscAssertPointer(*nullsp, 3);

9107:   for (PetscInt i = 0; i < n; i++) {
9109:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9110:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9111:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9112:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9113:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9114:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9115:   }
9116:   PetscCall(PetscFree(*nullsp));
9117:   PetscFunctionReturn(PETSC_SUCCESS);
9118: }

9120: /*@
9121:   MatSetNullSpace - attaches a null space to a matrix.

9123:   Logically Collective

9125:   Input Parameters:
9126: + mat    - the matrix
9127: - nullsp - the null space object

9129:   Level: advanced

9131:   Notes:
9132:   This null space is used by the `KSP` linear solvers to solve singular systems.

9134:   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`

9136:   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
9137:   to zero but the linear system will still be solved in a least squares sense.

9139:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9140:   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)$.
9141:   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
9142:   $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
9143:   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)$.
9144:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9146:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9147:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9148:   routine also automatically calls `MatSetTransposeNullSpace()`.

9150:   The user should call `MatNullSpaceDestroy()`.

9152: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9153:           `KSPSetPCSide()`
9154: @*/
9155: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9156: {
9157:   PetscFunctionBegin;
9160:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9161:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9162:   mat->nullsp = nullsp;
9163:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9164:   PetscFunctionReturn(PETSC_SUCCESS);
9165: }

9167: /*@
9168:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9170:   Logically Collective

9172:   Input Parameters:
9173: + mat    - the matrix
9174: - nullsp - the null space object

9176:   Level: developer

9178: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9179: @*/
9180: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9181: {
9182:   PetscFunctionBegin;
9185:   PetscAssertPointer(nullsp, 2);
9186:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9187:   PetscFunctionReturn(PETSC_SUCCESS);
9188: }

9190: /*@
9191:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9193:   Logically Collective

9195:   Input Parameters:
9196: + mat    - the matrix
9197: - nullsp - the null space object

9199:   Level: advanced

9201:   Notes:
9202:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9204:   See `MatSetNullSpace()`

9206: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9207: @*/
9208: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9209: {
9210:   PetscFunctionBegin;
9213:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9214:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9215:   mat->transnullsp = nullsp;
9216:   PetscFunctionReturn(PETSC_SUCCESS);
9217: }

9219: /*@
9220:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9221:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9223:   Logically Collective

9225:   Input Parameters:
9226: + mat    - the matrix
9227: - nullsp - the null space object

9229:   Level: advanced

9231:   Notes:
9232:   Overwrites any previous near null space that may have been attached

9234:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9236: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9237: @*/
9238: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9239: {
9240:   PetscFunctionBegin;
9244:   MatCheckPreallocated(mat, 1);
9245:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9246:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9247:   mat->nearnullsp = nullsp;
9248:   PetscFunctionReturn(PETSC_SUCCESS);
9249: }

9251: /*@
9252:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9254:   Not Collective

9256:   Input Parameter:
9257: . mat - the matrix

9259:   Output Parameter:
9260: . nullsp - the null space object, `NULL` if not set

9262:   Level: advanced

9264: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9265: @*/
9266: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9267: {
9268:   PetscFunctionBegin;
9271:   PetscAssertPointer(nullsp, 2);
9272:   MatCheckPreallocated(mat, 1);
9273:   *nullsp = mat->nearnullsp;
9274:   PetscFunctionReturn(PETSC_SUCCESS);
9275: }

9277: /*@
9278:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9280:   Collective

9282:   Input Parameters:
9283: + mat  - the matrix
9284: . row  - row/column permutation
9285: - info - information on desired factorization process

9287:   Level: developer

9289:   Notes:
9290:   Probably really in-place only when level of fill is zero, otherwise allocates
9291:   new space to store factored matrix and deletes previous memory.

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

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

9300: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9301: @*/
9302: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9303: {
9304:   PetscFunctionBegin;
9308:   PetscAssertPointer(info, 3);
9309:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9310:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9311:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9312:   MatCheckPreallocated(mat, 1);
9313:   PetscUseTypeMethod(mat, iccfactor, row, info);
9314:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9315:   PetscFunctionReturn(PETSC_SUCCESS);
9316: }

9318: /*@
9319:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9320:   ghosted ones.

9322:   Not Collective

9324:   Input Parameters:
9325: + mat  - the matrix
9326: - diag - the diagonal values, including ghost ones

9328:   Level: developer

9330:   Notes:
9331:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9333:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`

9335: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9336: @*/
9337: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9338: {
9339:   PetscMPIInt size;

9341:   PetscFunctionBegin;

9346:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9347:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9348:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9349:   if (size == 1) {
9350:     PetscInt n, m;
9351:     PetscCall(VecGetSize(diag, &n));
9352:     PetscCall(MatGetSize(mat, NULL, &m));
9353:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9354:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9355:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9356:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9357:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9358:   PetscFunctionReturn(PETSC_SUCCESS);
9359: }

9361: /*@
9362:   MatGetInertia - Gets the inertia from a factored matrix

9364:   Collective

9366:   Input Parameter:
9367: . mat - the matrix

9369:   Output Parameters:
9370: + nneg  - number of negative eigenvalues
9371: . nzero - number of zero eigenvalues
9372: - npos  - number of positive eigenvalues

9374:   Level: advanced

9376:   Note:
9377:   Matrix must have been factored by `MatCholeskyFactor()`

9379: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9380: @*/
9381: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9382: {
9383:   PetscFunctionBegin;
9386:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9387:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9388:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9389:   PetscFunctionReturn(PETSC_SUCCESS);
9390: }

9392: /*@C
9393:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9395:   Neighbor-wise Collective

9397:   Input Parameters:
9398: + mat - the factored matrix obtained with `MatGetFactor()`
9399: - b   - the right-hand-side vectors

9401:   Output Parameter:
9402: . x - the result vectors

9404:   Level: developer

9406:   Note:
9407:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9408:   call `MatSolves`(A,x,x).

9410: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9411: @*/
9412: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9413: {
9414:   PetscFunctionBegin;
9417:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9418:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9419:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9421:   MatCheckPreallocated(mat, 1);
9422:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9423:   PetscUseTypeMethod(mat, solves, b, x);
9424:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9425:   PetscFunctionReturn(PETSC_SUCCESS);
9426: }

9428: /*@
9429:   MatIsSymmetric - Test whether a matrix is symmetric

9431:   Collective

9433:   Input Parameters:
9434: + A   - the matrix to test
9435: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9437:   Output Parameter:
9438: . flg - the result

9440:   Level: intermediate

9442:   Notes:
9443:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9445:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9447:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9448:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9450: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9451:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9452: @*/
9453: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9454: {
9455:   PetscFunctionBegin;
9457:   PetscAssertPointer(flg, 3);
9458:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9459:   else {
9460:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9461:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9462:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9463:   }
9464:   PetscFunctionReturn(PETSC_SUCCESS);
9465: }

9467: /*@
9468:   MatIsHermitian - Test whether a matrix is Hermitian

9470:   Collective

9472:   Input Parameters:
9473: + A   - the matrix to test
9474: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9476:   Output Parameter:
9477: . flg - the result

9479:   Level: intermediate

9481:   Notes:
9482:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9484:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9486:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9487:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)

9489: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9490:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9491: @*/
9492: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9493: {
9494:   PetscFunctionBegin;
9496:   PetscAssertPointer(flg, 3);
9497:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9498:   else {
9499:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9500:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9501:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9502:   }
9503:   PetscFunctionReturn(PETSC_SUCCESS);
9504: }

9506: /*@
9507:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9509:   Not Collective

9511:   Input Parameter:
9512: . A - the matrix to check

9514:   Output Parameters:
9515: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9516: - flg - the result (only valid if set is `PETSC_TRUE`)

9518:   Level: advanced

9520:   Notes:
9521:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9522:   if you want it explicitly checked

9524:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9525:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9527: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9528: @*/
9529: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9530: {
9531:   PetscFunctionBegin;
9533:   PetscAssertPointer(set, 2);
9534:   PetscAssertPointer(flg, 3);
9535:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9536:     *set = PETSC_TRUE;
9537:     *flg = PetscBool3ToBool(A->symmetric);
9538:   } else *set = PETSC_FALSE;
9539:   PetscFunctionReturn(PETSC_SUCCESS);
9540: }

9542: /*@
9543:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9545:   Not Collective

9547:   Input Parameter:
9548: . A - the matrix to check

9550:   Output Parameters:
9551: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9552: - flg - the result (only valid if set is `PETSC_TRUE`)

9554:   Level: advanced

9556:   Notes:
9557:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9559:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9560:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9562: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9563: @*/
9564: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9565: {
9566:   PetscFunctionBegin;
9568:   PetscAssertPointer(set, 2);
9569:   PetscAssertPointer(flg, 3);
9570:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9571:     *set = PETSC_TRUE;
9572:     *flg = PetscBool3ToBool(A->spd);
9573:   } else *set = PETSC_FALSE;
9574:   PetscFunctionReturn(PETSC_SUCCESS);
9575: }

9577: /*@
9578:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9580:   Not Collective

9582:   Input Parameter:
9583: . A - the matrix to check

9585:   Output Parameters:
9586: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9587: - flg - the result (only valid if set is `PETSC_TRUE`)

9589:   Level: advanced

9591:   Notes:
9592:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9593:   if you want it explicitly checked

9595:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9596:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9598: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9599: @*/
9600: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9601: {
9602:   PetscFunctionBegin;
9604:   PetscAssertPointer(set, 2);
9605:   PetscAssertPointer(flg, 3);
9606:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9607:     *set = PETSC_TRUE;
9608:     *flg = PetscBool3ToBool(A->hermitian);
9609:   } else *set = PETSC_FALSE;
9610:   PetscFunctionReturn(PETSC_SUCCESS);
9611: }

9613: /*@
9614:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9616:   Collective

9618:   Input Parameter:
9619: . A - the matrix to test

9621:   Output Parameter:
9622: . flg - the result

9624:   Level: intermediate

9626:   Notes:
9627:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

9629:   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
9630:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9632: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9633: @*/
9634: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9635: {
9636:   PetscFunctionBegin;
9638:   PetscAssertPointer(flg, 2);
9639:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9640:   else {
9641:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9642:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9643:   }
9644:   PetscFunctionReturn(PETSC_SUCCESS);
9645: }

9647: /*@
9648:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

9650:   Not Collective

9652:   Input Parameter:
9653: . A - the matrix to check

9655:   Output Parameters:
9656: + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9657: - flg - the result (only valid if set is PETSC_TRUE)

9659:   Level: advanced

9661:   Notes:
9662:   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
9663:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9665:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

9667: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9668: @*/
9669: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9670: {
9671:   PetscFunctionBegin;
9673:   PetscAssertPointer(set, 2);
9674:   PetscAssertPointer(flg, 3);
9675:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9676:     *set = PETSC_TRUE;
9677:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9678:   } else *set = PETSC_FALSE;
9679:   PetscFunctionReturn(PETSC_SUCCESS);
9680: }

9682: /*@
9683:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9684:   to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

9686:   Not Collective

9688:   Input Parameter:
9689: . mat - the matrix

9691:   Output Parameters:
9692: + nstash    - the size of the stash
9693: . reallocs  - the number of additional mallocs incurred.
9694: . bnstash   - the size of the block stash
9695: - breallocs - the number of additional mallocs incurred.in the block stash

9697:   Level: advanced

9699: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9700: @*/
9701: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9702: {
9703:   PetscFunctionBegin;
9704:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9705:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9706:   PetscFunctionReturn(PETSC_SUCCESS);
9707: }

9709: /*@
9710:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9711:   parallel layout, `PetscLayout` for rows and columns

9713:   Collective

9715:   Input Parameter:
9716: . mat - the matrix

9718:   Output Parameters:
9719: + right - (optional) vector that the matrix can be multiplied against
9720: - left  - (optional) vector that the matrix vector product can be stored in

9722:   Options Database Key:
9723: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

9725:   Level: advanced

9727:   Notes:
9728:   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()`.

9730:   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`.

9732:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

9734:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
9735:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

9737: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
9738: @*/
9739: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9740: {
9741:   PetscFunctionBegin;
9744:   if (mat->ops->getvecs) {
9745:     PetscUseTypeMethod(mat, getvecs, right, left);
9746:   } else {
9747:     if (right) {
9748:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9749:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9750:       PetscCall(VecSetType(*right, mat->defaultvectype));
9751: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9752:       if (mat->boundtocpu && mat->bindingpropagates) {
9753:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9754:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9755:       }
9756: #endif
9757:     }
9758:     if (left) {
9759:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9760:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9761:       PetscCall(VecSetType(*left, mat->defaultvectype));
9762: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9763:       if (mat->boundtocpu && mat->bindingpropagates) {
9764:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9765:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9766:       }
9767: #endif
9768:     }
9769:   }
9770:   PetscFunctionReturn(PETSC_SUCCESS);
9771: }

9773: /*@
9774:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9775:   with default values.

9777:   Not Collective

9779:   Input Parameter:
9780: . info - the `MatFactorInfo` data structure

9782:   Level: developer

9784:   Notes:
9785:   The solvers are generally used through the `KSP` and `PC` objects, for example
9786:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

9788:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

9790: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9791: @*/
9792: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9793: {
9794:   PetscFunctionBegin;
9795:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9796:   PetscFunctionReturn(PETSC_SUCCESS);
9797: }

9799: /*@
9800:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

9802:   Collective

9804:   Input Parameters:
9805: + mat - the factored matrix
9806: - is  - the index set defining the Schur indices (0-based)

9808:   Level: advanced

9810:   Notes:
9811:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

9813:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

9815:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

9817: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9818:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9819: @*/
9820: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9821: {
9822:   PetscErrorCode (*f)(Mat, IS);

9824:   PetscFunctionBegin;
9829:   PetscCheckSameComm(mat, 1, is, 2);
9830:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9831:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9832:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9833:   PetscCall(MatDestroy(&mat->schur));
9834:   PetscCall((*f)(mat, is));
9835:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9836:   PetscFunctionReturn(PETSC_SUCCESS);
9837: }

9839: /*@
9840:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

9842:   Logically Collective

9844:   Input Parameters:
9845: + F      - the factored matrix obtained by calling `MatGetFactor()`
9846: . S      - location where to return the Schur complement, can be `NULL`
9847: - status - the status of the Schur complement matrix, can be `NULL`

9849:   Level: advanced

9851:   Notes:
9852:   You must call `MatFactorSetSchurIS()` before calling this routine.

9854:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

9856:   The routine provides a copy of the Schur matrix stored within the solver data structures.
9857:   The caller must destroy the object when it is no longer needed.
9858:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

9860:   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)

9862:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

9864:   Developer Note:
9865:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9866:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

9868: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9869: @*/
9870: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9871: {
9872:   PetscFunctionBegin;
9874:   if (S) PetscAssertPointer(S, 2);
9875:   if (status) PetscAssertPointer(status, 3);
9876:   if (S) {
9877:     PetscErrorCode (*f)(Mat, Mat *);

9879:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9880:     if (f) PetscCall((*f)(F, S));
9881:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9882:   }
9883:   if (status) *status = F->schur_status;
9884:   PetscFunctionReturn(PETSC_SUCCESS);
9885: }

9887: /*@
9888:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9890:   Logically Collective

9892:   Input Parameters:
9893: + F      - the factored matrix obtained by calling `MatGetFactor()`
9894: . S      - location where to return the Schur complement, can be `NULL`
9895: - status - the status of the Schur complement matrix, can be `NULL`

9897:   Level: advanced

9899:   Notes:
9900:   You must call `MatFactorSetSchurIS()` before calling this routine.

9902:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

9904:   The routine returns a the Schur Complement stored within the data structures of the solver.

9906:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

9908:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

9910:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

9912:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

9914: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9915: @*/
9916: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9917: {
9918:   PetscFunctionBegin;
9920:   if (S) {
9921:     PetscAssertPointer(S, 2);
9922:     *S = F->schur;
9923:   }
9924:   if (status) {
9925:     PetscAssertPointer(status, 3);
9926:     *status = F->schur_status;
9927:   }
9928:   PetscFunctionReturn(PETSC_SUCCESS);
9929: }

9931: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9932: {
9933:   Mat S = F->schur;

9935:   PetscFunctionBegin;
9936:   switch (F->schur_status) {
9937:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9938:   case MAT_FACTOR_SCHUR_INVERTED:
9939:     if (S) {
9940:       S->ops->solve             = NULL;
9941:       S->ops->matsolve          = NULL;
9942:       S->ops->solvetranspose    = NULL;
9943:       S->ops->matsolvetranspose = NULL;
9944:       S->ops->solveadd          = NULL;
9945:       S->ops->solvetransposeadd = NULL;
9946:       S->factortype             = MAT_FACTOR_NONE;
9947:       PetscCall(PetscFree(S->solvertype));
9948:     }
9949:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9950:     break;
9951:   default:
9952:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9953:   }
9954:   PetscFunctionReturn(PETSC_SUCCESS);
9955: }

9957: /*@
9958:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

9960:   Logically Collective

9962:   Input Parameters:
9963: + F      - the factored matrix obtained by calling `MatGetFactor()`
9964: . S      - location where the Schur complement is stored
9965: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

9967:   Level: advanced

9969: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9970: @*/
9971: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9972: {
9973:   PetscFunctionBegin;
9975:   if (S) {
9977:     *S = NULL;
9978:   }
9979:   F->schur_status = status;
9980:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
9981:   PetscFunctionReturn(PETSC_SUCCESS);
9982: }

9984: /*@
9985:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9987:   Logically Collective

9989:   Input Parameters:
9990: + F   - the factored matrix obtained by calling `MatGetFactor()`
9991: . rhs - location where the right-hand side of the Schur complement system is stored
9992: - sol - location where the solution of the Schur complement system has to be returned

9994:   Level: advanced

9996:   Notes:
9997:   The sizes of the vectors should match the size of the Schur complement

9999:   Must be called after `MatFactorSetSchurIS()`

10001: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10002: @*/
10003: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10004: {
10005:   PetscFunctionBegin;
10012:   PetscCheckSameComm(F, 1, rhs, 2);
10013:   PetscCheckSameComm(F, 1, sol, 3);
10014:   PetscCall(MatFactorFactorizeSchurComplement(F));
10015:   switch (F->schur_status) {
10016:   case MAT_FACTOR_SCHUR_FACTORED:
10017:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10018:     break;
10019:   case MAT_FACTOR_SCHUR_INVERTED:
10020:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10021:     break;
10022:   default:
10023:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10024:   }
10025:   PetscFunctionReturn(PETSC_SUCCESS);
10026: }

10028: /*@
10029:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10031:   Logically Collective

10033:   Input Parameters:
10034: + F   - the factored matrix obtained by calling `MatGetFactor()`
10035: . rhs - location where the right-hand side of the Schur complement system is stored
10036: - sol - location where the solution of the Schur complement system has to be returned

10038:   Level: advanced

10040:   Notes:
10041:   The sizes of the vectors should match the size of the Schur complement

10043:   Must be called after `MatFactorSetSchurIS()`

10045: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10046: @*/
10047: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10048: {
10049:   PetscFunctionBegin;
10056:   PetscCheckSameComm(F, 1, rhs, 2);
10057:   PetscCheckSameComm(F, 1, sol, 3);
10058:   PetscCall(MatFactorFactorizeSchurComplement(F));
10059:   switch (F->schur_status) {
10060:   case MAT_FACTOR_SCHUR_FACTORED:
10061:     PetscCall(MatSolve(F->schur, rhs, sol));
10062:     break;
10063:   case MAT_FACTOR_SCHUR_INVERTED:
10064:     PetscCall(MatMult(F->schur, rhs, sol));
10065:     break;
10066:   default:
10067:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10068:   }
10069:   PetscFunctionReturn(PETSC_SUCCESS);
10070: }

10072: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10073: #if PetscDefined(HAVE_CUDA)
10074: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10075: #endif

10077: /* Schur status updated in the interface */
10078: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10079: {
10080:   Mat S = F->schur;

10082:   PetscFunctionBegin;
10083:   if (S) {
10084:     PetscMPIInt size;
10085:     PetscBool   isdense, isdensecuda;

10087:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10088:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10089:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10090:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10091:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10092:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10093:     if (isdense) {
10094:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10095:     } else if (isdensecuda) {
10096: #if defined(PETSC_HAVE_CUDA)
10097:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10098: #endif
10099:     }
10100:     // HIP??????????????
10101:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10102:   }
10103:   PetscFunctionReturn(PETSC_SUCCESS);
10104: }

10106: /*@
10107:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10109:   Logically Collective

10111:   Input Parameter:
10112: . F - the factored matrix obtained by calling `MatGetFactor()`

10114:   Level: advanced

10116:   Notes:
10117:   Must be called after `MatFactorSetSchurIS()`.

10119:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10121: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10122: @*/
10123: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10124: {
10125:   PetscFunctionBegin;
10128:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10129:   PetscCall(MatFactorFactorizeSchurComplement(F));
10130:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10131:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10132:   PetscFunctionReturn(PETSC_SUCCESS);
10133: }

10135: /*@
10136:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10138:   Logically Collective

10140:   Input Parameter:
10141: . F - the factored matrix obtained by calling `MatGetFactor()`

10143:   Level: advanced

10145:   Note:
10146:   Must be called after `MatFactorSetSchurIS()`

10148: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10149: @*/
10150: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10151: {
10152:   MatFactorInfo info;

10154:   PetscFunctionBegin;
10157:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10158:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10159:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10160:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10161:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10162:   } else {
10163:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10164:   }
10165:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10166:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10167:   PetscFunctionReturn(PETSC_SUCCESS);
10168: }

10170: /*@
10171:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10173:   Neighbor-wise Collective

10175:   Input Parameters:
10176: + A     - the matrix
10177: . P     - the projection matrix
10178: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10179: - 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
10180:           if the result is a dense matrix this is irrelevant

10182:   Output Parameter:
10183: . C - the product matrix

10185:   Level: intermediate

10187:   Notes:
10188:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10190:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10191:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10193:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10195:   Developer Note:
10196:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10198: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10199: @*/
10200: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10201: {
10202:   PetscFunctionBegin;
10203:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10204:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10206:   if (scall == MAT_INITIAL_MATRIX) {
10207:     PetscCall(MatProductCreate(A, P, NULL, C));
10208:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10209:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10210:     PetscCall(MatProductSetFill(*C, fill));

10212:     (*C)->product->api_user = PETSC_TRUE;
10213:     PetscCall(MatProductSetFromOptions(*C));
10214:     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);
10215:     PetscCall(MatProductSymbolic(*C));
10216:   } else { /* scall == MAT_REUSE_MATRIX */
10217:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10218:   }

10220:   PetscCall(MatProductNumeric(*C));
10221:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10222:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10223:     (*C)->spd = A->spd;
10224:   }
10225:   PetscFunctionReturn(PETSC_SUCCESS);
10226: }

10228: /*@
10229:   MatRARt - Creates the matrix product $C = R * A * R^T$

10231:   Neighbor-wise Collective

10233:   Input Parameters:
10234: + A     - the matrix
10235: . R     - the projection matrix
10236: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10237: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10238:           if the result is a dense matrix this is irrelevant

10240:   Output Parameter:
10241: . C - the product matrix

10243:   Level: intermediate

10245:   Notes:
10246:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10248:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10249:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10251:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10252:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10253:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10254:   We recommend using `MatPtAP()` when possible.

10256:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10258: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10259: @*/
10260: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10261: {
10262:   PetscFunctionBegin;
10263:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10264:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10266:   if (scall == MAT_INITIAL_MATRIX) {
10267:     PetscCall(MatProductCreate(A, R, NULL, C));
10268:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10269:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10270:     PetscCall(MatProductSetFill(*C, fill));

10272:     (*C)->product->api_user = PETSC_TRUE;
10273:     PetscCall(MatProductSetFromOptions(*C));
10274:     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);
10275:     PetscCall(MatProductSymbolic(*C));
10276:   } else { /* scall == MAT_REUSE_MATRIX */
10277:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10278:   }

10280:   PetscCall(MatProductNumeric(*C));
10281:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10282:   PetscFunctionReturn(PETSC_SUCCESS);
10283: }

10285: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10286: {
10287:   PetscBool flg = PETSC_TRUE;

10289:   PetscFunctionBegin;
10290:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10291:   if (scall == MAT_INITIAL_MATRIX) {
10292:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10293:     PetscCall(MatProductCreate(A, B, NULL, C));
10294:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10295:     PetscCall(MatProductSetFill(*C, fill));
10296:   } else { /* scall == MAT_REUSE_MATRIX */
10297:     Mat_Product *product = (*C)->product;

10299:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10300:     if (flg && product && product->type != ptype) {
10301:       PetscCall(MatProductClear(*C));
10302:       product = NULL;
10303:     }
10304:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10305:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10306:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10307:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10308:       product        = (*C)->product;
10309:       product->fill  = fill;
10310:       product->clear = PETSC_TRUE;
10311:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10312:       flg = PETSC_FALSE;
10313:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10314:     }
10315:   }
10316:   if (flg) {
10317:     (*C)->product->api_user = PETSC_TRUE;
10318:     PetscCall(MatProductSetType(*C, ptype));
10319:     PetscCall(MatProductSetFromOptions(*C));
10320:     PetscCall(MatProductSymbolic(*C));
10321:   }
10322:   PetscCall(MatProductNumeric(*C));
10323:   PetscFunctionReturn(PETSC_SUCCESS);
10324: }

10326: /*@
10327:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10329:   Neighbor-wise Collective

10331:   Input Parameters:
10332: + A     - the left matrix
10333: . B     - the right matrix
10334: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10335: - 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
10336:           if the result is a dense matrix this is irrelevant

10338:   Output Parameter:
10339: . C - the product matrix

10341:   Notes:
10342:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10344:   `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
10345:   call to this function with `MAT_INITIAL_MATRIX`.

10347:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10349:   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`,
10350:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10352:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10354:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10355:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10357:   Example of Usage:
10358: .vb
10359:      MatProductCreate(A,B,NULL,&C);
10360:      MatProductSetType(C,MATPRODUCT_AB);
10361:      MatProductSymbolic(C);
10362:      MatProductNumeric(C); // compute C=A * B
10363:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10364:      MatProductNumeric(C);
10365:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10366:      MatProductNumeric(C);
10367: .ve

10369:   Level: intermediate

10371: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10372: @*/
10373: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10374: {
10375:   PetscFunctionBegin;
10376:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10377:   PetscFunctionReturn(PETSC_SUCCESS);
10378: }

10380: /*@
10381:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10383:   Neighbor-wise Collective

10385:   Input Parameters:
10386: + A     - the left matrix
10387: . B     - the right matrix
10388: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10389: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10391:   Output Parameter:
10392: . C - the product matrix

10394:   Options Database Key:
10395: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10396:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10397:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10399:   Level: intermediate

10401:   Notes:
10402:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10404:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10406:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10407:   actually needed.

10409:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10410:   and for pairs of `MATMPIDENSE` matrices.

10412:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10413:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10415:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10417: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10418: @*/
10419: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10420: {
10421:   PetscFunctionBegin;
10422:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10423:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10424:   PetscFunctionReturn(PETSC_SUCCESS);
10425: }

10427: /*@
10428:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10430:   Neighbor-wise Collective

10432:   Input Parameters:
10433: + A     - the left matrix
10434: . B     - the right matrix
10435: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10436: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10438:   Output Parameter:
10439: . C - the product matrix

10441:   Level: intermediate

10443:   Notes:
10444:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10446:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10448:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10449:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10451:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10452:   actually needed.

10454:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10455:   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.

10457:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10459: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10460: @*/
10461: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10462: {
10463:   PetscFunctionBegin;
10464:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10465:   PetscFunctionReturn(PETSC_SUCCESS);
10466: }

10468: /*@
10469:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10471:   Neighbor-wise Collective

10473:   Input Parameters:
10474: + A     - the left matrix
10475: . B     - the middle matrix
10476: . C     - the right matrix
10477: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10478: - 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
10479:           if the result is a dense matrix this is irrelevant

10481:   Output Parameter:
10482: . D - the product matrix

10484:   Level: intermediate

10486:   Notes:
10487:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10489:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10491:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10492:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10494:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10495:   actually needed.

10497:   If you have many matrices with the same non-zero structure to multiply, you
10498:   should use `MAT_REUSE_MATRIX` in all calls but the first

10500:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10502: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10503: @*/
10504: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10505: {
10506:   PetscFunctionBegin;
10507:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10508:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10510:   if (scall == MAT_INITIAL_MATRIX) {
10511:     PetscCall(MatProductCreate(A, B, C, D));
10512:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10513:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10514:     PetscCall(MatProductSetFill(*D, fill));

10516:     (*D)->product->api_user = PETSC_TRUE;
10517:     PetscCall(MatProductSetFromOptions(*D));
10518:     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,
10519:                ((PetscObject)C)->type_name);
10520:     PetscCall(MatProductSymbolic(*D));
10521:   } else { /* user may change input matrices when REUSE */
10522:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10523:   }
10524:   PetscCall(MatProductNumeric(*D));
10525:   PetscFunctionReturn(PETSC_SUCCESS);
10526: }

10528: /*@
10529:   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

10531:   Collective

10533:   Input Parameters:
10534: + mat      - the matrix
10535: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10536: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10537: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10539:   Output Parameter:
10540: . matredundant - redundant matrix

10542:   Level: advanced

10544:   Notes:
10545:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10546:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10548:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10549:   calling it.

10551:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10553: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10554: @*/
10555: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10556: {
10557:   MPI_Comm       comm;
10558:   PetscMPIInt    size;
10559:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10560:   Mat_Redundant *redund     = NULL;
10561:   PetscSubcomm   psubcomm   = NULL;
10562:   MPI_Comm       subcomm_in = subcomm;
10563:   Mat           *matseq;
10564:   IS             isrow, iscol;
10565:   PetscBool      newsubcomm = PETSC_FALSE;

10567:   PetscFunctionBegin;
10569:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10570:     PetscAssertPointer(*matredundant, 5);
10572:   }

10574:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10575:   if (size == 1 || nsubcomm == 1) {
10576:     if (reuse == MAT_INITIAL_MATRIX) {
10577:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10578:     } else {
10579:       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");
10580:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10581:     }
10582:     PetscFunctionReturn(PETSC_SUCCESS);
10583:   }

10585:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10586:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10587:   MatCheckPreallocated(mat, 1);

10589:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10590:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10591:     /* create psubcomm, then get subcomm */
10592:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10593:     PetscCallMPI(MPI_Comm_size(comm, &size));
10594:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10596:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10597:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10598:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10599:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10600:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10601:     newsubcomm = PETSC_TRUE;
10602:     PetscCall(PetscSubcommDestroy(&psubcomm));
10603:   }

10605:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10606:   if (reuse == MAT_INITIAL_MATRIX) {
10607:     mloc_sub = PETSC_DECIDE;
10608:     nloc_sub = PETSC_DECIDE;
10609:     if (bs < 1) {
10610:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10611:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10612:     } else {
10613:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10614:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10615:     }
10616:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10617:     rstart = rend - mloc_sub;
10618:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10619:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10620:     PetscCall(ISSetIdentity(iscol));
10621:   } else { /* reuse == MAT_REUSE_MATRIX */
10622:     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");
10623:     /* retrieve subcomm */
10624:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10625:     redund = (*matredundant)->redundant;
10626:     isrow  = redund->isrow;
10627:     iscol  = redund->iscol;
10628:     matseq = redund->matseq;
10629:   }
10630:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10632:   /* get matredundant over subcomm */
10633:   if (reuse == MAT_INITIAL_MATRIX) {
10634:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10636:     /* create a supporting struct and attach it to C for reuse */
10637:     PetscCall(PetscNew(&redund));
10638:     (*matredundant)->redundant = redund;
10639:     redund->isrow              = isrow;
10640:     redund->iscol              = iscol;
10641:     redund->matseq             = matseq;
10642:     if (newsubcomm) {
10643:       redund->subcomm = subcomm;
10644:     } else {
10645:       redund->subcomm = MPI_COMM_NULL;
10646:     }
10647:   } else {
10648:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10649:   }
10650: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10651:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10652:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10653:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10654:   }
10655: #endif
10656:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10657:   PetscFunctionReturn(PETSC_SUCCESS);
10658: }

10660: /*@C
10661:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10662:   a given `Mat`. Each submatrix can span multiple procs.

10664:   Collective

10666:   Input Parameters:
10667: + mat     - the matrix
10668: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10669: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10671:   Output Parameter:
10672: . subMat - parallel sub-matrices each spanning a given `subcomm`

10674:   Level: advanced

10676:   Notes:
10677:   The submatrix partition across processors is dictated by `subComm` a
10678:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10679:   is not restricted to be grouped with consecutive original MPI processes.

10681:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10682:   map directly to the layout of the original matrix [wrt the local
10683:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10684:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10685:   the `subMat`. However the offDiagMat looses some columns - and this is
10686:   reconstructed with `MatSetValues()`

10688:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

10690: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10691: @*/
10692: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10693: {
10694:   PetscMPIInt commsize, subCommSize;

10696:   PetscFunctionBegin;
10697:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10698:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10699:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

10701:   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");
10702:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10703:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10704:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10705:   PetscFunctionReturn(PETSC_SUCCESS);
10706: }

10708: /*@
10709:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

10711:   Not Collective

10713:   Input Parameters:
10714: + mat   - matrix to extract local submatrix from
10715: . isrow - local row indices for submatrix
10716: - iscol - local column indices for submatrix

10718:   Output Parameter:
10719: . submat - the submatrix

10721:   Level: intermediate

10723:   Notes:
10724:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

10726:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
10727:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

10729:   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
10730:   `MatSetValuesBlockedLocal()` will also be implemented.

10732:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10733:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

10735: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10736: @*/
10737: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10738: {
10739:   PetscFunctionBegin;
10743:   PetscCheckSameComm(isrow, 2, iscol, 3);
10744:   PetscAssertPointer(submat, 4);
10745:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

10747:   if (mat->ops->getlocalsubmatrix) {
10748:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10749:   } else {
10750:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10751:   }
10752:   (*submat)->assembled = mat->assembled;
10753:   PetscFunctionReturn(PETSC_SUCCESS);
10754: }

10756: /*@
10757:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

10759:   Not Collective

10761:   Input Parameters:
10762: + mat    - matrix to extract local submatrix from
10763: . isrow  - local row indices for submatrix
10764: . iscol  - local column indices for submatrix
10765: - submat - the submatrix

10767:   Level: intermediate

10769: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10770: @*/
10771: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10772: {
10773:   PetscFunctionBegin;
10777:   PetscCheckSameComm(isrow, 2, iscol, 3);
10778:   PetscAssertPointer(submat, 4);

10781:   if (mat->ops->restorelocalsubmatrix) {
10782:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10783:   } else {
10784:     PetscCall(MatDestroy(submat));
10785:   }
10786:   *submat = NULL;
10787:   PetscFunctionReturn(PETSC_SUCCESS);
10788: }

10790: /*@
10791:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

10793:   Collective

10795:   Input Parameter:
10796: . mat - the matrix

10798:   Output Parameter:
10799: . is - if any rows have zero diagonals this contains the list of them

10801:   Level: developer

10803: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10804: @*/
10805: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10806: {
10807:   PetscFunctionBegin;
10810:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10811:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10813:   if (!mat->ops->findzerodiagonals) {
10814:     Vec                diag;
10815:     const PetscScalar *a;
10816:     PetscInt          *rows;
10817:     PetscInt           rStart, rEnd, r, nrow = 0;

10819:     PetscCall(MatCreateVecs(mat, &diag, NULL));
10820:     PetscCall(MatGetDiagonal(mat, diag));
10821:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10822:     PetscCall(VecGetArrayRead(diag, &a));
10823:     for (r = 0; r < rEnd - rStart; ++r)
10824:       if (a[r] == 0.0) ++nrow;
10825:     PetscCall(PetscMalloc1(nrow, &rows));
10826:     nrow = 0;
10827:     for (r = 0; r < rEnd - rStart; ++r)
10828:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10829:     PetscCall(VecRestoreArrayRead(diag, &a));
10830:     PetscCall(VecDestroy(&diag));
10831:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10832:   } else {
10833:     PetscUseTypeMethod(mat, findzerodiagonals, is);
10834:   }
10835:   PetscFunctionReturn(PETSC_SUCCESS);
10836: }

10838: /*@
10839:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

10841:   Collective

10843:   Input Parameter:
10844: . mat - the matrix

10846:   Output Parameter:
10847: . is - contains the list of rows with off block diagonal entries

10849:   Level: developer

10851: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10852: @*/
10853: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10854: {
10855:   PetscFunctionBegin;
10858:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10859:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10861:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10862:   PetscFunctionReturn(PETSC_SUCCESS);
10863: }

10865: /*@C
10866:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

10868:   Collective; No Fortran Support

10870:   Input Parameter:
10871: . mat - the matrix

10873:   Output Parameter:
10874: . values - the block inverses in column major order (FORTRAN-like)

10876:   Level: advanced

10878:   Notes:
10879:   The size of the blocks is determined by the block size of the matrix.

10881:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10883:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

10885: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10886: @*/
10887: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10888: {
10889:   PetscFunctionBegin;
10891:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10892:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10893:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10894:   PetscFunctionReturn(PETSC_SUCCESS);
10895: }

10897: /*@
10898:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

10900:   Collective; No Fortran Support

10902:   Input Parameters:
10903: + mat     - the matrix
10904: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10905: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

10907:   Output Parameter:
10908: . values - the block inverses in column major order (FORTRAN-like)

10910:   Level: advanced

10912:   Notes:
10913:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

10915:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10917: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10918: @*/
10919: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10920: {
10921:   PetscFunctionBegin;
10923:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10924:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10925:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10926:   PetscFunctionReturn(PETSC_SUCCESS);
10927: }

10929: /*@
10930:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

10932:   Collective

10934:   Input Parameters:
10935: + A - the matrix
10936: - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.

10938:   Level: advanced

10940:   Note:
10941:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

10943: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10944: @*/
10945: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10946: {
10947:   const PetscScalar *vals;
10948:   PetscInt          *dnnz;
10949:   PetscInt           m, rstart, rend, bs, i, j;

10951:   PetscFunctionBegin;
10952:   PetscCall(MatInvertBlockDiagonal(A, &vals));
10953:   PetscCall(MatGetBlockSize(A, &bs));
10954:   PetscCall(MatGetLocalSize(A, &m, NULL));
10955:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10956:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
10957:   PetscCall(PetscMalloc1(m / bs, &dnnz));
10958:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10959:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10960:   PetscCall(PetscFree(dnnz));
10961:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10962:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10963:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10964:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
10965:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10966:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10967:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
10968:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10969:   PetscFunctionReturn(PETSC_SUCCESS);
10970: }

10972: /*@
10973:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10974:   via `MatTransposeColoringCreate()`.

10976:   Collective

10978:   Input Parameter:
10979: . c - coloring context

10981:   Level: intermediate

10983: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
10984: @*/
10985: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10986: {
10987:   MatTransposeColoring matcolor = *c;

10989:   PetscFunctionBegin;
10990:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
10991:   if (--((PetscObject)matcolor)->refct > 0) {
10992:     matcolor = NULL;
10993:     PetscFunctionReturn(PETSC_SUCCESS);
10994:   }

10996:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
10997:   PetscCall(PetscFree(matcolor->rows));
10998:   PetscCall(PetscFree(matcolor->den2sp));
10999:   PetscCall(PetscFree(matcolor->colorforcol));
11000:   PetscCall(PetscFree(matcolor->columns));
11001:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11002:   PetscCall(PetscHeaderDestroy(c));
11003:   PetscFunctionReturn(PETSC_SUCCESS);
11004: }

11006: /*@
11007:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11008:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11009:   `MatTransposeColoring` to sparse `B`.

11011:   Collective

11013:   Input Parameters:
11014: + coloring - coloring context created with `MatTransposeColoringCreate()`
11015: - B        - sparse matrix

11017:   Output Parameter:
11018: . Btdense - dense matrix $B^T$

11020:   Level: developer

11022:   Note:
11023:   These are used internally for some implementations of `MatRARt()`

11025: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11026: @*/
11027: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11028: {
11029:   PetscFunctionBegin;

11034:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11035:   PetscFunctionReturn(PETSC_SUCCESS);
11036: }

11038: /*@
11039:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11040:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11041:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11042:   $C_{sp}$ from $C_{den}$.

11044:   Collective

11046:   Input Parameters:
11047: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11048: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11050:   Output Parameter:
11051: . Csp - sparse matrix

11053:   Level: developer

11055:   Note:
11056:   These are used internally for some implementations of `MatRARt()`

11058: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11059: @*/
11060: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11061: {
11062:   PetscFunctionBegin;

11067:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11068:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11069:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11070:   PetscFunctionReturn(PETSC_SUCCESS);
11071: }

11073: /*@
11074:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11076:   Collective

11078:   Input Parameters:
11079: + mat        - the matrix product C
11080: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11082:   Output Parameter:
11083: . color - the new coloring context

11085:   Level: intermediate

11087: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11088:           `MatTransColoringApplyDenToSp()`
11089: @*/
11090: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11091: {
11092:   MatTransposeColoring c;
11093:   MPI_Comm             comm;

11095:   PetscFunctionBegin;
11096:   PetscAssertPointer(color, 3);

11098:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11099:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11100:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11101:   c->ctype = iscoloring->ctype;
11102:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11103:   *color = c;
11104:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11105:   PetscFunctionReturn(PETSC_SUCCESS);
11106: }

11108: /*@
11109:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11110:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11112:   Not Collective

11114:   Input Parameter:
11115: . mat - the matrix

11117:   Output Parameter:
11118: . state - the current state

11120:   Level: intermediate

11122:   Notes:
11123:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11124:   different matrices

11126:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11128:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11130: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11131: @*/
11132: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11133: {
11134:   PetscFunctionBegin;
11136:   *state = mat->nonzerostate;
11137:   PetscFunctionReturn(PETSC_SUCCESS);
11138: }

11140: /*@
11141:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11142:   matrices from each processor

11144:   Collective

11146:   Input Parameters:
11147: + comm   - the communicators the parallel matrix will live on
11148: . seqmat - the input sequential matrices
11149: . n      - number of local columns (or `PETSC_DECIDE`)
11150: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11152:   Output Parameter:
11153: . mpimat - the parallel matrix generated

11155:   Level: developer

11157:   Note:
11158:   The number of columns of the matrix in EACH processor MUST be the same.

11160: .seealso: [](ch_matrices), `Mat`
11161: @*/
11162: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11163: {
11164:   PetscMPIInt size;

11166:   PetscFunctionBegin;
11167:   PetscCallMPI(MPI_Comm_size(comm, &size));
11168:   if (size == 1) {
11169:     if (reuse == MAT_INITIAL_MATRIX) {
11170:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11171:     } else {
11172:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11173:     }
11174:     PetscFunctionReturn(PETSC_SUCCESS);
11175:   }

11177:   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");

11179:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11180:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11181:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11182:   PetscFunctionReturn(PETSC_SUCCESS);
11183: }

11185: /*@
11186:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11188:   Collective

11190:   Input Parameters:
11191: + A - the matrix to create subdomains from
11192: - N - requested number of subdomains

11194:   Output Parameters:
11195: + n   - number of subdomains resulting on this MPI process
11196: - iss - `IS` list with indices of subdomains on this MPI process

11198:   Level: advanced

11200:   Note:
11201:   The number of subdomains must be smaller than the communicator size

11203: .seealso: [](ch_matrices), `Mat`, `IS`
11204: @*/
11205: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11206: {
11207:   MPI_Comm    comm, subcomm;
11208:   PetscMPIInt size, rank, color;
11209:   PetscInt    rstart, rend, k;

11211:   PetscFunctionBegin;
11212:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11213:   PetscCallMPI(MPI_Comm_size(comm, &size));
11214:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11215:   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);
11216:   *n    = 1;
11217:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11218:   color = rank / k;
11219:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11220:   PetscCall(PetscMalloc1(1, iss));
11221:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11222:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11223:   PetscCallMPI(MPI_Comm_free(&subcomm));
11224:   PetscFunctionReturn(PETSC_SUCCESS);
11225: }

11227: /*@
11228:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11230:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11231:   If they are not the same, uses `MatMatMatMult()`.

11233:   Once the coarse grid problem is constructed, correct for interpolation operators
11234:   that are not of full rank, which can legitimately happen in the case of non-nested
11235:   geometric multigrid.

11237:   Input Parameters:
11238: + restrct     - restriction operator
11239: . dA          - fine grid matrix
11240: . interpolate - interpolation operator
11241: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11242: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11244:   Output Parameter:
11245: . A - the Galerkin coarse matrix

11247:   Options Database Key:
11248: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11250:   Level: developer

11252:   Note:
11253:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11255: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11256: @*/
11257: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11258: {
11259:   IS  zerorows;
11260:   Vec diag;

11262:   PetscFunctionBegin;
11263:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11264:   /* Construct the coarse grid matrix */
11265:   if (interpolate == restrct) {
11266:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11267:   } else {
11268:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11269:   }

11271:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11272:      This can legitimately happen in the case of non-nested geometric multigrid.
11273:      In that event, we set the rows of the matrix to the rows of the identity,
11274:      ignoring the equations (as the RHS will also be zero). */

11276:   PetscCall(MatFindZeroRows(*A, &zerorows));

11278:   if (zerorows != NULL) { /* if there are any zero rows */
11279:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11280:     PetscCall(MatGetDiagonal(*A, diag));
11281:     PetscCall(VecISSet(diag, zerorows, 1.0));
11282:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11283:     PetscCall(VecDestroy(&diag));
11284:     PetscCall(ISDestroy(&zerorows));
11285:   }
11286:   PetscFunctionReturn(PETSC_SUCCESS);
11287: }

11289: /*@C
11290:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11292:   Logically Collective

11294:   Input Parameters:
11295: + mat - the matrix
11296: . op  - the name of the operation
11297: - f   - the function that provides the operation

11299:   Level: developer

11301:   Example Usage:
11302: .vb
11303:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11305:   PetscCall(MatCreateXXX(comm, ..., &A));
11306:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11307: .ve

11309:   Notes:
11310:   See the file `include/petscmat.h` for a complete list of matrix
11311:   operations, which all have the form MATOP_<OPERATION>, where
11312:   <OPERATION> is the name (in all capital letters) of the
11313:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11315:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11316:   sequence as the usual matrix interface routines, since they
11317:   are intended to be accessed via the usual matrix interface
11318:   routines, e.g.,
11319: .vb
11320:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11321: .ve

11323:   In particular each function MUST return `PETSC_SUCCESS` on success and
11324:   nonzero on failure.

11326:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11328: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11329: @*/
11330: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11331: {
11332:   PetscFunctionBegin;
11334:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11335:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11336:   PetscFunctionReturn(PETSC_SUCCESS);
11337: }

11339: /*@C
11340:   MatGetOperation - Gets a matrix operation for any matrix type.

11342:   Not Collective

11344:   Input Parameters:
11345: + mat - the matrix
11346: - op  - the name of the operation

11348:   Output Parameter:
11349: . f - the function that provides the operation

11351:   Level: developer

11353:   Example Usage:
11354: .vb
11355:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11357:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11358: .ve

11360:   Notes:
11361:   See the file `include/petscmat.h` for a complete list of matrix
11362:   operations, which all have the form MATOP_<OPERATION>, where
11363:   <OPERATION> is the name (in all capital letters) of the
11364:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11366:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11368: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11369: @*/
11370: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11371: {
11372:   PetscFunctionBegin;
11374:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11375:   PetscFunctionReturn(PETSC_SUCCESS);
11376: }

11378: /*@
11379:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11381:   Not Collective

11383:   Input Parameters:
11384: + mat - the matrix
11385: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11387:   Output Parameter:
11388: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11390:   Level: advanced

11392:   Note:
11393:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11395: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11396: @*/
11397: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11398: {
11399:   PetscFunctionBegin;
11401:   PetscAssertPointer(has, 3);
11402:   if (mat->ops->hasoperation) {
11403:     PetscUseTypeMethod(mat, hasoperation, op, has);
11404:   } else {
11405:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11406:     else {
11407:       *has = PETSC_FALSE;
11408:       if (op == MATOP_CREATE_SUBMATRIX) {
11409:         PetscMPIInt size;

11411:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11412:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11413:       }
11414:     }
11415:   }
11416:   PetscFunctionReturn(PETSC_SUCCESS);
11417: }

11419: /*@
11420:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11422:   Collective

11424:   Input Parameter:
11425: . mat - the matrix

11427:   Output Parameter:
11428: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11430:   Level: beginner

11432: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11433: @*/
11434: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11435: {
11436:   PetscFunctionBegin;
11439:   PetscAssertPointer(cong, 2);
11440:   if (!mat->rmap || !mat->cmap) {
11441:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11442:     PetscFunctionReturn(PETSC_SUCCESS);
11443:   }
11444:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11445:     PetscCall(PetscLayoutSetUp(mat->rmap));
11446:     PetscCall(PetscLayoutSetUp(mat->cmap));
11447:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11448:     if (*cong) mat->congruentlayouts = 1;
11449:     else mat->congruentlayouts = 0;
11450:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11451:   PetscFunctionReturn(PETSC_SUCCESS);
11452: }

11454: PetscErrorCode MatSetInf(Mat A)
11455: {
11456:   PetscFunctionBegin;
11457:   PetscUseTypeMethod(A, setinf);
11458:   PetscFunctionReturn(PETSC_SUCCESS);
11459: }

11461: /*@
11462:   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
11463:   and possibly removes small values from the graph structure.

11465:   Collective

11467:   Input Parameters:
11468: + A       - the matrix
11469: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11470: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11471: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11472: . num_idx - size of `index` array
11473: - index   - array of block indices to use for graph strength of connection weight

11475:   Output Parameter:
11476: . graph - the resulting graph

11478:   Level: advanced

11480: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11481: @*/
11482: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11483: {
11484:   PetscFunctionBegin;
11488:   PetscAssertPointer(graph, 7);
11489:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11490:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11491:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11492:   PetscFunctionReturn(PETSC_SUCCESS);
11493: }

11495: /*@
11496:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11497:   meaning the same memory is used for the matrix, and no new memory is allocated.

11499:   Collective

11501:   Input Parameters:
11502: + A    - the matrix
11503: - 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

11505:   Level: intermediate

11507:   Developer Note:
11508:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11509:   of the arrays in the data structure are unneeded.

11511: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11512: @*/
11513: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11514: {
11515:   PetscFunctionBegin;
11517:   PetscUseTypeMethod(A, eliminatezeros, keep);
11518:   PetscFunctionReturn(PETSC_SUCCESS);
11519: }

11521: /*@C
11522:   MatGetCurrentMemType - Get the memory location of the matrix

11524:   Not Collective, but the result will be the same on all MPI processes

11526:   Input Parameter:
11527: . A - the matrix whose memory type we are checking

11529:   Output Parameter:
11530: . m - the memory type

11532:   Level: intermediate

11534: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11535: @*/
11536: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11537: {
11538:   PetscFunctionBegin;
11540:   PetscAssertPointer(m, 2);
11541:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11542:   else *m = PETSC_MEMTYPE_HOST;
11543:   PetscFunctionReturn(PETSC_SUCCESS);
11544: }