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>
 10: #include <petscsf.h>

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

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

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

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

 56:   Logically Collective

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

 63:   Level: intermediate

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

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

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

 72:   If values have been inserted with `MatSetValues()`, call `MatAssemblyBegin()` and `MatAssemblyEnd()` before calling this routine.
 73:   The matrix is assembled on return.

 75:   Example Usage:
 76: .vb
 77:      PetscRandomCreate(PETSC_COMM_WORLD, &rctx);
 78:      MatSetRandom(x, rctx);
 79:      PetscRandomDestroy(&rctx);
 80: .ve

 82:   Developer Notes:
 83:   Implementations must leave the matrix assembled with increased object state, assembling it themselves when it is not already the case.
 84:   Implementations that insert only local entries can temporarily set `MAT_NO_OFF_PROC_ENTRIES` to `PETSC_TRUE` during assembly, restoring its previous value afterwards.

 86: .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
 87: @*/
 88: PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
 89: {
 90:   PetscRandom randObj = NULL;

 92:   PetscFunctionBegin;
 96:   PetscCheck(x->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for matrices where you have set values but not yet assembled");
 97:   MatCheckPreallocated(x, 1);

 99:   if (!rctx) {
100:     MPI_Comm comm;
101:     PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
102:     PetscCall(PetscRandomCreate(comm, &randObj));
103:     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
104:     PetscCall(PetscRandomSetFromOptions(randObj));
105:     rctx = randObj;
106:   }
107:   PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
108:   PetscUseTypeMethod(x, setrandom, rctx);
109:   PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));

111:   PetscCall(PetscRandomDestroy(&randObj));
112:   PetscFunctionReturn(PETSC_SUCCESS);
113: }

115: /*@
116:   MatCopyHashToXAIJ - copy hash table entries into an XAIJ matrix type

118:   Logically Collective

120:   Input Parameter:
121: . A - A matrix in unassembled, hash table form

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

126:   Example:
127: .vb
128:      PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
129:      PetscCall(MatCopyHashToXAIJ(A, B));
130: .ve

132:   Level: advanced

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

137: .seealso: [](ch_matrices), `Mat`, `MAT_USE_HASH_TABLE`
138: @*/
139: PetscErrorCode MatCopyHashToXAIJ(Mat A, Mat B)
140: {
141:   PetscFunctionBegin;
143:   PetscUseTypeMethod(A, copyhashtoxaij, B);
144:   PetscFunctionReturn(PETSC_SUCCESS);
145: }

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

150:   Logically Collective

152:   Input Parameter:
153: . mat - the factored matrix

155:   Output Parameters:
156: + pivot - the pivot value computed
157: - row   - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
158:          the share the matrix

160:   Level: advanced

162:   Notes:
163:   This routine does not work for factorizations done with external packages.

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

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

169: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
170: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
171: `MAT_FACTOR_NUMERIC_ZEROPIVOT`
172: @*/
173: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
174: {
175:   PetscFunctionBegin;
177:   PetscAssertPointer(pivot, 2);
178:   PetscAssertPointer(row, 3);
179:   *pivot = mat->factorerror_zeropivot_value;
180:   *row   = mat->factorerror_zeropivot_row;
181:   PetscFunctionReturn(PETSC_SUCCESS);
182: }

184: /*@
185:   MatFactorGetError - gets the error code from a factorization

187:   Logically Collective

189:   Input Parameter:
190: . mat - the factored matrix

192:   Output Parameter:
193: . err - the error code

195:   Level: advanced

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

200: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
201:           `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
202: @*/
203: PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
204: {
205:   PetscFunctionBegin;
207:   PetscAssertPointer(err, 2);
208:   *err = mat->factorerrortype;
209:   PetscFunctionReturn(PETSC_SUCCESS);
210: }

212: /*@
213:   MatFactorClearError - clears the error code in a factorization

215:   Logically Collective

217:   Input Parameter:
218: . mat - the factored matrix

220:   Level: developer

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

225: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
226:           `MatGetErrorCode()`, `MatFactorError`
227: @*/
228: PetscErrorCode MatFactorClearError(Mat mat)
229: {
230:   PetscFunctionBegin;
232:   mat->factorerrortype             = MAT_FACTOR_NOERROR;
233:   mat->factorerror_zeropivot_value = 0.0;
234:   mat->factorerror_zeropivot_row   = 0;
235:   PetscFunctionReturn(PETSC_SUCCESS);
236: }

238: PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
239: {
240:   Vec                r, l;
241:   const PetscScalar *al;
242:   PetscInt           i, nz, gnz, N, n, st;

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

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

297:   Input Parameter:
298: . mat - the matrix

300:   Output Parameter:
301: . keptrows - the rows that are not completely zero

303:   Level: intermediate

305:   Note:
306:   `keptrows` is set to `NULL` if all rows are nonzero.

308:   Developer Note:
309:   If `keptrows` is not `NULL`, it must be sorted.

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

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

330:   Input Parameter:
331: . mat - the matrix

333:   Output Parameter:
334: . zerorows - the rows that are completely zero

336:   Level: intermediate

338:   Note:
339:   `zerorows` is set to `NULL` if no rows are zero.

341: .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
342:  @*/
343: PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
344: {
345:   IS       keptrows;
346:   PetscInt m, n;

348:   PetscFunctionBegin;
351:   PetscAssertPointer(zerorows, 2);
352:   PetscCall(MatFindNonzeroRows(mat, &keptrows));
353:   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
354:      In keeping with this convention, we set zerorows to NULL if there are no zero
355:      rows. */
356:   if (keptrows == NULL) {
357:     *zerorows = NULL;
358:   } else {
359:     PetscCall(MatGetOwnershipRange(mat, &m, &n));
360:     PetscCall(ISComplement(keptrows, m, n, zerorows));
361:     PetscCall(ISDestroy(&keptrows));
362:   }
363:   PetscFunctionReturn(PETSC_SUCCESS);
364: }

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

369:   Not Collective

371:   Input Parameter:
372: . A - the matrix

374:   Output Parameter:
375: . a - the diagonal part (which is a SEQUENTIAL matrix)

377:   Level: advanced

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

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

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

397:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
398:     PetscCheck(size == 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for parallel matrix type %s", ((PetscObject)A)->type_name);
399:     *a = A;
400:   }
401:   PetscFunctionReturn(PETSC_SUCCESS);
402: }

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

407:   Not Collective

409:   Input Parameter:
410: . A - the matrix

412:   Output Parameter:
413: . sf - the `PetscSF`.

415:   Level: advanced

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

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

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

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

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

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

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

454:   Collective

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

459:   Output Parameter:
460: . trace - the sum of the diagonal entries

462:   Level: advanced

464: .seealso: [](ch_matrices), `Mat`
465: @*/
466: PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
467: {
468:   Vec diag;

470:   PetscFunctionBegin;
472:   PetscAssertPointer(trace, 2);
473:   PetscCall(MatCreateVecs(mat, &diag, NULL));
474:   PetscCall(MatGetDiagonal(mat, diag));
475:   PetscCall(VecSum(diag, trace));
476:   PetscCall(VecDestroy(&diag));
477:   PetscFunctionReturn(PETSC_SUCCESS);
478: }

480: /*@
481:   MatRealPart - Zeros out the imaginary part of the matrix

483:   Logically Collective

485:   Input Parameter:
486: . mat - the matrix

488:   Level: advanced

490: .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
491: @*/
492: PetscErrorCode MatRealPart(Mat mat)
493: {
494:   PetscFunctionBegin;
497:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
498:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
499:   MatCheckPreallocated(mat, 1);
500:   PetscUseTypeMethod(mat, realpart);
501:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
502:   PetscFunctionReturn(PETSC_SUCCESS);
503: }

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

508:   Collective

510:   Input Parameter:
511: . mat - the matrix

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

517:   Level: advanced

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

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

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

542:   Logically Collective

544:   Input Parameter:
545: . mat - the matrix

547:   Level: advanced

549: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
550: @*/
551: PetscErrorCode MatImaginaryPart(Mat mat)
552: {
553:   PetscFunctionBegin;
556:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
557:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
558:   MatCheckPreallocated(mat, 1);
559:   PetscUseTypeMethod(mat, imaginarypart);
560:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
561:   PetscFunctionReturn(PETSC_SUCCESS);
562: }

564: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
565: /*@
566:   MatGetRow - Gets a row of a matrix. You MUST call `MatRestoreRow()`
567:   for each row that you get to ensure that your application does
568:   not bleed memory.

570:   Not Collective

572:   Input Parameters:
573: + mat - the matrix
574: - row - the row to get

576:   Output Parameters:
577: + ncols - if not `NULL`, the number of nonzeros in `row`
578: . cols  - if not `NULL`, the column numbers
579: - vals  - if not `NULL`, the numerical values

581:   Level: advanced

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

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

591:   For better efficiency, set `cols` and/or `vals` to `NULL` if you do
592:   not wish to extract these quantities. `vals` must be `NULL` for a matrix with
593:   the `MAT_STRUCTURE_ONLY` option set to true, since no numerical values are stored.

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

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

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

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

610:   Fortran Note:
611: .vb
612:   PetscInt, pointer :: cols(:)
613:   PetscScalar, pointer :: vals(:)
614: .ve

616: .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
617: @*/
618: PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
619: {
620:   PetscInt incols;

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

637: /*@
638:   MatConjugate - replaces the matrix values with their complex conjugates

640:   Logically Collective

642:   Input Parameter:
643: . mat - the matrix

645:   Level: advanced

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

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

664:   Not Collective

666:   Input Parameters:
667: + mat   - the matrix
668: . row   - the row to get
669: . ncols - the number of nonzeros
670: . cols  - the columns of the nonzeros
671: - vals  - if nonzero the column values

673:   Level: advanced

675:   Notes:
676:   This routine should be called after you have finished examining the entries.

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

682:   Fortran Note:
683: .vb
684:   PetscInt, pointer :: cols(:)
685:   PetscScalar, pointer :: vals(:)
686: .ve

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

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

707:   Not Collective

709:   Input Parameter:
710: . mat - the matrix

712:   Level: advanced

714:   Note:
715:   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.

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

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

734:   Not Collective

736:   Input Parameter:
737: . mat - the matrix

739:   Level: advanced

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

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

758: /*@
759:   MatSetOptionsPrefix - Sets the prefix used for searching for all
760:   `Mat` options in the database.

762:   Logically Collective

764:   Input Parameters:
765: + A      - the matrix
766: - prefix - the prefix to prepend to all option names

768:   Level: advanced

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

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

778: .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
779: @*/
780: PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
781: {
782:   PetscFunctionBegin;
784:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
785:   PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
786:   PetscFunctionReturn(PETSC_SUCCESS);
787: }

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

793:   Logically Collective

795:   Input Parameters:
796: + A      - the matrix
797: - prefix - the prefix to prepend to all option names for the factored matrix

799:   Level: developer

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

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

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

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

829:   Logically Collective

831:   Input Parameters:
832: + A      - the matrix
833: - prefix - the prefix to prepend to all option names for the factored matrix

835:   Level: developer

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

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

844: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
845:           `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
846:           `MatSetOptionsPrefix()`
847: @*/
848: PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
849: {
850:   size_t len1, len2, new_len;

852:   PetscFunctionBegin;
854:   if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
855:   if (!A->factorprefix) {
856:     PetscCall(MatSetOptionsPrefixFactor(A, prefix));
857:     PetscFunctionReturn(PETSC_SUCCESS);
858:   }
859:   PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");

861:   PetscCall(PetscStrlen(A->factorprefix, &len1));
862:   PetscCall(PetscStrlen(prefix, &len2));
863:   new_len = len1 + len2 + 1;
864:   PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
865:   PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
866:   PetscFunctionReturn(PETSC_SUCCESS);
867: }

869: /*@
870:   MatAppendOptionsPrefix - Appends to the prefix used for searching for all
871:   matrix options in the database.

873:   Logically Collective

875:   Input Parameters:
876: + A      - the matrix
877: - prefix - the prefix to prepend to all option names

879:   Level: advanced

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

885: .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
886: @*/
887: PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
888: {
889:   PetscFunctionBegin;
891:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
892:   PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
893:   PetscFunctionReturn(PETSC_SUCCESS);
894: }

896: /*@
897:   MatGetOptionsPrefix - Gets the prefix used for searching for all
898:   matrix options in the database.

900:   Not Collective

902:   Input Parameter:
903: . A - the matrix

905:   Output Parameter:
906: . prefix - pointer to the prefix string used

908:   Level: advanced

910: .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
911: @*/
912: PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
913: {
914:   PetscFunctionBegin;
916:   PetscAssertPointer(prefix, 2);
917:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
918:   PetscFunctionReturn(PETSC_SUCCESS);
919: }

921: /*@
922:   MatGetState - Gets a snapshot of the state of a `Mat`

924:   Not Collective

926:   Input Parameter:
927: . A - the matrix

929:   Output Parameter:
930: . state - the matrix state

932:   Level: developer

934:   Note:
935:   The snapshot includes the matrix object id, state, and nonzero state. Use `MatStateCompare()` to determine whether two snapshots are the same, or `MatStateCompareUpdate()` to compare and update a saved snapshot.

937: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatStateCompare()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`, `PetscObjectStateGet()`, `PetscObjectGetId()`, `MatGetNonzeroState()`
938: @*/
939: PetscErrorCode MatGetState(Mat A, MatState *state)
940: {
941:   PetscFunctionBegin;
943:   PetscAssertPointer(state, 2);
944:   state->id           = ((PetscObject)A)->id;
945:   state->state        = ((PetscObject)A)->state;
946:   state->nonzerostate = A->nonzerostate;
947:   PetscFunctionReturn(PETSC_SUCCESS);
948: }

950: /*@
951:   MatStateCompare - Compares two matrix state snapshots

953:   Not Collective

955:   Input Parameters:
956: + state1 - the first matrix state
957: - state2 - the second matrix state

959:   Output Parameter:
960: . same - `PETSC_TRUE` if the matrix object id, state, and nonzero state are the same, `PETSC_FALSE` otherwise

962:   Level: developer

964: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`
965: @*/
966: PetscErrorCode MatStateCompare(MatState state1, MatState state2, PetscBool *same)
967: {
968:   PetscFunctionBegin;
969:   PetscAssertPointer(same, 3);
970:   *same = (PetscBool)(state1.id == state2.id && state1.state == state2.state && state1.nonzerostate == state2.nonzerostate);
971:   PetscFunctionReturn(PETSC_SUCCESS);
972: }

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

977:   Not Collective

979:   Input Parameter:
980: . A - the matrix

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

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

988:   Level: developer

990: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompare()`, `MatStateInvalidate()`
991: @*/
992: PetscErrorCode MatStateCompareUpdate(Mat A, MatState *state, PetscBool *same)
993: {
994:   MatState current;

996:   PetscFunctionBegin;
998:   PetscAssertPointer(state, 2);
999:   PetscAssertPointer(same, 3);
1000:   PetscCall(MatGetState(A, &current));
1001:   PetscCall(MatStateCompare(current, *state, same));
1002:   *state = current;
1003:   PetscFunctionReturn(PETSC_SUCCESS);
1004: }

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

1009:   Collective

1011:   Input Parameter:
1012: . A - the matrix

1014:   Level: beginner

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

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

1023:   Currently only supported for  `MATAIJ` matrices.

1025: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
1026: @*/
1027: PetscErrorCode MatResetPreallocation(Mat A)
1028: {
1029:   PetscFunctionBegin;
1032:   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
1033:   PetscFunctionReturn(PETSC_SUCCESS);
1034: }

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

1039:   Collective

1041:   Input Parameter:
1042: . A - the matrix

1044:   Level: intermediate

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

1049:   Currently only supported for `MATAIJ` matrices.

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

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

1072:   Collective

1074:   Input Parameter:
1075: . A - the matrix

1077:   Level: advanced

1079:   Notes:
1080:   If no preallocation has been provided for a `MATAIJ`, `MATBAIJ`, or `MATSBAIJ` matrix, `MatSetUp()` makes it record the
1081:   values given to `MatSetValues()` in a hash table, and the first assembly determines the nonzero pattern from it. Providing
1082:   preallocation instead, for example with `MatXAIJSetPreallocation()` or `MatSetPreallocationCOO()`, disables hash-table mode.

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

1086: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
1087: @*/
1088: PetscErrorCode MatSetUp(Mat A)
1089: {
1090:   PetscFunctionBegin;
1092:   if (!((PetscObject)A)->type_name) {
1093:     PetscMPIInt size;

1095:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1096:     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
1097:   }
1098:   if (!A->preallocated) PetscTryTypeMethod(A, setup);
1099:   PetscCall(PetscLayoutSetUp(A->rmap));
1100:   PetscCall(PetscLayoutSetUp(A->cmap));
1101:   A->preallocated = PETSC_TRUE;
1102:   PetscFunctionReturn(PETSC_SUCCESS);
1103: }

1105: #if PetscDefined(HAVE_SAWS)
1106: #include <petscviewersaws.h>
1107: #endif

1109: /*
1110:    If threadsafety is on extraneous matrices may be printed

1112:    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1113: */
1114: #if !PetscDefined(HAVE_THREADSAFETY)
1115: static PetscInt insidematview = 0;
1116: #endif

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

1121:   Collective

1123:   Input Parameters:
1124: + A    - the matrix
1125: . obj  - optional additional object that provides the options prefix to use
1126: - name - command line option

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

1131:   Level: intermediate

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

1137: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`, `PetscOptionsCreateViewer()`
1138: @*/
1139: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1140: {
1141:   PetscFunctionBegin;
1143: #if !PetscDefined(HAVE_THREADSAFETY)
1144:   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1145: #endif
1146:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1147:   PetscFunctionReturn(PETSC_SUCCESS);
1148: }

1150: /*@
1151:   MatView - display information about a matrix in a variety ways

1153:   Collective on viewer

1155:   Input Parameters:
1156: + mat    - the matrix
1157: - viewer - visualization context

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

1163:   Level: beginner

1165:   Notes:
1166:   The available visualization contexts include
1167: +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1168: .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1169: .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1170: -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure

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

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

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

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

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

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

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

1203:   One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1204:   and then use the following mouse functions.
1205: .vb
1206:   left mouse: zoom in
1207:   middle mouse: zoom out
1208:   right mouse: continue with the simulation
1209: .ve

1211: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1212:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`, `PetscOptionsCreateViewer()`
1213: @*/
1214: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1215: {
1216:   PetscInt          rows, cols, rbs, cbs;
1217:   PetscBool         isascii, isstring, issaws;
1218:   PetscViewerFormat format;
1219:   PetscMPIInt       size;

1221:   PetscFunctionBegin;
1224:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

1227:   PetscCall(PetscViewerGetFormat(viewer, &format));
1228:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1229:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

1231: #if !PetscDefined(HAVE_THREADSAFETY)
1232:   insidematview++;
1233: #endif
1234:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1235:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1236:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1237:   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");

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

1262:       PetscCall(PetscViewerASCIIPushTab(viewer));
1263:       PetscCall(MatGetSize(mat, &rows, &cols));
1264:       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1265:       if (rbs != 1 || cbs != 1) {
1266:         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" : ""));
1267:         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1268:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1269:       if (mat->factortype) {
1270:         MatSolverType solver;

1272:         PetscCall(MatFactorGetSolverType(mat, &solver));
1273:         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1274:         PetscCall(PetscStrcmpAny(solver, &nz_factor, MATSOLVERUMFPACK, MATSOLVERCHOLMOD, MATSOLVERSUPERLU, MATSOLVERSUPERLU_DIST, MATSOLVERSTRUMPACK, MATSOLVERHTOOL, ""));
1275:         nz_factor = !nz_factor;
1276:       }
1277:       if (mat->ops->getinfo) {
1278:         PetscBool is_constant_or_diagonal;

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

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

1302:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1303:         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1304:         PetscCall(PetscViewerASCIIPushTab(viewer));
1305:         PetscCall(ISView(tmp, viewer));
1306:         PetscCall(PetscViewerASCIIPopTab(viewer));
1307:         PetscCall(ISDestroy(&tmp));
1308:       }
1309:     }
1310:   } else if (issaws) {
1311: #if PetscDefined(HAVE_SAWS)
1312:     PetscMPIInt rank;

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

1344: #if PetscDefined(USE_DEBUG)
1345: #include <../src/sys/totalview/tv_data_display.h>
1346: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1347: {
1348:   TV_add_row("Local rows", "int", &mat->rmap->n);
1349:   TV_add_row("Local columns", "int", &mat->cmap->n);
1350:   TV_add_row("Global rows", "int", &mat->rmap->N);
1351:   TV_add_row("Global columns", "int", &mat->cmap->N);
1352:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1353:   return TV_format_OK;
1354: }
1355: #endif

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

1363:   Collective

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

1370:   Options Database Key:
1371: . -matload_block_size bs - set block size

1373:   Level: beginner

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

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

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

1388:   In parallel, each process can load a subset of rows (or the
1389:   entire matrix). This routine is especially useful when a large
1390:   matrix is stored on disk and only part of it is desired on each
1391:   process. For example, a parallel solver may access only some of
1392:   the rows from each process. The algorithm used here reads
1393:   relatively small blocks of data rather than reading the entire
1394:   matrix and then subsetting it.

1396:   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1397:   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1398:   or the sequence like
1399: .vb
1400:     PetscViewer v;
1401:     PetscViewerCreate(PETSC_COMM_WORLD, &v);
1402:     PetscViewerSetType(v, PETSCVIEWERBINARY);
1403:     PetscViewerSetFromOptions(v);
1404:     PetscViewerFileSetMode(v, FILE_MODE_READ);
1405:     PetscViewerFileSetName(v, "datafile");
1406: .ve
1407:   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1408: .vb
1409:   -viewer_type (binary|hdf5)
1410: .ve

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1476: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1477:  @*/
1478: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1479: {
1480:   PetscBool flg;

1482:   PetscFunctionBegin;

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

1488:   flg = PETSC_FALSE;
1489:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1490:   if (flg) {
1491:     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1492:     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1493:   }
1494:   flg = PETSC_FALSE;
1495:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1496:   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));

1498:   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1499:   PetscUseTypeMethod(mat, load, viewer);
1500:   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1501:   PetscFunctionReturn(PETSC_SUCCESS);
1502: }

1504: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1505: {
1506:   Mat_Redundant *redund = *redundant;

1508:   PetscFunctionBegin;
1509:   if (redund) {
1510:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1511:       PetscCall(ISDestroy(&redund->isrow));
1512:       PetscCall(ISDestroy(&redund->iscol));
1513:       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1514:     } else {
1515:       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1516:       PetscCall(PetscFree(redund->sbuf_j));
1517:       PetscCall(PetscFree(redund->sbuf_a));
1518:       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1519:         PetscCall(PetscFree(redund->rbuf_j[i]));
1520:         PetscCall(PetscFree(redund->rbuf_a[i]));
1521:       }
1522:       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1523:     }

1525:     PetscCall(PetscCommDestroy(&redund->subcomm));
1526:     PetscCall(PetscFree(redund));
1527:   }
1528:   PetscFunctionReturn(PETSC_SUCCESS);
1529: }

1531: /*@
1532:   MatDestroy - Frees space taken by a matrix.

1534:   Collective

1536:   Input Parameter:
1537: . A - the matrix

1539:   Level: beginner

1541:   Developer Note:
1542:   `MatHeaderMerge()` and `MatHeaderReplace()` manipulate the data in the `Mat` object and likely need changes
1543:   if changes are needed here.

1545: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1546: @*/
1547: PetscErrorCode MatDestroy(Mat *A)
1548: {
1549:   PetscFunctionBegin;
1550:   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1552:   if (--((PetscObject)*A)->refct > 0) {
1553:     *A = NULL;
1554:     PetscFunctionReturn(PETSC_SUCCESS);
1555:   }

1557:   /* if memory was published with SAWs then destroy it */
1558:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1559:   PetscTryTypeMethod(*A, destroy);

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

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

1587:   Not Collective

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

1599:   Level: beginner

1601:   Notes:
1602:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1603:   options cannot be mixed without intervening calls to the assembly
1604:   routines.

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

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

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

1617:   Fortran Notes:
1618:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1619: .vb
1620:   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1621: .ve

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

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

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

1642:   if (PetscDefined(USE_DEBUG)) {
1643:     PetscInt i, j;

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

1662:   if (mat->assembled) {
1663:     mat->was_assembled = PETSC_TRUE;
1664:     mat->assembled     = PETSC_FALSE;
1665:   }
1666:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1667:   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1668:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1669:   PetscFunctionReturn(PETSC_SUCCESS);
1670: }

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

1678:   Not Collective

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

1688:   Level: beginner

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

1693:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1694:   options cannot be mixed without intervening calls to the assembly
1695:   routines.

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

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

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

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

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

1715: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1716:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1717: @*/
1718: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1719: {
1720:   PetscInt        m, n;
1721:   const PetscInt *rows, *cols;

1723:   PetscFunctionBeginHot;
1725:   PetscCall(ISGetIndices(ism, &rows));
1726:   PetscCall(ISGetIndices(isn, &cols));
1727:   PetscCall(ISGetLocalSize(ism, &m));
1728:   PetscCall(ISGetLocalSize(isn, &n));
1729:   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1730:   PetscCall(ISRestoreIndices(ism, &rows));
1731:   PetscCall(ISRestoreIndices(isn, &cols));
1732:   PetscFunctionReturn(PETSC_SUCCESS);
1733: }

1735: /*@
1736:   MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix

1738:   Not Collective

1740:   Input Parameters:
1741: + mat - the matrix
1742: . row - the row to set
1743: - v   - a one-dimensional array that contains the values

1745:   Level: intermediate

1747:   Notes:
1748:   Currently only supported for `MATAIJ`.

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

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

1754:   `row` must belong to this MPI process

1756: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1757:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1758: @*/
1759: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1760: {
1761:   PetscInt globalrow;

1763:   PetscFunctionBegin;
1766:   PetscAssertPointer(v, 3);
1767:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1768:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1769:   PetscFunctionReturn(PETSC_SUCCESS);
1770: }

1772: /*@
1773:   MatSetValuesRow - Inserts a row of nonzero values into a matrix

1775:   Not Collective

1777:   Input Parameters:
1778: + mat - the matrix
1779: . row - the row to set
1780: - v   - a one dimensional array of values

1782:   Level: advanced

1784:   Notes:
1785:   Currently only supported for `MATAIJ`.

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

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

1791:   `row` must belong to this process

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

1807:   if (mat->assembled) {
1808:     mat->was_assembled = PETSC_TRUE;
1809:     mat->assembled     = PETSC_FALSE;
1810:   }
1811:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1812:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1813:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1814:   PetscFunctionReturn(PETSC_SUCCESS);
1815: }

1817: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1818: /*@
1819:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1820:   Using structured grid indexing

1822:   Not Collective

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

1834:   Level: beginner

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

1839:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1840:   options cannot be mixed without intervening calls to the assembly
1841:   routines.

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

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

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

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

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

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

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

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

1870:   Fortran Notes:
1871:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1872: .vb
1873:   call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1874: .ve

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

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

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

1892:   PetscFunctionBegin;
1893:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1896:   PetscAssertPointer(idxm, 3);
1897:   PetscAssertPointer(idxn, 5);

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

1932: /*@
1933:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1934:   Using structured grid indexing

1936:   Not Collective

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

1948:   Level: beginner

1950:   Notes:
1951:   By default the values, `v`, are row-oriented and unsorted.
1952:   See `MatSetOption()` for other options.

1954:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1955:   options cannot be mixed without intervening calls to the assembly
1956:   routines.

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

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

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

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

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

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

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

1982:   Fortran Notes:
1983:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1984: .vb
1985:   call MatSetValuesBlockedStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1986: .ve

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

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

2001:   PetscFunctionBegin;
2002:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2005:   PetscAssertPointer(idxm, 3);
2006:   PetscAssertPointer(idxn, 5);
2007:   PetscAssertPointer(v, 6);

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

2042: /*@
2043:   MatSetStencil - Sets the grid information for setting values into a matrix via
2044:   `MatSetValuesStencil()`

2046:   Not Collective

2048:   Input Parameters:
2049: + mat    - the matrix
2050: . dim    - dimension of the grid 1, 2, or 3
2051: . dims   - number of grid points in x, y, and z direction, including ghost points on your process
2052: . starts - starting point of ghost nodes on your process in x, y, and z direction
2053: - dof    - number of degrees of freedom per node

2055:   Level: beginner

2057:   Notes:
2058:   Inspired by the structured grid interface to the HYPRE package
2059:   (www.llnl.gov/CASC/hyper)

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

2064: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2065:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
2066: @*/
2067: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
2068: {
2069:   PetscFunctionBegin;
2071:   PetscAssertPointer(dims, 3);
2072:   PetscAssertPointer(starts, 4);

2074:   mat->stencil.dim = dim + (dof > 1);
2075:   for (PetscInt i = 0; i < dim; i++) {
2076:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
2077:     mat->stencil.starts[i] = starts[dim - i - 1];
2078:   }
2079:   mat->stencil.dims[dim]   = dof;
2080:   mat->stencil.starts[dim] = 0;
2081:   mat->stencil.noc         = (PetscBool)(dof == 1);
2082:   PetscFunctionReturn(PETSC_SUCCESS);
2083: }

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

2088:   Not Collective

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

2100:   Level: intermediate

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

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

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

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

2117:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2118:   options cannot be mixed without intervening calls to the assembly
2119:   routines.

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

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

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

2135:   Example:
2136: .vb
2137:    Suppose m=n=2 and block size(bs) = 2 The array is

2139:    1  2  | 3  4
2140:    5  6  | 7  8
2141:    - - - | - - -
2142:    9  10 | 11 12
2143:    13 14 | 15 16

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

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

2152:   Fortran Notes:
2153:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2154: .vb
2155:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2156: .ve

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

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

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

2220: /*@
2221:   MatGetValues - Gets a block of local values from a matrix.

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

2225:   Input Parameters:
2226: + mat  - the matrix
2227: . v    - a logically two-dimensional array for storing the values
2228: . m    - the number of rows
2229: . idxm - the  global indices of the rows
2230: . n    - the number of columns
2231: - idxn - the global indices of the columns

2233:   Level: advanced

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

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

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

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

2246:   `MatGetValues()` requires that the matrix has been assembled
2247:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`. Thus, calls to
2248:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2249:   without intermediate matrix assembly.

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

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

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

2273:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2274:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2275:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2276:   PetscFunctionReturn(PETSC_SUCCESS);
2277: }

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

2283:   Not Collective

2285:   Input Parameters:
2286: + mat  - the matrix
2287: . nrow - number of rows
2288: . irow - the row local indices
2289: . ncol - number of columns
2290: - icol - the column local indices

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

2296:   Level: advanced

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

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

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

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

2350:   Not Collective

2352:   Input Parameters:
2353: + mat  - the matrix
2354: . nb   - the number of blocks
2355: . bs   - the number of rows (and columns) in each block
2356: . rows - a concatenation of the rows for each block
2357: - v    - a concatenation of logically two-dimensional arrays of values

2359:   Level: advanced

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

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

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

2378:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2379:   for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2380:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2381:   PetscFunctionReturn(PETSC_SUCCESS);
2382: }

2384: /*@
2385:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2386:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2387:   using a local (per-process) numbering.

2389:   Not Collective

2391:   Input Parameters:
2392: + x        - the matrix
2393: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2394: - cmapping - column mapping

2396:   Level: intermediate

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

2401: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2402: @*/
2403: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2404: {
2405:   PetscFunctionBegin;
2410:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2411:   else {
2412:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2413:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2414:   }
2415:   PetscFunctionReturn(PETSC_SUCCESS);
2416: }

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

2421:   Not Collective

2423:   Input Parameter:
2424: . A - the matrix

2426:   Output Parameters:
2427: + rmapping - row mapping
2428: - cmapping - column mapping

2430:   Level: advanced

2432: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2433: @*/
2434: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2435: {
2436:   PetscFunctionBegin;
2439:   if (rmapping) {
2440:     PetscAssertPointer(rmapping, 2);
2441:     *rmapping = A->rmap->mapping;
2442:   }
2443:   if (cmapping) {
2444:     PetscAssertPointer(cmapping, 3);
2445:     *cmapping = A->cmap->mapping;
2446:   }
2447:   PetscFunctionReturn(PETSC_SUCCESS);
2448: }

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

2453:   Logically Collective

2455:   Input Parameters:
2456: + A    - the matrix
2457: . rmap - row layout
2458: - cmap - column layout

2460:   Level: advanced

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

2465: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2466: @*/
2467: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2468: {
2469:   PetscFunctionBegin;
2471:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2472:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2473:   PetscFunctionReturn(PETSC_SUCCESS);
2474: }

2476: /*@
2477:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2479:   Not Collective

2481:   Input Parameter:
2482: . A - the matrix

2484:   Output Parameters:
2485: + rmap - row layout
2486: - cmap - column layout

2488:   Level: advanced

2490: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2491: @*/
2492: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2493: {
2494:   PetscFunctionBegin;
2497:   if (rmap) {
2498:     PetscAssertPointer(rmap, 2);
2499:     *rmap = A->rmap;
2500:   }
2501:   if (cmap) {
2502:     PetscAssertPointer(cmap, 3);
2503:     *cmap = A->cmap;
2504:   }
2505:   PetscFunctionReturn(PETSC_SUCCESS);
2506: }

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

2512:   Not Collective

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

2524:   Level: intermediate

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

2529:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2530:   options cannot be mixed without intervening calls to the assembly
2531:   routines.

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

2536:   Fortran Notes:
2537:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2538: .vb
2539:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2540: .ve

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

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

2564:   if (mat->assembled) {
2565:     mat->was_assembled = PETSC_TRUE;
2566:     mat->assembled     = PETSC_FALSE;
2567:   }
2568:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2569:   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, v, addv);
2570:   else {
2571:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2572:     const PetscInt *irowm, *icolm;

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

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

2601:   Not Collective

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

2613:   Level: intermediate

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

2619:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2620:   options cannot be mixed without intervening calls to the assembly
2621:   routines.

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

2626:   Fortran Notes:
2627:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2628: .vb
2629:   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2630: .ve

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

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

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

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

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

2702:   Collective

2704:   Input Parameters:
2705: + mat - the matrix
2706: - x   - the vector to be multiplied

2708:   Output Parameter:
2709: . y - the result

2711:   Level: developer

2713:   Note:
2714:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2715:   call `MatMultDiagonalBlock`(A,y,y).

2717: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2718: @*/
2719: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2720: {
2721:   PetscFunctionBegin;

2727:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2728:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2729:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2730:   MatCheckPreallocated(mat, 1);

2732:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2733:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2734:   PetscFunctionReturn(PETSC_SUCCESS);
2735: }

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

2740:   Neighbor-wise Collective

2742:   Input Parameters:
2743: + mat - the matrix
2744: - x   - the vector to be multiplied

2746:   Output Parameter:
2747: . y - the result

2749:   Level: beginner

2751:   Note:
2752:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2753:   call `MatMult`(A,y,y).

2755: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2756: @*/
2757: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2758: {
2759:   PetscFunctionBegin;
2763:   VecCheckAssembled(x);
2765:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2766:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2767:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2768:   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);
2769:   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);
2770:   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);
2771:   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);
2772:   PetscCall(VecSetErrorIfLocked(y, 3));
2773:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2774:   MatCheckPreallocated(mat, 1);

2776:   PetscCall(VecLockReadPush(x));
2777:   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2778:   PetscUseTypeMethod(mat, mult, x, y);
2779:   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2780:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2781:   PetscCall(VecLockReadPop(x));
2782:   PetscFunctionReturn(PETSC_SUCCESS);
2783: }

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

2788:   Neighbor-wise Collective

2790:   Input Parameters:
2791: + mat - the matrix
2792: - x   - the vector to be multiplied

2794:   Output Parameter:
2795: . y - the result

2797:   Level: beginner

2799:   Notes:
2800:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2801:   call `MatMultTranspose`(A,y,y).

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

2806: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2807: @*/
2808: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2809: {
2810:   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;

2812:   PetscFunctionBegin;
2816:   VecCheckAssembled(x);

2819:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2820:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2821:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2822:   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);
2823:   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);
2824:   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);
2825:   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);
2826:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2827:   MatCheckPreallocated(mat, 1);

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

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

2846:   Neighbor-wise Collective

2848:   Input Parameters:
2849: + mat - the matrix
2850: - x   - the vector to be multiplied

2852:   Output Parameter:
2853: . y - the result

2855:   Level: beginner

2857:   Notes:
2858:   The vectors `x` and `y` cannot be the same. I.e., one cannot
2859:   call `MatMultHermitianTranspose`(A,y,y).

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

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

2865: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2866: @*/
2867: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2868: {
2869:   PetscFunctionBegin;

2875:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2876:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2877:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2878:   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);
2879:   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);
2880:   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);
2881:   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);
2882:   MatCheckPreallocated(mat, 1);

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

2906: /*@
2907:   MatMultAdd -  Computes $v3 = v2 + A v1$.

2909:   Neighbor-wise Collective

2911:   Input Parameters:
2912: + mat - the matrix
2913: . v1  - the vector to be multiplied by `mat`
2914: - v2  - the vector to be added to the result

2916:   Output Parameter:
2917: . v3 - the result

2919:   Level: beginner

2921:   Note:
2922:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2923:   call `MatMultAdd`(A,v1,v2,v1).

2925: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2926: @*/
2927: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2928: {
2929:   PetscFunctionBegin;

2936:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2937:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2938:   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);
2939:   /* 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);
2940:      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); */
2941:   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);
2942:   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);
2943:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2944:   MatCheckPreallocated(mat, 1);

2946:   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2947:   PetscCall(VecLockReadPush(v1));
2948:   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2949:   PetscCall(VecLockReadPop(v1));
2950:   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2951:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2952:   PetscFunctionReturn(PETSC_SUCCESS);
2953: }

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

2958:   Neighbor-wise Collective

2960:   Input Parameters:
2961: + mat - the matrix
2962: . v1  - the vector to be multiplied by the transpose of the matrix
2963: - v2  - the vector to be added to the result

2965:   Output Parameter:
2966: . v3 - the result

2968:   Level: beginner

2970:   Note:
2971:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2972:   call `MatMultTransposeAdd`(A,v1,v2,v1).

2974: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2975: @*/
2976: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2977: {
2978:   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;

2980:   PetscFunctionBegin;

2987:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2988:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2989:   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);
2990:   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);
2991:   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);
2992:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2993:   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2994:   MatCheckPreallocated(mat, 1);

2996:   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2997:   PetscCall(VecLockReadPush(v1));
2998:   PetscCall((*op)(mat, v1, v2, v3));
2999:   PetscCall(VecLockReadPop(v1));
3000:   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
3001:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3002:   PetscFunctionReturn(PETSC_SUCCESS);
3003: }

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

3008:   Neighbor-wise Collective

3010:   Input Parameters:
3011: + mat - the matrix
3012: . v1  - the vector to be multiplied by the Hermitian transpose
3013: - v2  - the vector to be added to the result

3015:   Output Parameter:
3016: . v3 - the result

3018:   Level: beginner

3020:   Note:
3021:   The vectors `v1` and `v3` cannot be the same. I.e., one cannot
3022:   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).

3024: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
3025: @*/
3026: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
3027: {
3028:   PetscFunctionBegin;

3035:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3036:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3037:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
3038:   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);
3039:   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);
3040:   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);
3041:   MatCheckPreallocated(mat, 1);

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

3065: static PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
3066: {
3067:   PetscFunctionBegin;
3068:   if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, NULL, &mat->dot_vec));
3069:   PetscCall(MatMult(mat, x, mat->dot_vec));
3070:   PetscCall(VecDot(mat->dot_vec, y, val));
3071:   PetscFunctionReturn(PETSC_SUCCESS);
3072: }

3074: static PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
3075: {
3076:   PetscScalar sval;

3078:   PetscFunctionBegin;
3079:   PetscCall(MatADot(mat, x, x, &sval));
3080:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3081:   PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) <= 100 * PETSC_MACHINE_EPSILON * PetscMax(1.0, PetscAbsScalar(sval)), PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
3082:   *val = PetscSqrtReal(PetscRealPart(sval));
3083:   PetscFunctionReturn(PETSC_SUCCESS);
3084: }

3086: /*@
3087:   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)
3088:   positive definite.

3090:   Collective

3092:   Input Parameters:
3093: + mat - matrix used to define the inner product
3094: . x   - first vector
3095: - y   - second vector

3097:   Output Parameter:
3098: . val - the dot product with respect to `A`

3100:   Level: intermediate

3102:   Note:
3103:   For complex vectors, `MatADot()` computes
3104: $$
3105:   val = (x,y)_A = y^H A x,
3106: $$
3107:   where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3108:   inner product where the SECOND argument gets the complex conjugate.

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

3134:   PetscCall(VecLockReadPush(x));
3135:   PetscCall(VecLockReadPush(y));
3136:   PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3137:   if (mat->ops->adot) PetscUseTypeMethod(mat, adot, x, y, val);
3138:   else PetscCall(MatADot_Default(mat, x, y, val));
3139:   PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3140:   PetscCall(VecLockReadPop(y));
3141:   PetscCall(VecLockReadPop(x));
3142:   PetscFunctionReturn(PETSC_SUCCESS);
3143: }

3145: /*@
3146:   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)
3147:   positive definite.

3149:   Collective

3151:   Input Parameters:
3152: + mat - matrix used to define norm
3153: - x   - the vector to compute the norm of

3155:   Output Parameter:
3156: . val - the norm with respect to `A`

3158:   Level: intermediate

3160:   Note:
3161:   For complex vectors, `MatANorm()` computes
3162: $$
3163:   val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3164: $$
3165:   where $x^H$ denotes the conjugate transpose of `x`.

3167: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3168: @*/
3169: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3170: {
3171:   PetscFunctionBegin;
3175:   VecCheckAssembled(x);
3177:   PetscAssertPointer(val, 3);
3178:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3179:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3180:   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);
3181:   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);
3182:   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);
3183:   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);
3184:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3185:   MatCheckPreallocated(mat, 1);

3187:   PetscCall(VecLockReadPush(x));
3188:   PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3189:   if (mat->ops->anorm) PetscUseTypeMethod(mat, anorm, x, val);
3190:   else PetscCall(MatANorm_Default(mat, x, val));
3191:   PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3192:   PetscCall(VecLockReadPop(x));
3193:   PetscFunctionReturn(PETSC_SUCCESS);
3194: }

3196: /*@
3197:   MatGetFactorType - gets the type of factorization a matrix is

3199:   Not Collective

3201:   Input Parameter:
3202: . mat - the matrix

3204:   Output Parameter:
3205: . 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`

3207:   Level: intermediate

3209: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3210:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3211: @*/
3212: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3213: {
3214:   PetscFunctionBegin;
3217:   PetscAssertPointer(t, 2);
3218:   *t = mat->factortype;
3219:   PetscFunctionReturn(PETSC_SUCCESS);
3220: }

3222: /*@
3223:   MatSetFactorType - sets the type of factorization a matrix is

3225:   Logically Collective

3227:   Input Parameters:
3228: + mat - the matrix
3229: - 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`

3231:   Level: intermediate

3233: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3234:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3235: @*/
3236: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3237: {
3238:   PetscFunctionBegin;
3241:   mat->factortype = t;
3242:   PetscFunctionReturn(PETSC_SUCCESS);
3243: }

3245: /*@
3246:   MatGetInfo - Returns information about matrix storage (number of
3247:   nonzeros, memory, etc.).

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

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

3255:   Output Parameter:
3256: . info - matrix information context

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

3261:   Level: intermediate

3263:   Notes:
3264:   The `MatInfo` context contains a variety of matrix data, including
3265:   number of nonzeros allocated and used, number of mallocs during
3266:   matrix assembly, etc. Additional information for factored matrices
3267:   is provided (such as the fill ratio, number of mallocs during
3268:   factorization, etc.).

3270:   Example:
3271:   See the file `${PETSC_DIR}/include/petscmat.h` for a complete list of
3272:   data within the `MatInfo` context.  For example,
3273: .vb
3274:       MatInfo info;
3275:       Mat     A;
3276:       double  mal, nz_a, nz_u;

3278:       MatGetInfo(A, MAT_LOCAL, &info);
3279:       mal  = info.mallocs;
3280:       nz_a = info.nz_allocated;
3281: .ve

3283: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3284: @*/
3285: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3286: {
3287:   PetscFunctionBegin;
3290:   PetscAssertPointer(info, 3);
3291:   MatCheckPreallocated(mat, 1);
3292:   PetscUseTypeMethod(mat, getinfo, flag, info);
3293:   PetscFunctionReturn(PETSC_SUCCESS);
3294: }

3296: /*
3297:    This is used by external packages where it is not easy to get the info from the actual
3298:    matrix factorization.
3299: */
3300: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3301: {
3302:   PetscFunctionBegin;
3303:   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3304:   PetscFunctionReturn(PETSC_SUCCESS);
3305: }

3307: /*@
3308:   MatLUFactor - Performs in-place LU factorization of matrix.

3310:   Collective

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

3323:   Level: developer

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

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

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

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

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

3346:   PetscFunctionBegin;
3350:   if (info) PetscAssertPointer(info, 4);
3352:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3353:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3354:   MatCheckPreallocated(mat, 1);
3355:   if (!info) {
3356:     PetscCall(MatFactorInfoInitialize(&tinfo));
3357:     info = &tinfo;
3358:   }

3360:   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3361:   PetscUseTypeMethod(mat, lufactor, row, col, info);
3362:   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3363:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3364:   PetscFunctionReturn(PETSC_SUCCESS);
3365: }

3367: /*@
3368:   MatILUFactor - Performs in-place ILU factorization of matrix.

3370:   Collective

3372:   Input Parameters:
3373: + mat  - the matrix
3374: . row  - row permutation
3375: . col  - column permutation
3376: - info - structure containing
3377: .vb
3378:       levels - number of levels of fill.
3379:       expected fill - as ratio of original fill.
3380:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3381:                 missing diagonal entries)
3382: .ve

3384:   Level: developer

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

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

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

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

3413:   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3414:   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3415:   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3416:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3417:   PetscFunctionReturn(PETSC_SUCCESS);
3418: }

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

3424:   Collective

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

3437:   Level: developer

3439:   Notes:
3440:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

3449: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3450: @*/
3451: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3452: {
3453:   MatFactorInfo tinfo;

3455:   PetscFunctionBegin;
3460:   if (info) PetscAssertPointer(info, 5);
3463:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3464:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3465:   MatCheckPreallocated(mat, 2);
3466:   if (!info) {
3467:     PetscCall(MatFactorInfoInitialize(&tinfo));
3468:     info = &tinfo;
3469:   }

3471:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3472:   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3473:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3474:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3475:   PetscFunctionReturn(PETSC_SUCCESS);
3476: }

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

3482:   Collective

3484:   Input Parameters:
3485: + fact - the factor matrix obtained with `MatGetFactor()`
3486: . mat  - the matrix
3487: - info - options for factorization

3489:   Level: developer

3491:   Notes:
3492:   See `MatLUFactor()` for in-place factorization. See
3493:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

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

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

3502: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3503: @*/
3504: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3505: {
3506:   MatFactorInfo tinfo;

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

3517:   MatCheckPreallocated(mat, 2);
3518:   if (!info) {
3519:     PetscCall(MatFactorInfoInitialize(&tinfo));
3520:     info = &tinfo;
3521:   }

3523:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3524:   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3525:   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3526:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3527:   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3528:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3529:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3530:   PetscFunctionReturn(PETSC_SUCCESS);
3531: }

3533: /*@
3534:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3535:   symmetric matrix.

3537:   Collective

3539:   Input Parameters:
3540: + mat  - the matrix
3541: . perm - row and column permutations
3542: - info - expected fill as ratio of original fill

3544:   Level: developer

3546:   Notes:
3547:   See `MatLUFactor()` for the nonsymmetric case. See also `MatGetFactor()`,
3548:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

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

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

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

3564:   PetscFunctionBegin;
3567:   if (info) PetscAssertPointer(info, 3);
3569:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3570:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3571:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3572:   MatCheckPreallocated(mat, 1);
3573:   if (!info) {
3574:     PetscCall(MatFactorInfoInitialize(&tinfo));
3575:     info = &tinfo;
3576:   }

3578:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3579:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3580:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3581:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3582:   PetscFunctionReturn(PETSC_SUCCESS);
3583: }

3585: /*@
3586:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3587:   of a symmetric matrix.

3589:   Collective

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

3602:   Level: developer

3604:   Notes:
3605:   See `MatLUFactorSymbolic()` for the nonsymmetric case. See also
3606:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

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

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

3615: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3616:           `MatGetOrdering()`
3617: @*/
3618: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3619: {
3620:   MatFactorInfo tinfo;

3622:   PetscFunctionBegin;
3626:   if (info) PetscAssertPointer(info, 4);
3629:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3630:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3631:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3632:   MatCheckPreallocated(mat, 2);
3633:   if (!info) {
3634:     PetscCall(MatFactorInfoInitialize(&tinfo));
3635:     info = &tinfo;
3636:   }

3638:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3639:   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3640:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3641:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3642:   PetscFunctionReturn(PETSC_SUCCESS);
3643: }

3645: /*@
3646:   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3647:   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3648:   `MatCholeskyFactorSymbolic()`.

3650:   Collective

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

3657:   Level: developer

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

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

3667: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3668: @*/
3669: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3670: {
3671:   MatFactorInfo tinfo;

3673:   PetscFunctionBegin;
3678:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3679:   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,
3680:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3681:   MatCheckPreallocated(mat, 2);
3682:   if (!info) {
3683:     PetscCall(MatFactorInfoInitialize(&tinfo));
3684:     info = &tinfo;
3685:   }

3687:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3688:   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3689:   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3690:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3691:   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3692:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3693:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3694:   PetscFunctionReturn(PETSC_SUCCESS);
3695: }

3697: /*@
3698:   MatQRFactor - Performs in-place QR factorization of matrix.

3700:   Collective

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

3712:   Level: developer

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

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

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

3725: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3726:           `MatSetUnfactored()`
3727: @*/
3728: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3729: {
3730:   PetscFunctionBegin;
3733:   if (info) PetscAssertPointer(info, 3);
3735:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3736:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3737:   MatCheckPreallocated(mat, 1);
3738:   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3739:   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3740:   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3741:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3742:   PetscFunctionReturn(PETSC_SUCCESS);
3743: }

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

3749:   Collective

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

3762:   Level: developer

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

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

3772: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3773: @*/
3774: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3775: {
3776:   MatFactorInfo tinfo;

3778:   PetscFunctionBegin;
3782:   if (info) PetscAssertPointer(info, 4);
3785:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3786:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3787:   MatCheckPreallocated(mat, 2);
3788:   if (!info) {
3789:     PetscCall(MatFactorInfoInitialize(&tinfo));
3790:     info = &tinfo;
3791:   }

3793:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3794:   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3795:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3796:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3797:   PetscFunctionReturn(PETSC_SUCCESS);
3798: }

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

3804:   Collective

3806:   Input Parameters:
3807: + fact - the factor matrix obtained with `MatGetFactor()`
3808: . mat  - the matrix
3809: - info - options for factorization

3811:   Level: developer

3813:   Notes:
3814:   See `MatQRFactor()` for in-place factorization.

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

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

3823: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3824: @*/
3825: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3826: {
3827:   MatFactorInfo tinfo;

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

3838:   MatCheckPreallocated(mat, 2);
3839:   if (!info) {
3840:     PetscCall(MatFactorInfoInitialize(&tinfo));
3841:     info = &tinfo;
3842:   }

3844:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3845:   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3846:   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3847:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3848:   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3849:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3850:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3851:   PetscFunctionReturn(PETSC_SUCCESS);
3852: }

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

3857:   Neighbor-wise Collective

3859:   Input Parameters:
3860: + mat - the factored matrix
3861: - b   - the right-hand-side vector

3863:   Output Parameter:
3864: . x - the result vector

3866:   Level: developer

3868:   Notes:
3869:   The vectors `b` and `x` cannot be the same. I.e., one cannot
3870:   call `MatSolve`(A,x,x).

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

3876: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3877: @*/
3878: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3879: {
3880:   PetscFunctionBegin;
3885:   PetscCheckSameComm(mat, 1, b, 2);
3886:   PetscCheckSameComm(mat, 1, x, 3);
3887:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3888:   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);
3889:   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);
3890:   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);
3891:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3892:   MatCheckPreallocated(mat, 1);

3894:   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3895:   PetscCall(VecFlag(x, mat->factorerrortype));
3896:   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3897:   else PetscUseTypeMethod(mat, solve, b, x);
3898:   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3899:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3900:   PetscFunctionReturn(PETSC_SUCCESS);
3901: }

3903: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3904: {
3905:   Vec      b, x;
3906:   PetscInt N;
3907:   PetscErrorCode (*f)(Mat, Vec, Vec);
3908:   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;

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

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

3941:   Neighbor-wise Collective

3943:   Input Parameters:
3944: + A - the factored matrix
3945: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3947:   Output Parameter:
3948: . X - the result matrix (dense matrix)

3950:   Level: developer

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

3956: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3957: @*/
3958: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3959: {
3960:   PetscFunctionBegin;
3965:   PetscCheckSameComm(A, 1, B, 2);
3966:   PetscCheckSameComm(A, 1, X, 3);
3967:   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);
3968:   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);
3969:   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");
3970:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3971:   MatCheckPreallocated(A, 1);

3973:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3974:   if (A->factorerrortype) {
3975:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3976:     PetscCall(MatFlag(X, 1));
3977:   } else if (!A->ops->matsolve) {
3978:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3979:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3980:   } else PetscUseTypeMethod(A, matsolve, B, X);
3981:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3982:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3983:   PetscFunctionReturn(PETSC_SUCCESS);
3984: }

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

3989:   Neighbor-wise Collective

3991:   Input Parameters:
3992: + A - the factored matrix
3993: - B - the right-hand-side matrix  (`MATDENSE` matrix)

3995:   Output Parameter:
3996: . X - the result matrix (dense matrix)

3998:   Level: developer

4000:   Note:
4001:   The matrices `B` and `X` cannot be the same. I.e., one cannot
4002:   call `MatMatSolveTranspose`(A,X,X).

4004: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
4005: @*/
4006: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
4007: {
4008:   PetscFunctionBegin;
4013:   PetscCheckSameComm(A, 1, B, 2);
4014:   PetscCheckSameComm(A, 1, X, 3);
4015:   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4016:   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);
4017:   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);
4018:   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);
4019:   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");
4020:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4021:   MatCheckPreallocated(A, 1);

4023:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
4024:   if (A->factorerrortype) {
4025:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4026:     PetscCall(MatFlag(X, 1));
4027:   } else if (!A->ops->matsolvetranspose) {
4028:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
4029:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
4030:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
4031:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
4032:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4033:   PetscFunctionReturn(PETSC_SUCCESS);
4034: }

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

4039:   Neighbor-wise Collective

4041:   Input Parameters:
4042: + A  - the factored matrix
4043: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

4045:   Output Parameter:
4046: . X - the result matrix (dense matrix)

4048:   Level: developer

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

4054: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
4055: @*/
4056: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
4057: {
4058:   PetscFunctionBegin;
4063:   PetscCheckSameComm(A, 1, Bt, 2);
4064:   PetscCheckSameComm(A, 1, X, 3);

4066:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4067:   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);
4068:   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);
4069:   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");
4070:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4071:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
4072:   MatCheckPreallocated(A, 1);

4074:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
4075:   if (A->factorerrortype) {
4076:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4077:     PetscCall(MatFlag(X, 1));
4078:   } else PetscUseTypeMethod(A, mattransposesolve, Bt, X);
4079:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
4080:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4081:   PetscFunctionReturn(PETSC_SUCCESS);
4082: }

4084: /*@
4085:   MatForwardSolve - Solves $L x = b$, given a factored matrix, $A = LU$, or
4086:   $U^T D^{1/2} x = b$, given a factored symmetric matrix, $A = U^T D U$,

4088:   Neighbor-wise Collective

4090:   Input Parameters:
4091: + mat - the factored matrix
4092: - b   - the right-hand-side vector

4094:   Output Parameter:
4095: . x - the result vector

4097:   Level: developer

4099:   Notes:
4100:   `MatSolve()` should be used for most applications, as it performs
4101:   a forward solve followed by a backward solve.

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

4106:   For matrix in `MATSEQBAIJ` format with block size larger than 1,
4107:   the diagonal blocks are not implemented as $D = D^{1/2} D^{1/2}$ yet.
4108:   `MatForwardSolve()` solves $U^T D y = b$, and
4109:   `MatBackwardSolve()` solves $U x = y$.
4110:   Thus they do not provide a symmetric preconditioner.

4112: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4113: @*/
4114: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4115: {
4116:   PetscFunctionBegin;
4121:   PetscCheckSameComm(mat, 1, b, 2);
4122:   PetscCheckSameComm(mat, 1, x, 3);
4123:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4124:   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);
4125:   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);
4126:   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);
4127:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4128:   MatCheckPreallocated(mat, 1);

4130:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4131:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4132:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4133:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4134:   PetscFunctionReturn(PETSC_SUCCESS);
4135: }

4137: /*@
4138:   MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
4139:   $D^{1/2} U x = b$, given a factored symmetric matrix, $A = U^T D U$,

4141:   Neighbor-wise Collective

4143:   Input Parameters:
4144: + mat - the factored matrix
4145: - b   - the right-hand-side vector

4147:   Output Parameter:
4148: . x - the result vector

4150:   Level: developer

4152:   Notes:
4153:   `MatSolve()` should be used for most applications, as it performs
4154:   a forward solve followed by a backward solve.

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

4159:   For matrix in `MATSEQBAIJ` format with block size larger than 1,
4160:   the diagonal blocks are not implemented as $D = D^{1/2} D^{1/2}$ yet.
4161:   `MatForwardSolve()` solves $U^T D y = b$, and
4162:   `MatBackwardSolve()` solves $U x = y$.
4163:   Thus they do not provide a symmetric preconditioner.

4165: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4166: @*/
4167: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4168: {
4169:   PetscFunctionBegin;
4174:   PetscCheckSameComm(mat, 1, b, 2);
4175:   PetscCheckSameComm(mat, 1, x, 3);
4176:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4177:   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);
4178:   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);
4179:   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);
4180:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4181:   MatCheckPreallocated(mat, 1);

4183:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4184:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4185:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4186:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4187:   PetscFunctionReturn(PETSC_SUCCESS);
4188: }

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

4193:   Neighbor-wise Collective

4195:   Input Parameters:
4196: + mat - the factored matrix
4197: . b   - the right-hand-side vector
4198: - y   - the vector to be added to

4200:   Output Parameter:
4201: . x - the result vector

4203:   Level: developer

4205:   Note:
4206:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4207:   call `MatSolveAdd`(A,x,y,x).

4209: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4210: @*/
4211: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4212: {
4213:   PetscScalar one = 1.0;
4214:   Vec         tmp;

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

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

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

4261:   Neighbor-wise Collective

4263:   Input Parameters:
4264: + mat - the factored matrix
4265: - b   - the right-hand-side vector

4267:   Output Parameter:
4268: . x - the result vector

4270:   Level: developer

4272:   Notes:
4273:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4274:   call `MatSolveTranspose`(A,x,x).

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

4280: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4281: @*/
4282: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4283: {
4284:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

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

4311: /*@
4312:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4313:   factored matrix.

4315:   Neighbor-wise Collective

4317:   Input Parameters:
4318: + mat - the factored matrix
4319: . b   - the right-hand-side vector
4320: - y   - the vector to be added to

4322:   Output Parameter:
4323: . x - the result vector

4325:   Level: developer

4327:   Note:
4328:   The vectors `b` and `x` cannot be the same. I.e., one cannot
4329:   call `MatSolveTransposeAdd`(A,x,y,x).

4331: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4332: @*/
4333: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4334: {
4335:   PetscScalar one = 1.0;
4336:   Vec         tmp;
4337:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

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

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

4380: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4381: /*@
4382:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4384:   Neighbor-wise Collective

4386:   Input Parameters:
4387: + mat   - the matrix
4388: . b     - the right-hand side
4389: . omega - the relaxation factor
4390: . flag  - flag indicating the type of SOR (see below)
4391: . shift - diagonal shift
4392: . its   - the number of iterations
4393: - lits  - the number of local iterations

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

4398:   SOR Flags:
4399: +     `SOR_FORWARD_SWEEP` - forward SOR
4400: .     `SOR_BACKWARD_SWEEP` - backward SOR
4401: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4402: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4403: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4404: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4405: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4406: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4407: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4409:   Level: developer

4411:   Notes:
4412:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4413:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4414:   on each process.

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

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

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

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

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

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

4451:   MatCheckPreallocated(mat, 1);
4452:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4453:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4454:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4455:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4456:   PetscFunctionReturn(PETSC_SUCCESS);
4457: }

4459: /*
4460:       Default matrix copy routine.
4461: */
4462: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4463: {
4464:   PetscInt           i, rstart = 0, rend = 0, nz;
4465:   const PetscInt    *cwork;
4466:   const PetscScalar *vwork;

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

4485: /*@
4486:   MatCopy - Copies a matrix to another matrix.

4488:   Collective

4490:   Input Parameters:
4491: + A   - the matrix
4492: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4494:   Output Parameter:
4495: . B - where the copy is put

4497:   Level: intermediate

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

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

4506: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4507: @*/
4508: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4509: {
4510:   PetscInt i;

4512:   PetscFunctionBegin;
4517:   PetscCheckSameComm(A, 1, B, 2);
4518:   MatCheckPreallocated(B, 2);
4519:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4520:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4521:   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,
4522:              A->cmap->N, B->cmap->N);
4523:   MatCheckPreallocated(A, 1);
4524:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4526:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4527:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4528:   else PetscCall(MatCopy_Basic(A, B, str));

4530:   B->stencil.dim = A->stencil.dim;
4531:   B->stencil.noc = A->stencil.noc;
4532:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4533:     B->stencil.dims[i]   = A->stencil.dims[i];
4534:     B->stencil.starts[i] = A->stencil.starts[i];
4535:   }

4537:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4538:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4539:   PetscFunctionReturn(PETSC_SUCCESS);
4540: }

4542: /*@
4543:   MatConvert - Converts a matrix to another matrix, either of the same
4544:   or different type.

4546:   Collective

4548:   Input Parameters:
4549: + mat     - the matrix
4550: . newtype - new matrix type. Use `MATSAME` to create a new matrix of the
4551:             same type as the original matrix.
4552: - reuse   - denotes if the destination matrix is to be created or reused.
4553:             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
4554:             `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).

4556:   Output Parameter:
4557: . M - pointer to place new matrix

4559:   Level: intermediate

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

4566:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4567:   the MPI communicator of the generated matrix is always the same as the communicator
4568:   of the input matrix.

4570: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4571: @*/
4572: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4573: {
4574:   PetscBool  sametype, issame, flg;
4575:   PetscBool3 issymmetric, ishermitian, isspd;
4576:   char       convname[256], mtype[256];
4577:   Mat        B;

4579:   PetscFunctionBegin;
4582:   PetscAssertPointer(M, 4);
4583:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4584:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4585:   MatCheckPreallocated(mat, 1);

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

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

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

4603:   /* Cache Mat options because some converters use MatHeaderReplace() */
4604:   issymmetric = mat->symmetric;
4605:   ishermitian = mat->hermitian;
4606:   isspd       = mat->spd;

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

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

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

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

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

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

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

4719:   /* Reset Mat options */
4720:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4721:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4722:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4723:   PetscFunctionReturn(PETSC_SUCCESS);
4724: }

4726: /*@
4727:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4729:   Not Collective

4731:   Input Parameter:
4732: . mat - the matrix, must be a factored matrix

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

4737:   Level: intermediate

4739: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4740: @*/
4741: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4742: {
4743:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4745:   PetscFunctionBegin;
4748:   PetscAssertPointer(type, 2);
4749:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4750:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4751:   if (conv) PetscCall((*conv)(mat, type));
4752:   else *type = MATSOLVERPETSC;
4753:   PetscFunctionReturn(PETSC_SUCCESS);
4754: }

4756: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4757: struct _MatSolverTypeForSpecifcType {
4758:   MatType mtype;
4759:   /* no entry for MAT_FACTOR_NONE */
4760:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4761:   MatSolverTypeForSpecifcType next;
4762: };

4764: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4765: struct _MatSolverTypeHolder {
4766:   char                       *name;
4767:   MatSolverTypeForSpecifcType handlers;
4768:   MatSolverTypeHolder         next;
4769: };

4771: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4776:   Logically Collective, No Fortran Support

4778:   Input Parameters:
4779: + package      - name of the package, for example `petsc` or `superlu`
4780: . mtype        - the matrix type that works with this package
4781: . ftype        - the type of factorization supported by the package
4782: - createfactor - routine that will create the factored matrix ready to be used

4784:   Level: developer

4786: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4787:   `MatGetFactor()`
4788: @*/
4789: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4790: {
4791:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4792:   PetscBool                   flg;
4793:   MatSolverTypeForSpecifcType inext, iprev = NULL;

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

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

4838:   Input Parameters:
4839: + 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
4840: . ftype - the type of factorization supported by the type
4841: - mtype - the matrix type that works with this type

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

4848:   Calling sequence of `createfactor`:
4849: + A     - the matrix providing the factor matrix
4850: . ftype - the `MatFactorType` of the factor requested
4851: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4853:   Level: developer

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

4860: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4861:           `MatInitializePackage()`
4862: @*/
4863: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4864: {
4865:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4866:   PetscBool                   flg;
4867:   MatSolverTypeForSpecifcType inext;

4869:   PetscFunctionBegin;
4870:   if (foundtype) *foundtype = PETSC_FALSE;
4871:   if (foundmtype) *foundmtype = PETSC_FALSE;
4872:   if (createfactor) *createfactor = NULL;

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

4927: PetscErrorCode MatSolverTypeDestroy(void)
4928: {
4929:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4930:   MatSolverTypeForSpecifcType inext, iprev;

4932:   PetscFunctionBegin;
4933:   while (next) {
4934:     PetscCall(PetscFree(next->name));
4935:     inext = next->handlers;
4936:     while (inext) {
4937:       PetscCall(PetscFree(inext->mtype));
4938:       iprev = inext;
4939:       inext = inext->next;
4940:       PetscCall(PetscFree(iprev));
4941:     }
4942:     prev = next;
4943:     next = next->next;
4944:     PetscCall(PetscFree(prev));
4945:   }
4946:   MatSolverTypeHolders = NULL;
4947:   PetscFunctionReturn(PETSC_SUCCESS);
4948: }

4950: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4951: {
4952:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4953:   MatSolverTypeForSpecifcType inext;
4954:   PetscBool                   flg, same;

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

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

4988:   Logically Collective

4990:   Input Parameter:
4991: . mat - the matrix

4993:   Output Parameter:
4994: . flg - `PETSC_TRUE` if uses the ordering

4996:   Level: developer

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

5002: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
5003: @*/
5004: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
5005: {
5006:   PetscFunctionBegin;
5007:   *flg = mat->canuseordering;
5008:   PetscFunctionReturn(PETSC_SUCCESS);
5009: }

5011: /*@
5012:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

5014:   Logically Collective

5016:   Input Parameters:
5017: + mat   - the matrix obtained with `MatGetFactor()`
5018: - ftype - the factorization type to be used

5020:   Output Parameter:
5021: . otype - the preferred ordering type

5023:   Level: developer

5025: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
5026: @*/
5027: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
5028: {
5029:   PetscFunctionBegin;
5030:   *otype = mat->preferredordering[ftype];
5031:   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
5032:   PetscFunctionReturn(PETSC_SUCCESS);
5033: }

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

5039:   Collective

5041:   Input Parameters:
5042: + mat   - the matrix
5043: . 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
5044:           the other criteria is returned
5045: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

5055:   Level: intermediate

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

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

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

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

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

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

5080: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
5081:           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
5082:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
5083:           `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5084:           `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
5085: @*/
5086: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
5087: {
5088:   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
5089:   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);

5091:   PetscFunctionBegin;

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

5098:   PetscCall(MatIsShell(mat, &shell));
5099:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
5100:   if (hasop) {
5101:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
5102:     PetscFunctionReturn(PETSC_SUCCESS);
5103:   }

5105:   if (!type) {
5106:     PetscBool foundbase;

5108:     /* First try exact MatType registrations in solver registration order. If all matching backends
5109:        decline this matrix instance by returning NULL, then try base-type registrations. */
5110:     PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
5111:     if (!*f) {
5112:       PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
5113:       foundtype = (PetscBool)(foundtype || foundbase);
5114:     }
5115:     PetscCheck(foundtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate a solver type for factorization type %s and matrix type %s.", MatFactorTypes[ftype], ((PetscObject)mat)->type_name);
5116:     if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5117:     PetscFunctionReturn(PETSC_SUCCESS);
5118:   }

5120:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
5121:   PetscCheck(foundtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate%s solver type%s%s for factorization type %s and matrix type %s.%s%s", !type ? " a" : "", type ? " " : "", type ? type : "", MatFactorTypes[ftype],
5122:              ((PetscObject)mat)->type_name, type ? " Perhaps you must ./configure with --download-" : "", type ? type : "");
5123:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
5124:   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);

5126:   PetscCall((*conv)(mat, ftype, f));
5127:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5128:   PetscFunctionReturn(PETSC_SUCCESS);
5129: }

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

5134:   Not Collective

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

5141:   Output Parameter:
5142: . flg - `PETSC_TRUE` if the factorization is available

5144:   Level: intermediate

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

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

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

5155: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5156:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5157: @*/
5158: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5159: {
5160:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5162:   PetscFunctionBegin;
5164:   PetscAssertPointer(flg, 4);

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

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

5172:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5173:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5174:   PetscFunctionReturn(PETSC_SUCCESS);
5175: }

5177: /*@
5178:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5180:   Collective

5182:   Input Parameters:
5183: + mat - the matrix
5184: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5185:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5187:   Output Parameter:
5188: . M - pointer to place new matrix

5190:   Level: intermediate

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

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

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

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

5203: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5204: @*/
5205: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5206: {
5207:   Mat               B;
5208:   VecType           vtype;
5209:   PetscInt          i;
5210:   PetscObject       dm, container_h, container_d;
5211:   PetscErrorCodeFn *viewf;

5213:   PetscFunctionBegin;
5216:   PetscAssertPointer(M, 3);
5217:   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5218:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5219:   MatCheckPreallocated(mat, 1);

5221:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5222:   PetscUseTypeMethod(mat, duplicate, op, M);
5223:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5224:   B = *M;

5226:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5227:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5228:   PetscCall(MatGetVecType(mat, &vtype));
5229:   PetscCall(MatSetVecType(B, vtype));

5231:   B->stencil.dim = mat->stencil.dim;
5232:   B->stencil.noc = mat->stencil.noc;
5233:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5234:     B->stencil.dims[i]   = mat->stencil.dims[i];
5235:     B->stencil.starts[i] = mat->stencil.starts[i];
5236:   }

5238:   B->nooffproczerorows = mat->nooffproczerorows;
5239:   B->nooffprocentries  = mat->nooffprocentries;
5240:   B->nonzerostate      = mat->nonzerostate;

5242:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5243:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5244:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5245:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5246:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5247:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5248:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5249:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5250:   PetscFunctionReturn(PETSC_SUCCESS);
5251: }

5253: /*@
5254:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5256:   Logically Collective

5258:   Input Parameter:
5259: . mat - the matrix

5261:   Output Parameter:
5262: . v - the diagonal of the matrix

5264:   Level: intermediate

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

5271:   Currently only correct in parallel for square matrices.

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

5286:     PetscCall(VecGetLocalSize(v, &nv));
5287:     PetscCall(MatGetLocalSize(mat, &row, &col));
5288:     ndiag = PetscMin(row, col);
5289:     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);
5290:   }

5292:   PetscUseTypeMethod(mat, getdiagonal, v);
5293:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5294:   PetscFunctionReturn(PETSC_SUCCESS);
5295: }

5297: /*@
5298:   MatGetRowMin - Gets the minimum value (of the real part) of each
5299:   row of the matrix

5301:   Logically Collective

5303:   Input Parameter:
5304: . mat - the matrix

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

5310:   Level: intermediate

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

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

5318: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5319:           `MatGetRowMax()`
5320: @*/
5321: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5322: {
5323:   PetscFunctionBegin;
5327:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5329:   if (!mat->cmap->N) {
5330:     PetscCall(VecSet(v, PETSC_MAX_REAL));
5331:     if (idx) {
5332:       PetscInt i, m = mat->rmap->n;
5333:       for (i = 0; i < m; i++) idx[i] = -1;
5334:     }
5335:   } else {
5336:     MatCheckPreallocated(mat, 1);
5337:   }
5338:   PetscUseTypeMethod(mat, getrowmin, v, idx);
5339:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5340:   PetscFunctionReturn(PETSC_SUCCESS);
5341: }

5343: /*@
5344:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5345:   row of the matrix

5347:   Logically Collective

5349:   Input Parameter:
5350: . mat - the matrix

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

5356:   Level: intermediate

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

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

5364: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5365: @*/
5366: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5367: {
5368:   PetscFunctionBegin;
5372:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5373:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

5375:   if (!mat->cmap->N) {
5376:     PetscCall(VecSet(v, 0.0));
5377:     if (idx) {
5378:       PetscInt i, m = mat->rmap->n;
5379:       for (i = 0; i < m; i++) idx[i] = -1;
5380:     }
5381:   } else {
5382:     MatCheckPreallocated(mat, 1);
5383:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5384:     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5385:   }
5386:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5387:   PetscFunctionReturn(PETSC_SUCCESS);
5388: }

5390: /*@
5391:   MatGetRowMax - Gets the maximum value (of the real part) of each
5392:   row of the matrix

5394:   Logically Collective

5396:   Input Parameter:
5397: . mat - the matrix

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

5403:   Level: intermediate

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

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

5411: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5412: @*/
5413: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5414: {
5415:   PetscFunctionBegin;
5419:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5421:   if (!mat->cmap->N) {
5422:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5423:     if (idx) {
5424:       PetscInt i, m = mat->rmap->n;
5425:       for (i = 0; i < m; i++) idx[i] = -1;
5426:     }
5427:   } else {
5428:     MatCheckPreallocated(mat, 1);
5429:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5430:   }
5431:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5432:   PetscFunctionReturn(PETSC_SUCCESS);
5433: }

5435: /*@
5436:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5437:   row of the matrix

5439:   Logically Collective

5441:   Input Parameter:
5442: . mat - the matrix

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

5448:   Level: intermediate

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

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

5456: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5457: @*/
5458: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5459: {
5460:   PetscFunctionBegin;
5464:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5466:   if (!mat->cmap->N) {
5467:     PetscCall(VecSet(v, 0.0));
5468:     if (idx) {
5469:       PetscInt i, m = mat->rmap->n;
5470:       for (i = 0; i < m; i++) idx[i] = -1;
5471:     }
5472:   } else {
5473:     MatCheckPreallocated(mat, 1);
5474:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5475:     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5476:   }
5477:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5478:   PetscFunctionReturn(PETSC_SUCCESS);
5479: }

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

5484:   Logically Collective

5486:   Input Parameter:
5487: . mat - the matrix

5489:   Output Parameter:
5490: . v - the vector for storing the sum

5492:   Level: intermediate

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

5496: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5497: @*/
5498: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5499: {
5500:   PetscFunctionBegin;
5504:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5506:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5507:   else {
5508:     MatCheckPreallocated(mat, 1);
5509:     PetscUseTypeMethod(mat, getrowsumabs, v);
5510:   }
5511:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5512:   PetscFunctionReturn(PETSC_SUCCESS);
5513: }

5515: /*@
5516:   MatGetRowSum - Gets the sum of each row of the matrix

5518:   Logically or Neighborhood Collective

5520:   Input Parameter:
5521: . mat - the matrix

5523:   Output Parameter:
5524: . v - the vector for storing the sum of rows

5526:   Level: intermediate

5528:   Note:
5529:   This code is slow since it is not currently specialized for different formats

5531: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5532: @*/
5533: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5534: {
5535:   Vec ones;

5537:   PetscFunctionBegin;
5541:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5542:   MatCheckPreallocated(mat, 1);
5543:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5544:   PetscCall(VecSet(ones, 1.));
5545:   PetscCall(MatMult(mat, ones, v));
5546:   PetscCall(VecDestroy(&ones));
5547:   PetscFunctionReturn(PETSC_SUCCESS);
5548: }

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

5554:   Collective

5556:   Input Parameter:
5557: . mat - the matrix to provide the transpose

5559:   Output Parameter:
5560: . 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

5562:   Level: advanced

5564:   Note:
5565:   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
5566:   routine allows bypassing that call.

5568: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5569: @*/
5570: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5571: {
5572:   MatState *rb = NULL;

5574:   PetscFunctionBegin;
5575:   PetscCall(PetscNew(&rb));
5576:   rb->id    = ((PetscObject)mat)->id;
5577:   rb->state = 0;
5578:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5579:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5580:   PetscFunctionReturn(PETSC_SUCCESS);
5581: }

5583: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5584: {
5585:   PetscContainer rB                         = NULL;
5586:   MatState      *rb                         = NULL;
5587:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

5589:   PetscFunctionBegin;
5592:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5593:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5594:   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5595:   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5596:   MatCheckPreallocated(mat, 1);
5597:   if (reuse == MAT_REUSE_MATRIX) {
5598:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5599:     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5600:     PetscCall(PetscContainerGetPointer(rB, &rb));
5601:     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5602:     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5603:   }

5605:   if (conjugate) {
5606:     f = mat->ops->hermitiantranspose;
5607:     if (f) PetscCall((*f)(mat, reuse, B));
5608:   }
5609:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5610:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5611:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5612:       PetscUseTypeMethod(mat, transpose, reuse, B);
5613:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5614:     }
5615:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5616:     if (conjugate) PetscCall(MatConjugate(*B));
5617:   }

5619:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5620:   if (reuse != MAT_INPLACE_MATRIX) {
5621:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5622:     PetscCall(PetscContainerGetPointer(rB, &rb));
5623:     rb->state        = ((PetscObject)mat)->state;
5624:     rb->nonzerostate = mat->nonzerostate;
5625:   }
5626:   PetscFunctionReturn(PETSC_SUCCESS);
5627: }

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

5632:   Collective

5634:   Input Parameters:
5635: + mat   - the matrix to transpose
5636: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5638:   Output Parameter:
5639: . B - the transpose of the matrix

5641:   Level: intermediate

5643:   Notes:
5644:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

5658: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5659:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5660: @*/
5661: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5662: {
5663:   PetscFunctionBegin;
5664:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5665:   PetscFunctionReturn(PETSC_SUCCESS);
5666: }

5668: /*@
5669:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5671:   Collective

5673:   Input Parameter:
5674: . A - the matrix to transpose

5676:   Output Parameter:
5677: . 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
5678:       numerical portion.

5680:   Level: intermediate

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

5685: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5686: @*/
5687: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5688: {
5689:   PetscFunctionBegin;
5692:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5693:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5694:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5695:   PetscUseTypeMethod(A, transposesymbolic, B);
5696:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5698:   PetscCall(MatTransposeSetPrecursor(A, *B));
5699:   PetscFunctionReturn(PETSC_SUCCESS);
5700: }

5702: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5703: {
5704:   PetscContainer rB;
5705:   MatState      *rb;

5707:   PetscFunctionBegin;
5710:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5711:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5712:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5713:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5714:   PetscCall(PetscContainerGetPointer(rB, &rb));
5715:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5716:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5717:   PetscFunctionReturn(PETSC_SUCCESS);
5718: }

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

5724:   Collective

5726:   Input Parameters:
5727: + A   - the matrix to test
5728: . B   - the matrix to test against, this can equal the first parameter
5729: - tol - tolerance, differences between entries smaller than this are counted as zero

5731:   Output Parameter:
5732: . flg - the result

5734:   Level: intermediate

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

5740: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5741: @*/
5742: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5743: {
5744:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5746:   PetscFunctionBegin;
5749:   PetscAssertPointer(flg, 4);
5750:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5751:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5752:   *flg = PETSC_FALSE;
5753:   if (f && g) {
5754:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5755:     PetscCall((*f)(A, B, tol, flg));
5756:   } else {
5757:     MatType mattype;

5759:     PetscCall(MatGetType(f ? B : A, &mattype));
5760:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5761:   }
5762:   PetscFunctionReturn(PETSC_SUCCESS);
5763: }

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

5768:   Collective

5770:   Input Parameters:
5771: + mat   - the matrix to transpose and complex conjugate
5772: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5774:   Output Parameter:
5775: . B - the Hermitian transpose

5777:   Level: intermediate

5779: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5780: @*/
5781: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5782: {
5783:   PetscFunctionBegin;
5784:   PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5785:   PetscFunctionReturn(PETSC_SUCCESS);
5786: }

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

5791:   Collective

5793:   Input Parameters:
5794: + A   - the matrix to test
5795: . B   - the matrix to test against, this can equal the first parameter
5796: - tol - tolerance, differences between entries smaller than this are counted as zero

5798:   Output Parameter:
5799: . flg - the result

5801:   Level: intermediate

5803:   Notes:
5804:   Only available for `MATAIJ` matrices.

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

5810: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5811: @*/
5812: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5813: {
5814:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5816:   PetscFunctionBegin;
5819:   PetscAssertPointer(flg, 4);
5820:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5821:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5822:   if (f && g) {
5823:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5824:     PetscCall((*f)(A, B, tol, flg));
5825:   } else {
5826:     MatType mattype;

5828:     PetscCall(MatGetType(f ? B : A, &mattype));
5829:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5830:   }
5831:   PetscFunctionReturn(PETSC_SUCCESS);
5832: }

5834: /*@
5835:   MatPermute - Creates a new matrix with rows and columns permuted from the
5836:   original.

5838:   Collective

5840:   Input Parameters:
5841: + mat - the matrix to permute
5842: . row - row permutation, each process supplies only the permutation for its rows
5843: - col - column permutation, each process supplies only the permutation for its columns

5845:   Output Parameter:
5846: . B - the permuted matrix

5848:   Level: advanced

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

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

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

5877:   if (mat->ops->permute) {
5878:     PetscUseTypeMethod(mat, permute, row, col, B);
5879:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5880:   } else {
5881:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5882:   }
5883:   PetscFunctionReturn(PETSC_SUCCESS);
5884: }

5886: /*@
5887:   MatEqual - Compares two matrices.

5889:   Collective

5891:   Input Parameters:
5892: + A - the first matrix
5893: - B - the second matrix

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

5898:   Level: intermediate

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

5904: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5905: @*/
5906: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5907: {
5908:   PetscFunctionBegin;
5913:   PetscAssertPointer(flg, 3);
5914:   PetscCheckSameComm(A, 1, B, 2);
5915:   MatCheckPreallocated(A, 1);
5916:   MatCheckPreallocated(B, 2);
5917:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5918:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5919:   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,
5920:              B->cmap->N);
5921:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5922:   else PetscCall(MatMultEqual(A, B, 10, flg));
5923:   PetscFunctionReturn(PETSC_SUCCESS);
5924: }

5926: /*@
5927:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5928:   matrices that are stored as vectors. Either of the two scaling
5929:   matrices can be `NULL`.

5931:   Collective

5933:   Input Parameters:
5934: + mat - the matrix to be scaled
5935: . l   - the left scaling vector (or `NULL`)
5936: - r   - the right scaling vector (or `NULL`)

5938:   Level: intermediate

5940:   Note:
5941:   `MatDiagonalScale()` computes $A = LAR$, where
5942:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5943:   The L scales the rows of the matrix, the R scales the columns of the matrix.
5944:   For `MATSEQSBAIJ`, if `l` and `r` are different `Vec` objects, `mat` changes to type `MATSEQBAIJ` because the result is not necessarily symmetric,
5945:   unless `l` and `r` have identical entries and `mat` is known to remain symmetric.

5947: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5948: @*/
5949: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5950: {
5951:   PetscBool  flg = PETSC_FALSE, update;
5952:   PetscBool3 symmetric, hermitian, spd;

5954:   PetscFunctionBegin;
5957:   if (l) {
5959:     PetscCheckSameComm(mat, 1, l, 2);
5960:   }
5961:   if (r) {
5963:     PetscCheckSameComm(mat, 1, r, 3);
5964:   }
5965:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5966:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5967:   MatCheckPreallocated(mat, 1);
5968:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5970:   symmetric = mat->symmetric;
5971:   hermitian = mat->hermitian;
5972:   spd       = mat->spd;
5973:   update    = (PetscBool)(l != r && (PetscBool3ToBool(symmetric) == PETSC_TRUE || PetscBool3ToBool(hermitian) == PETSC_TRUE));
5974:   if (update == PETSC_TRUE) {
5975:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(symmetric) == PETSC_TRUE) {
5976:       if (l != NULL && r != NULL) PetscCall(VecEqual(l, r, &flg));
5977:       if (flg == PETSC_FALSE) {
5978:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5979:         PetscCheck(flg == PETSC_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For MATMPISBAIJ, left and right scaling vectors must be the same");
5980:         symmetric = spd = PETSC_BOOL3_FALSE;
5981:         if (!PetscDefined(USE_COMPLEX)) hermitian = PETSC_BOOL3_FALSE;
5982:         else hermitian = PETSC_BOOL3_UNKNOWN;
5983:       }
5984:     }
5985:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(hermitian) == PETSC_TRUE) {
5986:       flg = PETSC_FALSE;
5987:       if (l != NULL && r != NULL) {
5988:         Vec conjugate;

5990:         PetscCall(VecDuplicate(l, &conjugate));
5991:         PetscCall(VecCopy(l, conjugate));
5992:         PetscCall(VecConjugate(conjugate));
5993:         PetscCall(VecEqual(conjugate, r, &flg));
5994:         PetscCall(VecDestroy(&conjugate));
5995:       }
5996:       if (flg == PETSC_FALSE) {
5997:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5998:         PetscCheck(flg == PETSC_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For Hermitian MATMPISBAIJ, left and right scaling vectors must be conjugate one of the other");
5999:         hermitian = PETSC_BOOL3_FALSE;
6000:         symmetric = spd = PETSC_BOOL3_UNKNOWN;
6001:       }
6002:     }
6003:   }
6004:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6005:   PetscUseTypeMethod(mat, diagonalscale, PetscBool3ToBool(symmetric) == PETSC_TRUE && flg == PETSC_TRUE ? r : l, r);
6006:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6007:   if (update == PETSC_TRUE) {
6008:     mat->symmetric = symmetric;
6009:     mat->hermitian = hermitian;
6010:     mat->spd       = spd;
6011:   }
6012:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6013:   PetscFunctionReturn(PETSC_SUCCESS);
6014: }

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

6019:   Logically Collective

6021:   Input Parameters:
6022: + mat - the matrix to be scaled
6023: - a   - the scaling value

6025:   Level: intermediate

6027: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
6028: @*/
6029: PetscErrorCode MatScale(Mat mat, PetscScalar a)
6030: {
6031:   PetscFunctionBegin;
6034:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6035:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6037:   MatCheckPreallocated(mat, 1);

6039:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6040:   if (a != (PetscScalar)1.0) {
6041:     PetscUseTypeMethod(mat, scale, a);
6042:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6043:   }
6044:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6045:   PetscFunctionReturn(PETSC_SUCCESS);
6046: }

6048: /*@
6049:   MatNorm - Calculates various norms of a matrix.

6051:   Collective

6053:   Input Parameters:
6054: + mat  - the matrix
6055: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

6057:   Output Parameter:
6058: . nrm - the resulting norm

6060:   Level: intermediate

6062: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
6063: @*/
6064: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
6065: {
6066:   PetscFunctionBegin;
6070:   PetscAssertPointer(nrm, 3);

6072:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6073:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6074:   MatCheckPreallocated(mat, 1);

6076:   PetscUseTypeMethod(mat, norm, type, nrm);
6077:   PetscFunctionReturn(PETSC_SUCCESS);
6078: }

6080: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6081: {
6082:   PetscScalar *ax, nm1;
6083:   PetscInt     st, en, n;

6085:   PetscFunctionBegin;
6086:   PetscCall(VecGetSize(x, &n));
6087:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6088:   nm1 = n - 1;
6089:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6090:   PetscCall(VecGetArrayWrite(x, &ax));
6091:   for (PetscInt i = st; i < en; i++) {
6092:     const PetscInt    ii = i - st;
6093:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6095:     ax[ii] = s * (1.0 + i / nm1);
6096:   }
6097:   PetscCall(VecRestoreArrayWrite(x, &ax));
6098:   PetscFunctionReturn(PETSC_SUCCESS);
6099: }

6101: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6102: {
6103:   Vec         x, y;
6104:   PetscReal   normx, normy;
6105:   PetscInt    i, N;
6106:   PetscRandom rnd;

6108:   PetscFunctionBegin;
6109:   if (maxit < 0) maxit = 1;
6110:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6111:   PetscCall(PetscRandomSetFromOptions(rnd));
6112:   PetscCall(MatCreateVecs(A, &x, &y));
6113:   PetscCall(VecBindToCPU(x, boundtocpu));
6114:   PetscCall(VecBindToCPU(y, boundtocpu));
6115:   PetscCall(VecGetSize(x, &N));
6116:   *n = 0.0;
6117:   for (i = 0; i < maxit; i++) {
6118:     PetscCall(VecSetRandom(x, rnd));
6119:     switch (normtype) {
6120:     case NORM_1:
6121:       PetscCall(VecNorm(x, NORM_1, &normx));
6122:       if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6123:       break;
6124:     case NORM_INFINITY:
6125:       PetscCall(VecShift(x, -0.5));
6126:       PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6127:       break;
6128:     case NORM_2:
6129:       PetscCall(VecNormalize(x, NULL));
6130:       break;
6131:     default:
6132:       PetscUnreachable();
6133:     }
6134:     PetscCall(MatMult(A, x, y));
6135:     PetscCall(VecNorm(y, normtype, &normy));
6136:     *n = PetscMax(*n, normy);
6137:     PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6138:   }
6139:   PetscCall(VecDestroy(&x));
6140:   PetscCall(VecDestroy(&y));
6141:   PetscCall(PetscRandomDestroy(&rnd));
6142:   PetscFunctionReturn(PETSC_SUCCESS);
6143: }

6145: /*@
6146:   MatNormApproximate - Approximate the norm of a matrix.

6148:   Collective

6150:   Input Parameters:
6151: + A        - the matrix
6152: . normtype - the `NormType`
6153: - maxit    - maximum number of iterations to use

6155:   Output Parameter:
6156: . n - the norm estimate

6158:   Level: intermediate

6160:   Notes:
6161:   Does not need access to the matrix entries; it just performs matrix-vector and transposed matrix-vector products {cite}`Higham1992`, {cite}`doi:10.1137/S0895479899356080`.

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

6165: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6166: @*/
6167: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6168: {
6169:   Vec         x, y, w, z;
6170:   PetscReal   normz, adot;
6171:   PetscScalar dot;
6172:   PetscInt    i, j, N, jold = -1;
6173:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

6175:   PetscFunctionBegin;
6180:   PetscAssertPointer(n, 4);
6181: #if PetscDefined(HAVE_DEVICE)
6182:   boundtocpu = A->boundtocpu;
6183: #endif
6184:   PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6185:   switch (normtype) {
6186:   case NORM_INFINITY:
6187:   case NORM_1:
6188:     if (!hasop) {
6189:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6190:       i = maxit;
6191:       break;
6192:     } else {
6193:       PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6194:       if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6195:       else {
6196:         Mat B;

6198:         PetscCall(MatCreateHermitianTranspose(A, &B));
6199:         A = B;
6200:       }
6201:     }
6202:     if (maxit < 0) maxit = 10; /* pure guess */
6203:     PetscCall(MatCreateVecs(A, &x, &y));
6204:     PetscCall(MatCreateVecs(A, &z, &w));
6205:     PetscCall(VecBindToCPU(x, boundtocpu));
6206:     PetscCall(VecBindToCPU(y, boundtocpu));
6207:     PetscCall(VecBindToCPU(z, boundtocpu));
6208:     PetscCall(VecBindToCPU(w, boundtocpu));
6209:     PetscCall(VecGetSize(x, &N));
6210:     PetscCall(VecSet(x, 1. / N));
6211:     *n = 0.0;
6212:     for (i = 0; i < maxit; i++) {
6213:       PetscCall(MatMult(A, x, y));
6214:       PetscCall(VecNorm(y, NORM_1, n));
6215:       if (PetscDefined(USE_COMPLEX)) {
6216:         PetscCall(VecCopy(y, w));
6217:         PetscCall(VecAbs(w));
6218:         PetscCall(VecPointwiseDivide(w, y, w));
6219:       } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6220:       PetscCall(MatMultHermitianTranspose(A, w, z));
6221:       PetscCall(VecRealPart(z));
6222:       PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6223:       PetscCall(VecDot(x, z, &dot));
6224:       adot = PetscAbsScalar(dot);
6225:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6226:       if (normz <= adot && i > 0) {
6227:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6228:         break;
6229:       }
6230:       PetscCall(VecAbs(z));
6231:       PetscCall(VecMax(z, &j, &normz));
6232:       if (j == jold) {
6233:         PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6234:         break;
6235:       }
6236:       jold = j;
6237:       if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6238:     }
6239:     /* last check */
6240:     if (N > 1) {
6241:       PetscReal ny;

6243:       PetscCall(VecSetFinalNormApp_Private(x));
6244:       PetscCall(MatMult(A, x, y));
6245:       PetscCall(VecNorm(y, NORM_1, &ny));
6246:       ny = 2 * ny / (3 * N);
6247:       PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6248:       *n = PetscMax(*n, ny);
6249:     }
6250:     PetscCall(MatDestroy(&A));
6251:     PetscCall(VecDestroy(&x));
6252:     PetscCall(VecDestroy(&w));
6253:     PetscCall(VecDestroy(&y));
6254:     PetscCall(VecDestroy(&z));
6255:     break;
6256:   case NORM_2:
6257:     if (!hasop) {
6258:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6259:       i = maxit;
6260:       break;
6261:     }
6262:     if (maxit < 0) maxit = 20; /* pure guess */
6263:     PetscCall(MatCreateVecs(A, &x, &y));
6264:     PetscCall(MatCreateVecs(A, &z, NULL));
6265:     PetscCall(VecBindToCPU(x, boundtocpu));
6266:     PetscCall(VecBindToCPU(y, boundtocpu));
6267:     PetscCall(VecBindToCPU(z, boundtocpu));
6268:     PetscCall(VecSetRandom(x, NULL));
6269:     PetscCall(VecNormalize(x, NULL));
6270:     *n = 0.0;
6271:     for (i = 0; i < maxit; i++) {
6272:       PetscCall(MatMult(A, x, y));
6273:       PetscCall(VecNormalize(y, n));
6274:       PetscCall(MatMultHermitianTranspose(A, y, z));
6275:       PetscCall(VecNorm(z, NORM_2, &normz));
6276:       PetscCall(VecDot(x, z, &dot));
6277:       adot = PetscAbsScalar(dot);
6278:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6279:       if (normz <= adot) {
6280:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6281:         break;
6282:       }
6283:       if (i < maxit - 1) {
6284:         Vec t;

6286:         PetscCall(VecNormalize(z, NULL));
6287:         t = x;
6288:         x = z;
6289:         z = t;
6290:       }
6291:     }
6292:     PetscCall(VecDestroy(&x));
6293:     PetscCall(VecDestroy(&y));
6294:     PetscCall(VecDestroy(&z));
6295:     break;
6296:   default:
6297:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6298:   }
6299:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6300:   PetscFunctionReturn(PETSC_SUCCESS);
6301: }

6303: /*
6304:      This variable is used to prevent counting of MatAssemblyBegin() that
6305:    are called from within a MatAssemblyEnd().
6306: */
6307: static PetscInt MatAssemblyEnd_InUse = 0;
6308: /*@
6309:   MatAssemblyBegin - Begins assembling the matrix. This routine should
6310:   be called after completing all calls to `MatSetValues()`.

6312:   Collective

6314:   Input Parameters:
6315: + mat  - the matrix
6316: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6318:   Level: beginner

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

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

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

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

6336: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6337: @*/
6338: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6339: {
6340:   PetscFunctionBegin;
6343:   MatCheckPreallocated(mat, 1);
6344:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6345:   if (mat->assembled) {
6346:     mat->was_assembled = PETSC_TRUE;
6347:     mat->assembled     = PETSC_FALSE;
6348:   }

6350:   if (!MatAssemblyEnd_InUse) {
6351:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6352:     PetscTryTypeMethod(mat, assemblybegin, type);
6353:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6354:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6355:   PetscFunctionReturn(PETSC_SUCCESS);
6356: }

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

6362:   Not Collective

6364:   Input Parameter:
6365: . mat - the matrix

6367:   Output Parameter:
6368: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6370:   Level: advanced

6372: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6373: @*/
6374: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6375: {
6376:   PetscFunctionBegin;
6378:   PetscAssertPointer(assembled, 2);
6379:   *assembled = mat->assembled;
6380:   PetscFunctionReturn(PETSC_SUCCESS);
6381: }

6383: /*@
6384:   MatAssemblyEnd - Completes assembling the matrix. This routine should
6385:   be called after `MatAssemblyBegin()`.

6387:   Collective

6389:   Input Parameters:
6390: + mat  - the matrix
6391: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

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

6396:   Level: beginner

6398: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6399:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`, `PetscOptionsCreateViewer()`
6400: @*/
6401: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6402: {
6403:   static PetscInt inassm = 0;
6404:   PetscBool       flg    = PETSC_FALSE;

6406:   PetscFunctionBegin;

6410:   inassm++;
6411:   MatAssemblyEnd_InUse++;
6412:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6413:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6414:     PetscTryTypeMethod(mat, assemblyend, type);
6415:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6416:   } else PetscTryTypeMethod(mat, assemblyend, type);

6418:   /* Flush assembly is not a true assembly */
6419:   if (type != MAT_FLUSH_ASSEMBLY) {
6420:     if (mat->num_ass) {
6421:       if (!mat->symmetry_eternal) {
6422:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6423:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6424:       }
6425:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6426:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6427:     }
6428:     mat->num_ass++;
6429:     mat->assembled        = PETSC_TRUE;
6430:     mat->ass_nonzerostate = mat->nonzerostate;
6431:   }

6433:   mat->insertmode = NOT_SET_VALUES;
6434:   MatAssemblyEnd_InUse--;
6435:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6436:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6437:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6439:     if (mat->checksymmetryonassembly) {
6440:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6441:       if (flg) {
6442:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6443:       } else {
6444:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6445:       }
6446:     }
6447:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6448:   }
6449:   inassm--;
6450:   PetscFunctionReturn(PETSC_SUCCESS);
6451: }

6453: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6454: /*@
6455:   MatSetOption - Sets a parameter option for a matrix. Some options
6456:   may be specific to certain storage formats. Some options
6457:   determine how values will be inserted (or added). Sorted,
6458:   row-oriented input will generally assemble the fastest. The default
6459:   is row-oriented.

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

6463:   Input Parameters:
6464: + mat - the matrix
6465: . op  - the option, one of those listed below (and possibly others),
6466: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6468:   Options Describing Matrix Structure:
6469: + `MAT_SPD`                         - symmetric positive definite
6470: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6471: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6472: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6473: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6474: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6475: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

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

6480:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6481:    Insert a logically dense subblock, which can be
6482: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6484:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6485:    nothing to do with how the data is stored internally in the matrix
6486:    data structure.

6488:    When (re)assembling a matrix, we can restrict the input for
6489:    efficiency/debugging purposes. These options include
6490: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6491: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6492: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-process entries
6493: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6494: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6495: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6496:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6497:                                       performance for very large process counts.
6498: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6499:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6500:                                       functions, instead sending only neighbor messages.

6502:   Level: intermediate

6504:   Notes:
6505:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6507:   Some options are relevant only for particular matrix types and
6508:   are thus ignored by others. Other options are not supported by
6509:   certain matrix types and will generate an error message if set.

6511:   Once `MAT_STRUCTURE_ONLY` has been set to `PETSC_TRUE`, it cannot be set back to `PETSC_FALSE`.

6513:   The matrix properties must be consistent with one another. With real scalars, `MAT_SPD` implies `MAT_SYMMETRIC`, and
6514:   both `MAT_SYMMETRIC` and `MAT_HERMITIAN` imply `MAT_STRUCTURALLY_SYMMETRIC`. Setting a property that contradicts
6515:   another known property generates an error. Still with real scalars, setting either `MAT_SYMMETRIC` or `MAT_HERMITIAN`
6516:   also sets the other to the same value.

6518:   If using Fortran to compute a matrix, one may need to use the column-oriented
6519:   option (or convert to the row-oriented format).

6521:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6522:   that would generate a new entry in the nonzero structure is instead
6523:   ignored. Thus, if memory has not already been allocated for this particular
6524:   data, then the insertion is ignored. For dense matrices, in which
6525:   the entire array is allocated, no entries are ever ignored.
6526:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6528:   `MAT_NEW_NONZERO_LOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6529:   that would generate a new entry in the nonzero structure instead produces
6530:   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

6532:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6533:   that would generate a new entry that has not been preallocated will
6534:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6535:   only.) This is a useful flag when debugging matrix memory preallocation.
6536:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6538:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6539:   other processes should be dropped, rather than stashed.
6540:   This is useful if you know that the "owning" process is also
6541:   always generating the correct matrix entries, so that PETSc need
6542:   not transfer duplicate entries generated on another process.

6544:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6545:   searches during matrix assembly. When this flag is set, the hash table
6546:   is created during the first matrix assembly. This hash table is
6547:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6548:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6549:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6550:   supported by `MATMPIBAIJ` format only.

6552:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6553:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6555:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ`, `MATSELL`, and `MATIS` matrices this will stop zero values
6556:   from creating a zero location in the matrix. A zero on the diagonal is exempt and still creates its
6557:   location, so that operations needing a full diagonal, such as `MatSOR()`, keep working. The exemption
6558:   covers the diagonal portion of the owning process's rows; a zero added with `ADD_VALUES` to a row owned
6559:   by another process is dropped as it is stashed and never reaches that test. A matrix assembled without
6560:   preallocation, through `MatSetUp()`, decides the exemption from process-local indices, so it does not
6561:   hold there when the row and column layouts differ

6563:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6565:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6566:   zero row routines and thus improves performance for very large process counts.

6568:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6569:   part of the matrix (since they should match the upper triangular part).

6571:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6572:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6573:   with finite difference schemes with non-periodic boundary conditions.

6575:   Developer Note:
6576:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6577:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6578:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6579:   not changed.

6581: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6582: @*/
6583: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6584: {
6585:   PetscFunctionBegin;
6587:   if (op > 0) {
6590:   }

6592:   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);

6594:   switch (op) {
6595:   case MAT_FORCE_DIAGONAL_ENTRIES:
6596:     mat->force_diagonals = flg;
6597:     PetscFunctionReturn(PETSC_SUCCESS);
6598:   case MAT_NO_OFF_PROC_ENTRIES:
6599:     mat->nooffprocentries = flg;
6600:     PetscFunctionReturn(PETSC_SUCCESS);
6601:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6602:     mat->assembly_subset = flg;
6603:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6604: #if !PetscDefined(HAVE_MPIUNI)
6605:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6606: #endif
6607:       mat->stash.first_assembly_done = PETSC_FALSE;
6608:     }
6609:     PetscFunctionReturn(PETSC_SUCCESS);
6610:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6611:     mat->nooffproczerorows = flg;
6612:     PetscFunctionReturn(PETSC_SUCCESS);
6613:   case MAT_SPD:
6614:     PetscCheck(PetscDefined(USE_COMPLEX) || !flg || mat->symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SPD to PETSC_TRUE when MAT_SYMMETRIC is PETSC_FALSE");
6615:     PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SPD to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6616:     if (flg) {
6617:       mat->spd                    = PETSC_BOOL3_TRUE;
6618:       mat->symmetric              = PETSC_BOOL3_TRUE;
6619:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6620:       if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_TRUE;
6621:     } else mat->spd = PETSC_BOOL3_FALSE;
6622:     break;
6623:   case MAT_SYMMETRIC:
6624:     PetscCheck(PetscDefined(USE_COMPLEX) || flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SYMMETRIC to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6625:     PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SYMMETRIC to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6626:     mat->symmetric = PetscBoolToBool3(flg);
6627:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6628:     if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PetscBoolToBool3(flg);
6629:     break;
6630:   case MAT_HERMITIAN:
6631:     PetscCheck(PetscDefined(USE_COMPLEX) || flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_HERMITIAN to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6632:     PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_HERMITIAN to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6633:     mat->hermitian = PetscBoolToBool3(flg);
6634:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6635:     if (!PetscDefined(USE_COMPLEX)) mat->symmetric = PetscBoolToBool3(flg);
6636:     break;
6637:   case MAT_STRUCTURALLY_SYMMETRIC:
6638:     PetscCheck(flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6639:     PetscCheck(flg || mat->symmetric != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_SYMMETRIC is PETSC_TRUE");
6640:     PetscCheck(flg || mat->hermitian != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_HERMITIAN is PETSC_TRUE");
6641:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6642:     break;
6643:   case MAT_SYMMETRY_ETERNAL:
6644:     PetscCheck(mat->symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SYMMETRY_ETERNAL without first setting MAT_SYMMETRIC to PETSC_TRUE or PETSC_FALSE");
6645:     mat->symmetry_eternal = flg;
6646:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6647:     break;
6648:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6649:     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 PETSC_TRUE or PETSC_FALSE");
6650:     mat->structural_symmetry_eternal = flg;
6651:     break;
6652:   case MAT_SPD_ETERNAL:
6653:     PetscCheck(mat->spd != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SPD_ETERNAL without first setting MAT_SPD to PETSC_TRUE or PETSC_FALSE");
6654:     mat->spd_eternal = flg;
6655:     if (flg) {
6656:       mat->structural_symmetry_eternal = PETSC_TRUE;
6657:       mat->symmetry_eternal            = PETSC_TRUE;
6658:     }
6659:     break;
6660:   case MAT_STRUCTURE_ONLY:
6661:     PetscCheck(flg || !mat->structure_only, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_STRUCTURE_ONLY to PETSC_FALSE after it has been set to PETSC_TRUE");
6662:     mat->structure_only = flg;
6663:     break;
6664:   case MAT_SORTED_FULL:
6665:     mat->sortedfull = flg;
6666:     break;
6667:   default:
6668:     break;
6669:   }
6670:   PetscCheck((op != MAT_ROW_ORIENTED) || ((PetscObject)mat)->type_name, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "The matrix type must be set (MatSetType()) before setting this option");
6671:   PetscTryTypeMethod(mat, setoption, op, flg);
6672:   PetscFunctionReturn(PETSC_SUCCESS);
6673: }

6675: /*@
6676:   MatGetOption - Gets a parameter option that has been set for a matrix.

6678:   Logically Collective

6680:   Input Parameters:
6681: + mat - the matrix
6682: - op  - the option, this only responds to certain options, check the code for which ones

6684:   Output Parameter:
6685: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6687:   Level: intermediate

6689:   Notes:
6690:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6692:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6693:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6695: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6696:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6697: @*/
6698: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6699: {
6700:   PetscFunctionBegin;

6704:   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);
6705:   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()");

6707:   switch (op) {
6708:   case MAT_NO_OFF_PROC_ENTRIES:
6709:     *flg = mat->nooffprocentries;
6710:     break;
6711:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6712:     *flg = mat->nooffproczerorows;
6713:     break;
6714:   case MAT_SYMMETRIC:
6715:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6716:     break;
6717:   case MAT_HERMITIAN:
6718:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6719:     break;
6720:   case MAT_STRUCTURALLY_SYMMETRIC:
6721:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6722:     break;
6723:   case MAT_SPD:
6724:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6725:     break;
6726:   case MAT_SYMMETRY_ETERNAL:
6727:     *flg = mat->symmetry_eternal;
6728:     break;
6729:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6730:     *flg = mat->symmetry_eternal;
6731:     break;
6732:   default:
6733:     break;
6734:   }
6735:   PetscFunctionReturn(PETSC_SUCCESS);
6736: }

6738: /*@
6739:   MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6740:   this routine retains the old nonzero structure.

6742:   Logically Collective

6744:   Input Parameter:
6745: . mat - the matrix

6747:   Level: intermediate

6749:   Note:
6750:   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.
6751:   See the Performance chapter of the users manual for information on preallocating matrices.
6752:   For matrices with the `MAT_STRUCTURE_ONLY` option set to true, this routine leaves the structure and object state unchanged because no numerical values are stored.

6754: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6755: @*/
6756: PetscErrorCode MatZeroEntries(Mat mat)
6757: {
6758:   PetscFunctionBegin;
6761:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6762:   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");
6763:   MatCheckPreallocated(mat, 1);

6765:   if (mat->structure_only == PETSC_FALSE) {
6766:     PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6767:     PetscUseTypeMethod(mat, zeroentries);
6768:     PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6769:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6770:   }
6771:   PetscFunctionReturn(PETSC_SUCCESS);
6772: }

6774: /*@
6775:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6776:   of a set of rows and columns of a matrix.

6778:   Collective

6780:   Input Parameters:
6781: + mat     - the matrix
6782: . numRows - the number of rows/columns to zero
6783: . rows    - the global row indices
6784: . diag    - value put in the diagonal of the eliminated rows
6785: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6786: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6788:   Level: intermediate

6790:   Notes:
6791:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6793:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6794:   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

6796:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6797:   Krylov method to take advantage of the known solution on the zeroed rows.

6799:   For the parallel case, all processes that share the matrix (i.e.,
6800:   those in the communicator used for matrix creation) MUST call this
6801:   routine, regardless of whether any rows being zeroed are owned by
6802:   them.

6804:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6805:   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
6806:   missing.

6808:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6809:   list only rows local to itself).

6811:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6813: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6814:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6815: @*/
6816: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6817: {
6818:   PetscFunctionBegin;
6821:   if (numRows) PetscAssertPointer(rows, 3);
6822:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6823:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6824:   MatCheckPreallocated(mat, 1);

6826:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6827:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6828:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6829:   PetscFunctionReturn(PETSC_SUCCESS);
6830: }

6832: /*@
6833:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6834:   of a set of rows and columns of a matrix.

6836:   Collective

6838:   Input Parameters:
6839: + mat  - the matrix
6840: . is   - the rows to zero
6841: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6842: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6843: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6845:   Level: intermediate

6847:   Note:
6848:   See `MatZeroRowsColumns()` for details on how this routine operates.

6850: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6851:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6852: @*/
6853: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6854: {
6855:   PetscInt        numRows;
6856:   const PetscInt *rows;

6858:   PetscFunctionBegin;
6863:   PetscCall(ISGetLocalSize(is, &numRows));
6864:   PetscCall(ISGetIndices(is, &rows));
6865:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6866:   PetscCall(ISRestoreIndices(is, &rows));
6867:   PetscFunctionReturn(PETSC_SUCCESS);
6868: }

6870: /*@
6871:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6872:   of a set of rows of a matrix.

6874:   Collective

6876:   Input Parameters:
6877: + mat     - the matrix
6878: . numRows - the number of rows to zero
6879: . rows    - the global row indices
6880: . diag    - value put in the diagonal of the zeroed rows
6881: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6882: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6884:   Level: intermediate

6886:   Notes:
6887:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6889:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6891:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6892:   Krylov method to take advantage of the known solution on the zeroed rows.

6894:   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)
6895:   from the matrix.

6897:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6898:   but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6899:   formats this does not alter the nonzero structure.

6901:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6902:   of the matrix is not changed the values are
6903:   merely zeroed.

6905:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6906:   formats can optionally remove the main diagonal entry from the
6907:   nonzero structure as well, by passing 0.0 as the final argument).

6909:   For the parallel case, all processes that share the matrix (i.e.,
6910:   those in the communicator used for matrix creation) MUST call this
6911:   routine, regardless of whether any rows being zeroed are owned by
6912:   them.

6914:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6915:   list only rows local to itself).

6917:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6918:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6920: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6921:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6922: @*/
6923: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6924: {
6925:   PetscFunctionBegin;
6928:   if (numRows) PetscAssertPointer(rows, 3);
6929:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6930:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6931:   MatCheckPreallocated(mat, 1);

6933:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6934:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6935:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6936:   PetscFunctionReturn(PETSC_SUCCESS);
6937: }

6939: /*@
6940:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6941:   of a set of rows of a matrix indicated by an `IS`

6943:   Collective

6945:   Input Parameters:
6946: + mat  - the matrix
6947: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6948: . diag - value put in all diagonals of eliminated rows
6949: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6950: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6952:   Level: intermediate

6954:   Note:
6955:   See `MatZeroRows()` for details on how this routine operates.

6957: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6958:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6959: @*/
6960: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6961: {
6962:   PetscInt        numRows = 0;
6963:   const PetscInt *rows    = NULL;

6965:   PetscFunctionBegin;
6968:   if (is) {
6970:     PetscCall(ISGetLocalSize(is, &numRows));
6971:     PetscCall(ISGetIndices(is, &rows));
6972:   }
6973:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6974:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6975:   PetscFunctionReturn(PETSC_SUCCESS);
6976: }

6978: /*@
6979:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6980:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6982:   Collective

6984:   Input Parameters:
6985: + mat     - the matrix
6986: . numRows - the number of rows to remove
6987: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6988: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6989: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6990: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6992:   Level: intermediate

6994:   Notes:
6995:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

7007:   Fortran Note:
7008:   `idxm` and `idxn` should be declared as
7009: .vb
7010:     MatStencil idxm(4, m)
7011: .ve
7012:   and the values inserted using
7013: .vb
7014:     idxm(MatStencil_i, 1) = i
7015:     idxm(MatStencil_j, 1) = j
7016:     idxm(MatStencil_k, 1) = k
7017:     idxm(MatStencil_c, 1) = c
7018:    etc
7019: .ve

7021: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7022:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7023: @*/
7024: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7025: {
7026:   PetscInt  dim    = mat->stencil.dim;
7027:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7028:   PetscInt *dims   = mat->stencil.dims + 1;
7029:   PetscInt *starts = mat->stencil.starts;
7030:   PetscInt *dxm    = (PetscInt *)rows;
7031:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7033:   PetscFunctionBegin;
7036:   if (numRows) PetscAssertPointer(rows, 3);

7038:   PetscCall(PetscMalloc1(numRows, &jdxm));
7039:   for (i = 0; i < numRows; ++i) {
7040:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7041:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7042:     /* Local index in X dir */
7043:     tmp = *dxm++ - starts[0];
7044:     /* Loop over remaining dimensions */
7045:     for (j = 0; j < dim - 1; ++j) {
7046:       /* If nonlocal, set index to be negative */
7047:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7048:       /* Update local index */
7049:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7050:     }
7051:     /* Skip component slot if necessary */
7052:     if (mat->stencil.noc) dxm++;
7053:     /* Local row number */
7054:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7055:   }
7056:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
7057:   PetscCall(PetscFree(jdxm));
7058:   PetscFunctionReturn(PETSC_SUCCESS);
7059: }

7061: /*@
7062:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
7063:   of a set of rows and columns of a matrix.

7065:   Collective

7067:   Input Parameters:
7068: + mat     - the matrix
7069: . numRows - the number of rows/columns to remove
7070: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
7071: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
7072: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7073: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7075:   Level: intermediate

7077:   Notes:
7078:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

7090:   Fortran Note:
7091:   `idxm` and `idxn` should be declared as
7092: .vb
7093:     MatStencil idxm(4, m)
7094: .ve
7095:   and the values inserted using
7096: .vb
7097:     idxm(MatStencil_i, 1) = i
7098:     idxm(MatStencil_j, 1) = j
7099:     idxm(MatStencil_k, 1) = k
7100:     idxm(MatStencil_c, 1) = c
7101:     etc
7102: .ve

7104: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7105:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7106: @*/
7107: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7108: {
7109:   PetscInt  dim    = mat->stencil.dim;
7110:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7111:   PetscInt *dims   = mat->stencil.dims + 1;
7112:   PetscInt *starts = mat->stencil.starts;
7113:   PetscInt *dxm    = (PetscInt *)rows;
7114:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7116:   PetscFunctionBegin;
7119:   if (numRows) PetscAssertPointer(rows, 3);

7121:   PetscCall(PetscMalloc1(numRows, &jdxm));
7122:   for (i = 0; i < numRows; ++i) {
7123:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7124:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7125:     /* Local index in X dir */
7126:     tmp = *dxm++ - starts[0];
7127:     /* Loop over remaining dimensions */
7128:     for (j = 0; j < dim - 1; ++j) {
7129:       /* If nonlocal, set index to be negative */
7130:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7131:       /* Update local index */
7132:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7133:     }
7134:     /* Skip component slot if necessary */
7135:     if (mat->stencil.noc) dxm++;
7136:     /* Local row number */
7137:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7138:   }
7139:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7140:   PetscCall(PetscFree(jdxm));
7141:   PetscFunctionReturn(PETSC_SUCCESS);
7142: }

7144: /*@
7145:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7146:   of a set of rows of a matrix; using local numbering of rows.

7148:   Collective

7150:   Input Parameters:
7151: + mat     - the matrix
7152: . numRows - the number of rows to remove
7153: . rows    - the local row indices
7154: . diag    - value put in all diagonals of eliminated rows
7155: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7156: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7158:   Level: intermediate

7160:   Notes:
7161:   Before calling `MatZeroRowsLocal()`, the user must first set the
7162:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7164:   See `MatZeroRows()` for details on how this routine operates.

7166: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7167:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7168: @*/
7169: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7170: {
7171:   PetscFunctionBegin;
7174:   if (numRows) PetscAssertPointer(rows, 3);
7175:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7176:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7177:   MatCheckPreallocated(mat, 1);

7179:   if (mat->ops->zerorowslocal) {
7180:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7181:   } else {
7182:     IS        is, newis;
7183:     PetscInt *newRows, nl = 0;

7185:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7186:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7187:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7188:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7189:     for (PetscInt i = 0; i < numRows; i++)
7190:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7191:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7192:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7193:     PetscCall(ISDestroy(&newis));
7194:     PetscCall(ISDestroy(&is));
7195:   }
7196:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7197:   PetscFunctionReturn(PETSC_SUCCESS);
7198: }

7200: /*@
7201:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7202:   of a set of rows of a matrix; using local numbering of rows.

7204:   Collective

7206:   Input Parameters:
7207: + mat  - the matrix
7208: . is   - index set of rows to remove
7209: . diag - value put in all diagonals of eliminated rows
7210: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7211: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7213:   Level: intermediate

7215:   Notes:
7216:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7217:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7219:   See `MatZeroRows()` for details on how this routine operates.

7221: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7222:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7223: @*/
7224: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7225: {
7226:   PetscInt        numRows;
7227:   const PetscInt *rows;

7229:   PetscFunctionBegin;
7233:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7234:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7235:   MatCheckPreallocated(mat, 1);

7237:   PetscCall(ISGetLocalSize(is, &numRows));
7238:   PetscCall(ISGetIndices(is, &rows));
7239:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7240:   PetscCall(ISRestoreIndices(is, &rows));
7241:   PetscFunctionReturn(PETSC_SUCCESS);
7242: }

7244: /*@
7245:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7246:   of a set of rows and columns of a matrix; using local numbering of rows.

7248:   Collective

7250:   Input Parameters:
7251: + mat     - the matrix
7252: . numRows - the number of rows to remove
7253: . rows    - the global row indices
7254: . diag    - value put in all diagonals of eliminated rows
7255: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7256: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7258:   Level: intermediate

7260:   Notes:
7261:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7262:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7264:   See `MatZeroRowsColumns()` for details on how this routine operates.

7266: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7267:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7268: @*/
7269: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7270: {
7271:   PetscFunctionBegin;
7274:   if (numRows) PetscAssertPointer(rows, 3);
7275:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7276:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7277:   MatCheckPreallocated(mat, 1);

7279:   if (mat->ops->zerorowscolumnslocal) {
7280:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7281:   } else {
7282:     IS        is, newis;
7283:     PetscInt *newRows, nl = 0;

7285:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7286:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7287:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7288:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7289:     for (PetscInt i = 0; i < numRows; i++)
7290:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7291:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7292:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7293:     PetscCall(ISDestroy(&newis));
7294:     PetscCall(ISDestroy(&is));
7295:   }
7296:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7297:   PetscFunctionReturn(PETSC_SUCCESS);
7298: }

7300: /*@
7301:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7302:   of a set of rows and columns of a matrix; using local numbering of rows.

7304:   Collective

7306:   Input Parameters:
7307: + mat  - the matrix
7308: . is   - index set of rows to remove
7309: . diag - value put in all diagonals of eliminated rows
7310: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7311: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7313:   Level: intermediate

7315:   Notes:
7316:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7317:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7319:   See `MatZeroRowsColumns()` for details on how this routine operates.

7321: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7322:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7323: @*/
7324: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7325: {
7326:   PetscInt        numRows;
7327:   const PetscInt *rows;

7329:   PetscFunctionBegin;
7333:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7334:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7335:   MatCheckPreallocated(mat, 1);

7337:   PetscCall(ISGetLocalSize(is, &numRows));
7338:   PetscCall(ISGetIndices(is, &rows));
7339:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7340:   PetscCall(ISRestoreIndices(is, &rows));
7341:   PetscFunctionReturn(PETSC_SUCCESS);
7342: }

7344: /*@
7345:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7347:   Not Collective

7349:   Input Parameter:
7350: . mat - the matrix

7352:   Output Parameters:
7353: + m - the number of global rows
7354: - n - the number of global columns

7356:   Level: beginner

7358:   Note:
7359:   Both output parameters can be `NULL` on input.

7361: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7362: @*/
7363: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7364: {
7365:   PetscFunctionBegin;
7367:   if (m) *m = mat->rmap->N;
7368:   if (n) *n = mat->cmap->N;
7369:   PetscFunctionReturn(PETSC_SUCCESS);
7370: }

7372: /*@
7373:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7374:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7376:   Not Collective

7378:   Input Parameter:
7379: . mat - the matrix

7381:   Output Parameters:
7382: + m - the number of local rows, use `NULL` to not obtain this value
7383: - n - the number of local columns, use `NULL` to not obtain this value

7385:   Level: beginner

7387: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7388: @*/
7389: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7390: {
7391:   PetscFunctionBegin;
7393:   if (m) PetscAssertPointer(m, 2);
7394:   if (n) PetscAssertPointer(n, 3);
7395:   if (m) *m = mat->rmap->n;
7396:   if (n) *n = mat->cmap->n;
7397:   PetscFunctionReturn(PETSC_SUCCESS);
7398: }

7400: /*@
7401:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7402:   vector one multiplies this matrix by that are owned by this process.

7404:   Not Collective, unless matrix has not been allocated, then collective

7406:   Input Parameter:
7407: . mat - the matrix

7409:   Output Parameters:
7410: + m - the global index of the first local column, use `NULL` to not obtain this value
7411: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7413:   Level: developer

7415:   Notes:
7416:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7418:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7419:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7424:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7425:   Layouts](sec_matlayout) for details on matrix layouts.

7427: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7428:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7429: @*/
7430: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7431: {
7432:   PetscFunctionBegin;
7435:   if (m) PetscAssertPointer(m, 2);
7436:   if (n) PetscAssertPointer(n, 3);
7437:   MatCheckPreallocated(mat, 1);
7438:   if (m) *m = mat->cmap->rstart;
7439:   if (n) *n = mat->cmap->rend;
7440:   PetscFunctionReturn(PETSC_SUCCESS);
7441: }

7443: /*@
7444:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7445:   this MPI process.

7447:   Not Collective

7449:   Input Parameter:
7450: . mat - the matrix

7452:   Output Parameters:
7453: + m - the global index of the first local row, use `NULL` to not obtain this value
7454: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7456:   Level: beginner

7458:   Notes:
7459:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7461:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7462:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

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

7469:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7470:   would contain the result of a matrix vector product with this matrix. See [Matrix
7471:   Layouts](sec_matlayout) for details on matrix layouts.

7473: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7474:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7475: @*/
7476: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7477: {
7478:   PetscFunctionBegin;
7481:   if (m) PetscAssertPointer(m, 2);
7482:   if (n) PetscAssertPointer(n, 3);
7483:   MatCheckPreallocated(mat, 1);
7484:   if (m) *m = mat->rmap->rstart;
7485:   if (n) *n = mat->rmap->rend;
7486:   PetscFunctionReturn(PETSC_SUCCESS);
7487: }

7489: /*@
7490:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7491:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7493:   Not Collective, unless matrix has not been allocated

7495:   Input Parameter:
7496: . mat - the matrix

7498:   Output Parameter:
7499: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7500:            where `size` is the number of MPI processes used by `mat`

7502:   Level: beginner

7504:   Notes:
7505:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7507:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7508:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7513:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7514:   would contain the result of a matrix vector product with this matrix. See [Matrix
7515:   Layouts](sec_matlayout) for details on matrix layouts.

7517: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7518:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7519:           `DMDAGetGhostCorners()`, `DM`
7520: @*/
7521: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7522: {
7523:   PetscFunctionBegin;
7526:   MatCheckPreallocated(mat, 1);
7527:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7528:   PetscFunctionReturn(PETSC_SUCCESS);
7529: }

7531: /*@
7532:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7533:   vector one multiplies this vector by that are owned by each process.

7535:   Not Collective, unless matrix has not been allocated

7537:   Input Parameter:
7538: . mat - the matrix

7540:   Output Parameter:
7541: . ranges - start of each process's portion plus one more than the total length at the end

7543:   Level: beginner

7545:   Notes:
7546:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7548:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7549:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

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

7554:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7555:   Layouts](sec_matlayout) for details on matrix layouts.

7557: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7558:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7559:           `DMDAGetGhostCorners()`, `DM`
7560: @*/
7561: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7562: {
7563:   PetscFunctionBegin;
7566:   MatCheckPreallocated(mat, 1);
7567:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7568:   PetscFunctionReturn(PETSC_SUCCESS);
7569: }

7571: /*@
7572:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7574:   Not Collective

7576:   Input Parameter:
7577: . A - matrix

7579:   Output Parameters:
7580: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7581: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7583:   Level: intermediate

7585:   Note:
7586:   You should call `ISDestroy()` on the returned `IS`

7588:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7589:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7590:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7591:   details on matrix layouts.

7593: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7594: @*/
7595: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7596: {
7597:   PetscErrorCode (*f)(Mat, IS *, IS *);

7599:   PetscFunctionBegin;
7602:   MatCheckPreallocated(A, 1);
7603:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7604:   if (f) {
7605:     PetscCall((*f)(A, rows, cols));
7606:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7607:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7608:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7609:   }
7610:   PetscFunctionReturn(PETSC_SUCCESS);
7611: }

7613: /*@
7614:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7615:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7616:   to complete the factorization.

7618:   Collective

7620:   Input Parameters:
7621: + fact - the factorized matrix obtained with `MatGetFactor()`
7622: . mat  - the matrix
7623: . row  - row permutation
7624: . col  - column permutation
7625: - info - structure containing
7626: .vb
7627:       levels - number of levels of fill.
7628:       expected fill - as ratio of original fill.
7629:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7630:                 missing diagonal entries)
7631: .ve

7633:   Level: developer

7635:   Notes:
7636:   See [Matrix Factorization](sec_matfactor) for additional information.

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

7642:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

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

7647: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7648:           `MatGetOrdering()`, `MatFactorInfo`
7649: @*/
7650: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7651: {
7652:   PetscFunctionBegin;
7657:   PetscAssertPointer(info, 5);
7658:   PetscAssertPointer(fact, 1);
7659:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7660:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7661:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7662:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7663:   MatCheckPreallocated(mat, 2);

7665:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7666:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7667:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7668:   PetscFunctionReturn(PETSC_SUCCESS);
7669: }

7671: /*@
7672:   MatICCFactorSymbolic - Performs symbolic incomplete
7673:   Cholesky factorization for a symmetric matrix. Use
7674:   `MatCholeskyFactorNumeric()` to complete the factorization.

7676:   Collective

7678:   Input Parameters:
7679: + fact - the factorized matrix obtained with `MatGetFactor()`
7680: . mat  - the matrix to be factored
7681: . perm - row and column permutation
7682: - info - structure containing
7683: .vb
7684:       levels - number of levels of fill.
7685:       expected fill - as ratio of original fill.
7686: .ve

7688:   Level: developer

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

7695:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

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

7700: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7701: @*/
7702: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7703: {
7704:   PetscFunctionBegin;
7708:   PetscAssertPointer(info, 4);
7709:   PetscAssertPointer(fact, 1);
7710:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7711:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7712:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7713:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7714:   MatCheckPreallocated(mat, 2);

7716:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7717:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7718:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7719:   PetscFunctionReturn(PETSC_SUCCESS);
7720: }

7722: /*@
7723:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7724:   points to an array of valid matrices, they may be reused to store the new
7725:   submatrices.

7727:   Collective

7729:   Input Parameters:
7730: + mat   - the matrix
7731: . n     - the number of submatrixes to be extracted (on this process, may be zero)
7732: . irow  - index set of rows to extract
7733: . icol  - index set of columns to extract
7734: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7736:   Output Parameter:
7737: . submat - the array of submatrices

7739:   Level: advanced

7741:   Notes:
7742:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7743:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7744:   to extract a parallel submatrix.

7746:   Some matrix types place restrictions on the row and column
7747:   indices, such as that they be sorted or that they be equal to each other.
7748:   `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.

7750:   The index sets may not have duplicate entries.

7752:   When extracting submatrices from a parallel matrix, each process can
7753:   form a different submatrix by setting the rows and columns of its
7754:   individual index sets according to the local submatrix desired.

7756:   When finished using the submatrices, the user should destroy
7757:   them with `MatDestroySubMatrices()`.

7759:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7760:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7762:   This routine creates the matrices in submat; you should NOT create them before
7763:   calling it. It also allocates the array of matrix pointers submat.

7765:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7766:   request one row/column in a block, they must request all rows/columns that are in
7767:   that block. For example, if the block size is 2 you cannot request just row 0 and
7768:   column 0.

7770:   Fortran Note:
7771: .vb
7772:   Mat, pointer :: submat(:)
7773: .ve

7775: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7776: @*/
7777: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7778: {
7779:   PetscInt  i;
7780:   PetscBool eq;

7782:   PetscFunctionBegin;
7785:   if (n) {
7786:     PetscAssertPointer(irow, 3);
7788:     PetscAssertPointer(icol, 4);
7790:   }
7791:   PetscAssertPointer(submat, 6);
7792:   if (n && scall == MAT_REUSE_MATRIX) {
7793:     PetscAssertPointer(*submat, 6);
7795:   }
7796:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7797:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7798:   MatCheckPreallocated(mat, 1);
7799:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7800:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7801:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7802:   for (i = 0; i < n; i++) {
7803:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7804:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7805:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7806: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7807:     if (mat->boundtocpu && mat->bindingpropagates) {
7808:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7809:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7810:     }
7811: #endif
7812:   }
7813:   PetscFunctionReturn(PETSC_SUCCESS);
7814: }

7816: /*@
7817:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7819:   Collective

7821:   Input Parameters:
7822: + mat   - the matrix
7823: . n     - the number of submatrixes to be extracted
7824: . irow  - index set of rows to extract
7825: . icol  - index set of columns to extract
7826: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7828:   Output Parameter:
7829: . submat - the array of submatrices

7831:   Level: advanced

7833:   Note:
7834:   This is used by `PCGASM`

7836: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7837: @*/
7838: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7839: {
7840:   PetscInt  i;
7841:   PetscBool eq;

7843:   PetscFunctionBegin;
7846:   if (n) {
7847:     PetscAssertPointer(irow, 3);
7849:     PetscAssertPointer(icol, 4);
7851:   }
7852:   PetscAssertPointer(submat, 6);
7853:   if (n && scall == MAT_REUSE_MATRIX) {
7854:     PetscAssertPointer(*submat, 6);
7856:   }
7857:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7858:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7859:   MatCheckPreallocated(mat, 1);

7861:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7862:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7863:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7864:   for (i = 0; i < n; i++) {
7865:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7866:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7867:   }
7868:   PetscFunctionReturn(PETSC_SUCCESS);
7869: }

7871: /*@
7872:   MatDestroyMatrices - Destroys an array of matrices

7874:   Collective

7876:   Input Parameters:
7877: + n   - the number of local matrices
7878: - mat - the matrices (this is a pointer to the array of matrices)

7880:   Level: advanced

7882:   Notes:
7883:   Frees not only the matrices, but also the array that contains the matrices

7885:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7887: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7888: @*/
7889: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7890: {
7891:   PetscInt i;

7893:   PetscFunctionBegin;
7894:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7895:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7896:   PetscAssertPointer(mat, 2);

7898:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7900:   /* memory is allocated even if n = 0 */
7901:   PetscCall(PetscFree(*mat));
7902:   PetscFunctionReturn(PETSC_SUCCESS);
7903: }

7905: /*@
7906:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7908:   Collective

7910:   Input Parameters:
7911: + n   - the number of local matrices
7912: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7914:   Level: advanced

7916:   Note:
7917:   Frees not only the matrices, but also the array that contains the matrices

7919: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7920: @*/
7921: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7922: {
7923:   Mat mat0;

7925:   PetscFunctionBegin;
7926:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7927:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7928:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7929:   PetscAssertPointer(mat, 2);

7931:   mat0 = (*mat)[0];
7932:   if (mat0 && mat0->ops->destroysubmatrices) {
7933:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7934:   } else {
7935:     PetscCall(MatDestroyMatrices(n, mat));
7936:   }
7937:   PetscFunctionReturn(PETSC_SUCCESS);
7938: }

7940: /*@
7941:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7943:   Collective

7945:   Input Parameter:
7946: . mat - the matrix

7948:   Output Parameter:
7949: . matstruct - the sequential matrix with the nonzero structure of `mat`

7951:   Level: developer

7953: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7954: @*/
7955: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7956: {
7957:   PetscFunctionBegin;
7959:   PetscAssertPointer(matstruct, 2);

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

7965:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7966:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7967:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7968:   PetscFunctionReturn(PETSC_SUCCESS);
7969: }

7971: /*@
7972:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7974:   Collective

7976:   Input Parameter:
7977: . mat - the matrix

7979:   Level: advanced

7981:   Note:
7982:   This is not needed, one can just call `MatDestroy()`

7984: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7985: @*/
7986: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7987: {
7988:   PetscFunctionBegin;
7989:   PetscAssertPointer(mat, 1);
7990:   PetscCall(MatDestroy(mat));
7991:   PetscFunctionReturn(PETSC_SUCCESS);
7992: }

7994: /*@
7995:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7996:   replaces the index sets by larger ones that represent submatrices with
7997:   additional overlap.

7999:   Collective

8001:   Input Parameters:
8002: + mat - the matrix
8003: . n   - the number of index sets
8004: . is  - the array of index sets (these index sets will changed during the call)
8005: - ov  - the additional overlap requested

8007:   Options Database Key:
8008: . -mat_increase_overlap_scalable (true|false) - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

8010:   Level: developer

8012:   Note:
8013:   The computed overlap preserves the matrix block sizes when the blocks are square.
8014:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
8015:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

8017: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
8018: @*/
8019: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
8020: {
8021:   PetscInt i, bs, cbs;

8023:   PetscFunctionBegin;
8027:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8028:   if (n) {
8029:     PetscAssertPointer(is, 3);
8031:   }
8032:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8033:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8034:   MatCheckPreallocated(mat, 1);

8036:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
8037:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8038:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
8039:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8040:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
8041:   if (bs == cbs) {
8042:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
8043:   }
8044:   PetscFunctionReturn(PETSC_SUCCESS);
8045: }

8047: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

8049: /*@
8050:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
8051:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
8052:   additional overlap.

8054:   Collective

8056:   Input Parameters:
8057: + mat - the matrix
8058: . n   - the number of index sets
8059: . is  - the array of index sets (these index sets will changed during the call)
8060: - ov  - the additional overlap requested

8062:   `   Options Database Key:
8063: . -mat_increase_overlap_scalable (true|false) - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

8065:   Level: developer

8067: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
8068: @*/
8069: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
8070: {
8071:   PetscInt i;

8073:   PetscFunctionBegin;
8076:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8077:   if (n) {
8078:     PetscAssertPointer(is, 3);
8080:   }
8081:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8082:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8083:   MatCheckPreallocated(mat, 1);
8084:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
8085:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8086:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
8087:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8088:   PetscFunctionReturn(PETSC_SUCCESS);
8089: }

8091: /*@
8092:   MatGetBlockSize - Returns the matrix block size.

8094:   Not Collective

8096:   Input Parameter:
8097: . mat - the matrix

8099:   Output Parameter:
8100: . bs - block size

8102:   Level: intermediate

8104:   Notes:
8105:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8107:   If the block size has not been set yet this routine returns 1.

8109: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8110: @*/
8111: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8112: {
8113:   PetscFunctionBegin;
8115:   PetscAssertPointer(bs, 2);
8116:   *bs = mat->rmap->bs;
8117:   PetscFunctionReturn(PETSC_SUCCESS);
8118: }

8120: /*@
8121:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8123:   Not Collective

8125:   Input Parameter:
8126: . mat - the matrix

8128:   Output Parameters:
8129: + rbs - row block size
8130: - cbs - column block size

8132:   Level: intermediate

8134:   Notes:
8135:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8136:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8138:   If a block size has not been set yet this routine returns 1.

8140: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8141: @*/
8142: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8143: {
8144:   PetscFunctionBegin;
8146:   if (rbs) PetscAssertPointer(rbs, 2);
8147:   if (cbs) PetscAssertPointer(cbs, 3);
8148:   if (rbs) *rbs = mat->rmap->bs;
8149:   if (cbs) *cbs = mat->cmap->bs;
8150:   PetscFunctionReturn(PETSC_SUCCESS);
8151: }

8153: /*@
8154:   MatSetBlockSize - Sets the matrix block size.

8156:   Logically Collective

8158:   Input Parameters:
8159: + mat - the matrix
8160: - bs  - block size

8162:   Level: intermediate

8164:   Notes:
8165:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8166:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8168:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8169:   is compatible with the matrix local sizes.

8171: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8172: @*/
8173: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8174: {
8175:   PetscFunctionBegin;
8178:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8179:   PetscFunctionReturn(PETSC_SUCCESS);
8180: }

8182: typedef struct {
8183:   PetscInt         n;
8184:   IS              *is;
8185:   Mat             *mat;
8186:   PetscObjectState nonzerostate;
8187:   Mat              C;
8188: } EnvelopeData;

8190: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8191: {
8192:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8194:   PetscFunctionBegin;
8195:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8196:   PetscCall(PetscFree(edata->is));
8197:   PetscCall(PetscFree(edata));
8198:   PetscFunctionReturn(PETSC_SUCCESS);
8199: }

8201: /*@
8202:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8203:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8205:   Collective

8207:   Input Parameter:
8208: . mat - the matrix

8210:   Level: intermediate

8212:   Notes:
8213:   There can be zeros within the blocks

8215:   The blocks can overlap between processes, including laying on more than two processes

8217: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8218: @*/
8219: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8220: {
8221:   PetscInt        n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8222:   PetscInt       *diag, *odiag, sc;
8223:   PetscInt       *seqv, *parv, *gidx;
8224:   const PetscInt *ia, *ja;
8225:   PetscBool       set, flag, done;
8226:   Mat             AA = mat, A;
8227:   MPI_Comm        comm;
8228:   PetscMPIInt     rank, size, tag;
8229:   MPI_Status      status;
8230:   PetscContainer  container;
8231:   EnvelopeData   *edata;
8232:   PetscSF         sf;
8233:   PetscLayout     layout;

8235:   PetscFunctionBegin;
8237:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8238:   if (!set || !flag) {
8239:     /* TODO: only needs nonzero structure of transpose */
8240:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8241:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8242:   }
8243:   PetscCall(MatAIJGetLocalMat(AA, &A));
8244:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8245:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8247:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8248:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8249:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8250:   PetscCallMPI(MPI_Comm_size(comm, &size));
8251:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8253:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8255:   if (rank > 0) {
8256:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8257:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8258:   }
8259:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8260:   for (i = 0; i < n; i++) {
8261:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8262:     II  = rstart + i;
8263:     if (env == II) {
8264:       starts[lblocks]  = tbs;
8265:       sizes[lblocks++] = 1 + II - tbs;
8266:       tbs              = 1 + II;
8267:     }
8268:   }
8269:   if (rank < size - 1) {
8270:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8271:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8272:   }

8274:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8275:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8276:   PetscCall(MatDestroy(&A));

8278:   PetscCall(PetscNew(&edata));
8279:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8280:   edata->n = lblocks;
8281:   /* create IS needed for extracting blocks from the original matrix */
8282:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8283:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8285:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8286:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8287:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8288:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8289:   PetscCall(MatSetType(edata->C, MATAIJ));

8291:   /* Communicate the start and end of each row, from each block to the correct rank */
8292:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8293:   PetscCall(PetscCalloc3(2 * ln, &seqv, 2 * mat->rmap->n, &parv, 2 * ln, &gidx));
8294:   for (PetscInt i = 0; i < lblocks; i++) {
8295:     for (PetscInt j = 0; j < sizes[i]; j++) {
8296:       seqv[cnt]     = starts[i];
8297:       seqv[cnt + 1] = starts[i] + sizes[i];
8298:       cnt += 2;
8299:     }
8300:   }
8301:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8302:   sc -= cnt;
8303:   for (PetscInt i = 0; i < cnt; i++) gidx[i] = sc + i;
8304:   PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, 1, &layout));
8305:   PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)mat), &sf));
8306:   PetscCall(PetscSFSetGraphLayout(sf, layout, cnt, NULL, PETSC_COPY_VALUES, gidx));
8307:   PetscCall(PetscLayoutDestroy(&layout));
8308:   PetscCall(PetscSFReduceBegin(sf, MPIU_INT, seqv, parv, MPI_REPLACE));
8309:   PetscCall(PetscSFReduceEnd(sf, MPIU_INT, seqv, parv, MPI_REPLACE));
8310:   PetscCall(PetscSFDestroy(&sf));
8311:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8312:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8313:   cnt = 0;
8314:   PetscCall(MatGetSize(mat, NULL, &n));
8315:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8316:     PetscInt start, end, d = 0, od = 0;

8318:     start = parv[cnt];
8319:     end   = parv[cnt + 1];
8320:     cnt += 2;

8322:     if (start < cstart) {
8323:       od += cstart - start + n - cend;
8324:       d += cend - cstart;
8325:     } else if (start < cend) {
8326:       od += n - cend;
8327:       d += cend - start;
8328:     } else od += n - start;
8329:     if (end <= cstart) {
8330:       od -= cstart - end + n - cend;
8331:       d -= cend - cstart;
8332:     } else if (end < cend) {
8333:       od -= n - cend;
8334:       d -= cend - end;
8335:     } else od -= n - end;

8337:     odiag[i] = od;
8338:     diag[i]  = d;
8339:   }
8340:   PetscCall(PetscFree3(seqv, parv, gidx));
8341:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8342:   PetscCall(PetscFree2(diag, odiag));
8343:   PetscCall(PetscFree2(sizes, starts));

8345:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8346:   PetscCall(PetscContainerSetPointer(container, edata));
8347:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8348:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8349:   PetscCall(PetscObjectDereference((PetscObject)container));
8350:   PetscFunctionReturn(PETSC_SUCCESS);
8351: }

8353: /*@
8354:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8356:   Collective

8358:   Input Parameters:
8359: + A     - the matrix
8360: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8362:   Output Parameter:
8363: . C - matrix with inverted block diagonal of `A`

8365:   Level: advanced

8367:   Note:
8368:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8370: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8371: @*/
8372: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8373: {
8374:   PetscContainer   container;
8375:   EnvelopeData    *edata;
8376:   PetscObjectState nonzerostate;

8378:   PetscFunctionBegin;
8379:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8380:   if (!container) {
8381:     PetscCall(MatComputeVariableBlockEnvelope(A));
8382:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8383:   }
8384:   PetscCall(PetscContainerGetPointer(container, &edata));
8385:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8386:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8387:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8389:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8390:   *C = edata->C;

8392:   for (PetscInt i = 0; i < edata->n; i++) {
8393:     Mat          D;
8394:     PetscScalar *dvalues;

8396:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8397:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8398:     PetscCall(MatSeqDenseInvert(D));
8399:     PetscCall(MatDenseGetArray(D, &dvalues));
8400:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8401:     PetscCall(MatDestroy(&D));
8402:   }
8403:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8404:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8405:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8406:   PetscFunctionReturn(PETSC_SUCCESS);
8407: }

8409: /*@
8410:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8412:   Not Collective

8414:   Input Parameters:
8415: + mat     - the matrix
8416: . nblocks - the number of blocks on this process, each block can only exist on a single MPI process
8417: - bsizes  - the block sizes

8419:   Level: intermediate

8421:   Note:
8422:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8424: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8425:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8426: @*/
8427: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8428: {
8429:   PetscInt ncnt = 0, nlocal;

8431:   PetscFunctionBegin;
8433:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8434:   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);
8435:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8436:   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);
8437:   PetscCall(PetscFree(mat->bsizes));
8438:   mat->nblocks = nblocks;
8439:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8440:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8441:   PetscFunctionReturn(PETSC_SUCCESS);
8442: }

8444: /*@
8445:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8447:   Not Collective; No Fortran Support

8449:   Input Parameter:
8450: . mat - the matrix

8452:   Output Parameters:
8453: + nblocks - the number of blocks on this process
8454: - bsizes  - the block sizes

8456:   Level: intermediate

8458: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8459: @*/
8460: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8461: {
8462:   PetscFunctionBegin;
8464:   if (nblocks) *nblocks = mat->nblocks;
8465:   if (bsizes) *bsizes = mat->bsizes;
8466:   PetscFunctionReturn(PETSC_SUCCESS);
8467: }

8469: /*@
8470:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8472:   Not Collective

8474:   Input Parameters:
8475: + subA  - the submatrix
8476: . A     - the original matrix
8477: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8479:   Level: developer

8481:   Note:
8482:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8484: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8485: @*/
8486: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8487: {
8488:   const PetscInt *rows;
8489:   PetscInt        n, rStart, rEnd, Nb = 0;
8490:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8492:   PetscFunctionBegin;
8493:   // The code for block size extraction does not support an unsorted IS
8494:   if (flg) PetscCall(ISSorted(isrow, &flg));
8495:   // We don't support originally off-diagonal blocks
8496:   if (flg) {
8497:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8498:     PetscCall(ISGetLocalSize(isrow, &n));
8499:     PetscCall(ISGetIndices(isrow, &rows));
8500:     for (PetscInt i = 0; i < n && flg; ++i) {
8501:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8502:     }
8503:     PetscCall(ISRestoreIndices(isrow, &rows));
8504:   }
8505:   // quiet return if we can't extract block size
8506:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8507:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8509:   // extract block sizes
8510:   PetscCall(ISGetIndices(isrow, &rows));
8511:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8512:     PetscBool occupied = PETSC_FALSE;

8514:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8515:       const PetscInt row = gr + br;

8517:       if (i == n) break;
8518:       if (rows[i] == row) {
8519:         occupied = PETSC_TRUE;
8520:         ++i;
8521:       }
8522:       while (i < n && rows[i] < row) ++i;
8523:     }
8524:     gr += A->bsizes[b];
8525:     if (occupied) ++Nb;
8526:   }
8527:   subA->nblocks = Nb;
8528:   PetscCall(PetscFree(subA->bsizes));
8529:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8530:   PetscInt sb = 0;
8531:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8532:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8533:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8534:       const PetscInt row = gr + br;

8536:       if (i == n) break;
8537:       if (rows[i] == row) {
8538:         ++subA->bsizes[sb];
8539:         ++i;
8540:       }
8541:       while (i < n && rows[i] < row) ++i;
8542:     }
8543:     gr += A->bsizes[b];
8544:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8545:   }
8546:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8547:   PetscInt nlocal, ncnt = 0;
8548:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8549:   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);
8550:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8551:   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);
8552:   PetscCall(ISRestoreIndices(isrow, &rows));
8553:   PetscFunctionReturn(PETSC_SUCCESS);
8554: }

8556: /*@
8557:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8559:   Logically Collective

8561:   Input Parameters:
8562: + mat - the matrix
8563: . rbs - row block size
8564: - cbs - column block size

8566:   Level: intermediate

8568:   Notes:
8569:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8570:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8571:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8573:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8574:   are compatible with the matrix local sizes.

8576:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8578: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8579: @*/
8580: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8581: {
8582:   PetscFunctionBegin;
8586:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8587:   if (mat->rmap->refcnt) {
8588:     ISLocalToGlobalMapping l2g  = NULL;
8589:     PetscLayout            nmap = NULL;

8591:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8592:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8593:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8594:     mat->rmap          = nmap;
8595:     mat->rmap->mapping = l2g;
8596:   }
8597:   if (mat->cmap->refcnt) {
8598:     ISLocalToGlobalMapping l2g  = NULL;
8599:     PetscLayout            nmap = NULL;

8601:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8602:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8603:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8604:     mat->cmap          = nmap;
8605:     mat->cmap->mapping = l2g;
8606:   }
8607:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8608:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8609:   PetscFunctionReturn(PETSC_SUCCESS);
8610: }

8612: /*@
8613:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8615:   Logically Collective

8617:   Input Parameters:
8618: + mat     - the matrix
8619: . fromRow - matrix from which to copy row block size
8620: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8622:   Level: developer

8624: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8625: @*/
8626: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8627: {
8628:   PetscFunctionBegin;
8632:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8633:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8634:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8635:   PetscFunctionReturn(PETSC_SUCCESS);
8636: }

8638: /*@
8639:   MatResidual - Default routine to calculate the residual $r = b - Ax$

8641:   Collective

8643:   Input Parameters:
8644: + mat - the matrix
8645: . b   - the right-hand-side
8646: - x   - the approximate solution

8648:   Output Parameter:
8649: . r - location to store the residual

8651:   Level: developer

8653: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8654: @*/
8655: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8656: {
8657:   PetscFunctionBegin;
8663:   MatCheckPreallocated(mat, 1);
8664:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8665:   if (!mat->ops->residual) {
8666:     PetscCall(MatMult(mat, x, r));
8667:     PetscCall(VecAYPX(r, -1.0, b));
8668:   } else {
8669:     PetscUseTypeMethod(mat, residual, b, x, r);
8670:   }
8671:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8672:   PetscFunctionReturn(PETSC_SUCCESS);
8673: }

8675: /*@
8676:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8678:   Collective

8680:   Input Parameters:
8681: + mat             - the matrix
8682: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8683: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8684: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8685:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8686:                     always used.

8688:   Output Parameters:
8689: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8690: . 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
8691: . ja   - the column indices, use `NULL` if not needed
8692: - done - indicates if the routine actually worked and returned appropriate `ia` and `ja` arrays; callers
8693:          are responsible for handling the case when done is `PETSC_FALSE` and `ia` and `ja` are not provided

8695:   Level: developer

8697:   Notes:
8698:   You CANNOT change any of the `ia` or `ja` values.

8700:   Use `MatRestoreRowIJ()` when you are finished accessing the `ia` and `ja` values.

8702:   Fortran Notes:
8703:   Use
8704: .vb
8705:     PetscInt, pointer :: ia(:),ja(:)
8706:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8707:     ! Access the ith and jth entries via ia(i) and ja(j)
8708: .ve

8710: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8711: @*/
8712: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8713: {
8714:   PetscFunctionBegin;
8717:   if (n) PetscAssertPointer(n, 5);
8718:   if (ia) PetscAssertPointer(ia, 6);
8719:   if (ja) PetscAssertPointer(ja, 7);
8720:   if (done) PetscAssertPointer(done, 8);
8721:   MatCheckPreallocated(mat, 1);
8722:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8723:   else {
8724:     if (done) *done = PETSC_TRUE;
8725:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8726:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8727:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8728:   }
8729:   PetscFunctionReturn(PETSC_SUCCESS);
8730: }

8732: /*@
8733:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8735:   Collective

8737:   Input Parameters:
8738: + mat             - the matrix
8739: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8740: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8741:                     symmetrized
8742: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8743:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8744:                     always used.

8746:   Output Parameters:
8747: + n    - number of columns in the (possibly compressed) matrix
8748: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8749: . ja   - the row indices
8750: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8752:   Level: developer

8754: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8755: @*/
8756: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8757: {
8758:   PetscFunctionBegin;
8761:   PetscAssertPointer(n, 5);
8762:   if (ia) PetscAssertPointer(ia, 6);
8763:   if (ja) PetscAssertPointer(ja, 7);
8764:   PetscAssertPointer(done, 8);
8765:   MatCheckPreallocated(mat, 1);
8766:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8767:   else {
8768:     *done = PETSC_TRUE;
8769:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8770:   }
8771:   PetscFunctionReturn(PETSC_SUCCESS);
8772: }

8774: /*@
8775:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8777:   Collective

8779:   Input Parameters:
8780: + mat             - the matrix
8781: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8782: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8783: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8784:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8785:                     always used.
8786: . n               - size of (possibly compressed) matrix, or `NULL`
8787: . ia              - the row pointers, or `NULL`
8788: - ja              - the column indices, or `NULL`

8790:   Output Parameter:
8791: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8793:   Level: developer

8795:   Note:
8796:   This routine zeros out `n`, `ia`, and `ja` if they are provided. Use of `ia` or `ja` after `MatRestoreRowIJ()` is always invalid.

8798: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8799: @*/
8800: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8801: {
8802:   PetscFunctionBegin;
8805:   if (ia) PetscAssertPointer(ia, 6);
8806:   if (ja) PetscAssertPointer(ja, 7);
8807:   if (done) PetscAssertPointer(done, 8);
8808:   MatCheckPreallocated(mat, 1);

8810:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8811:   else {
8812:     if (done) *done = PETSC_TRUE;
8813:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8814:     if (n) *n = 0;
8815:     if (ia) *ia = NULL;
8816:     if (ja) *ja = NULL;
8817:   }
8818:   PetscFunctionReturn(PETSC_SUCCESS);
8819: }

8821: /*@
8822:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8824:   Collective

8826:   Input Parameters:
8827: + mat             - the matrix
8828: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8829: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8830: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8831:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8832:                     always used.

8834:   Output Parameters:
8835: + n    - size of (possibly compressed) matrix
8836: . ia   - the column pointers
8837: . ja   - the row indices
8838: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8840:   Level: developer

8842: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8843: @*/
8844: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8845: {
8846:   PetscFunctionBegin;
8849:   if (ia) PetscAssertPointer(ia, 6);
8850:   if (ja) PetscAssertPointer(ja, 7);
8851:   PetscAssertPointer(done, 8);
8852:   MatCheckPreallocated(mat, 1);

8854:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8855:   else {
8856:     *done = PETSC_TRUE;
8857:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8858:     if (n) *n = 0;
8859:     if (ia) *ia = NULL;
8860:     if (ja) *ja = NULL;
8861:   }
8862:   PetscFunctionReturn(PETSC_SUCCESS);
8863: }

8865: /*@
8866:   MatColoringPatch - Utility routine used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8867:   `MatGetColumnIJ()`.

8869:   Collective

8871:   Input Parameters:
8872: + mat        - the matrix
8873: . ncolors    - maximum color value
8874: . n          - number of entries in `colorarray`
8875: - colorarray - array indicating color for each column

8877:   Output Parameter:
8878: . iscoloring - coloring generated using `colorarray` information

8880:   Level: developer

8882: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8883: @*/
8884: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8885: {
8886:   PetscFunctionBegin;
8889:   PetscAssertPointer(colorarray, 4);
8890:   PetscAssertPointer(iscoloring, 5);
8891:   MatCheckPreallocated(mat, 1);

8893:   if (!mat->ops->coloringpatch) {
8894:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8895:   } else {
8896:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8897:   }
8898:   PetscFunctionReturn(PETSC_SUCCESS);
8899: }

8901: /*@
8902:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8904:   Logically Collective

8906:   Input Parameter:
8907: . mat - the factored matrix to be reset

8909:   Level: developer

8911:   Notes:
8912:   This routine should be used only with factored matrices formed by in-place
8913:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8914:   format). This option can save memory, for example, when solving nonlinear
8915:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8916:   ILU(0) preconditioner.

8918:   One can specify in-place ILU(0) factorization by calling
8919: .vb
8920:      PCType(pc,PCILU);
8921:      PCFactorSeUseInPlace(pc);
8922: .ve
8923:   or by using the options -pc_type ilu -pc_factor_in_place

8925:   In-place factorization ILU(0) can also be used as a local
8926:   solver for the blocks within the block Jacobi or additive Schwarz
8927:   methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8928:   for details on setting local solver options.

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

8934: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8935: @*/
8936: PetscErrorCode MatSetUnfactored(Mat mat)
8937: {
8938:   PetscFunctionBegin;
8941:   MatCheckPreallocated(mat, 1);
8942:   mat->factortype = MAT_FACTOR_NONE;
8943:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8944:   PetscUseTypeMethod(mat, setunfactored);
8945:   PetscFunctionReturn(PETSC_SUCCESS);
8946: }

8948: /*@
8949:   MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8950:   as the original matrix.

8952:   Collective

8954:   Input Parameters:
8955: + mat   - the original matrix
8956: . isrow - parallel `IS` containing the rows this process should obtain
8957: . 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.
8958: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8960:   Output Parameter:
8961: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)

8963:   Level: advanced

8965:   Notes:
8966:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8968:   Some matrix types place restrictions on the row and column indices, such
8969:   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;
8970:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8971:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.

8973:   The index sets may not have duplicate entries.

8975:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8976:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8977:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8978:   will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8979:   you are finished using it.

8981:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8982:   the input matrix.

8984:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8986:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8987:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8989:   Example usage:
8990:   Consider the following 8x8 matrix with 34 non-zero values, that is
8991:   assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8992:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8993:   as follows
8994: .vb
8995:             1  2  0  |  0  3  0  |  0  4
8996:     Proc0   0  5  6  |  7  0  0  |  8  0
8997:             9  0 10  | 11  0  0  | 12  0
8998:     -------------------------------------
8999:            13  0 14  | 15 16 17  |  0  0
9000:     Proc1   0 18  0  | 19 20 21  |  0  0
9001:             0  0  0  | 22 23  0  | 24  0
9002:     -------------------------------------
9003:     Proc2  25 26 27  |  0  0 28  | 29  0
9004:            30  0  0  | 31 32 33  |  0 34
9005: .ve

9007:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is

9009: .vb
9010:             2  0  |  0  3  0  |  0
9011:     Proc0   5  6  |  7  0  0  |  8
9012:     -------------------------------
9013:     Proc1  18  0  | 19 20 21  |  0
9014:     -------------------------------
9015:     Proc2  26 27  |  0  0 28  | 29
9016:             0  0  | 31 32 33  |  0
9017: .ve

9019: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
9020: @*/
9021: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
9022: {
9023:   PetscMPIInt size;
9024:   Mat        *local;
9025:   IS          iscoltmp;
9026:   PetscBool   flg;

9028:   PetscFunctionBegin;
9032:   PetscAssertPointer(newmat, 5);
9035:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9036:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
9037:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

9039:   MatCheckPreallocated(mat, 1);
9040:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

9042:   if (!iscol || isrow == iscol) {
9043:     PetscBool   stride;
9044:     PetscMPIInt grab = 0;
9045:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
9046:     if (stride) {
9047:       PetscInt first, step, n, rstart, rend;
9048:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
9049:       if (step == 1) {
9050:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
9051:         if (rstart == first) {
9052:           PetscCall(ISGetLocalSize(isrow, &n));
9053:           if (n == rend - rstart) grab = 1;
9054:         }
9055:       }
9056:     }
9057:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
9058:     if (grab) {
9059:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
9060:       if (cll == MAT_INITIAL_MATRIX) {
9061:         *newmat = mat;
9062:         PetscCall(PetscObjectReference((PetscObject)mat));
9063:       }
9064:       PetscFunctionReturn(PETSC_SUCCESS);
9065:     }
9066:   }

9068:   if (!iscol) {
9069:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
9070:   } else {
9071:     iscoltmp = iscol;
9072:   }

9074:   /* if original matrix is on just one process then use submatrix generated */
9075:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
9076:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
9077:     goto setproperties;
9078:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
9079:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
9080:     *newmat = *local;
9081:     PetscCall(PetscFree(local));
9082:     goto setproperties;
9083:   } else if (!mat->ops->createsubmatrix) {
9084:     /* Create a new matrix type that implements the operation using the full matrix */
9085:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9086:     switch (cll) {
9087:     case MAT_INITIAL_MATRIX:
9088:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9089:       break;
9090:     case MAT_REUSE_MATRIX:
9091:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9092:       break;
9093:     default:
9094:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9095:     }
9096:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9097:     goto setproperties;
9098:   }

9100:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9101:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9102:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9104: setproperties:
9105:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9106:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9107:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9108:   }
9109:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9110:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9111:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9112:   PetscFunctionReturn(PETSC_SUCCESS);
9113: }

9115: /*@
9116:   MatPropagateSymmetryOptions - Propagates symmetry properties set on a matrix to another matrix

9118:   Not Collective

9120:   Input Parameters:
9121: + A - the matrix we wish to propagate properties from
9122: - B - the matrix we wish to propagate properties to

9124:   Level: beginner

9126:   Note:
9127:   Propagates the properties associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9129: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9130: @*/
9131: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9132: {
9133:   PetscFunctionBegin;
9136:   B->symmetry_eternal            = A->symmetry_eternal;
9137:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9138:   B->symmetric                   = A->symmetric;
9139:   B->structurally_symmetric      = A->structurally_symmetric;
9140:   B->spd                         = A->spd;
9141:   B->hermitian                   = A->hermitian;
9142:   PetscFunctionReturn(PETSC_SUCCESS);
9143: }

9145: /*@
9146:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9147:   used during the assembly process to store values that belong to
9148:   other processes.

9150:   Not Collective

9152:   Input Parameters:
9153: + mat   - the matrix
9154: . size  - the initial size of the stash.
9155: - bsize - the initial size of the block-stash(if used).

9157:   Options Database Key:
9158: . -matstash_initial_size (size|size0,size1,...,sizep-1) - set initial size of stash for all or each of the MPI processes, sets both block and non-block stash sizes

9160:   Level: intermediate

9162:   Notes:
9163:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9164:   the stash is used for values set with `MatSetValues()`

9166:   Run with the option `-info` and look for output of the form
9167:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9168:   to determine the appropriate value, MM, to use for size and
9169:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9170:   to determine the value, BMM to use for bsize

9172: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9173: @*/
9174: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9175: {
9176:   PetscFunctionBegin;
9179:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9180:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9181:   PetscFunctionReturn(PETSC_SUCCESS);
9182: }

9184: /*@
9185:   MatInterpolateAdd - $w = y + A x$ or $A^T x$ depending on the shape of
9186:   the matrix

9188:   Neighbor-wise Collective

9190:   Input Parameters:
9191: + A - the matrix
9192: . x - the vector to be multiplied by the interpolation operator
9193: - y - the vector to be added to the result

9195:   Output Parameter:
9196: . w - the resulting vector

9198:   Level: intermediate

9200:   Notes:
9201:   `w` may be the same vector as `y`.

9203:   This allows one to use either the restriction or interpolation (its transpose)
9204:   matrix to do the interpolation

9206: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9207: @*/
9208: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9209: {
9210:   PetscInt M, N, Ny;

9212:   PetscFunctionBegin;
9217:   PetscCall(MatGetSize(A, &M, &N));
9218:   PetscCall(VecGetSize(y, &Ny));
9219:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9220:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9221:   PetscFunctionReturn(PETSC_SUCCESS);
9222: }

9224: /*@
9225:   MatInterpolate - $y = A x$ or $A^T x$ depending on the shape of
9226:   the matrix

9228:   Neighbor-wise Collective

9230:   Input Parameters:
9231: + A - the matrix
9232: - x - the vector to be interpolated

9234:   Output Parameter:
9235: . y - the resulting vector

9237:   Level: intermediate

9239:   Note:
9240:   This allows one to use either the restriction or interpolation (its transpose)
9241:   matrix to do the interpolation

9243: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9244: @*/
9245: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9246: {
9247:   PetscInt M, N, Ny;

9249:   PetscFunctionBegin;
9253:   PetscCall(MatGetSize(A, &M, &N));
9254:   PetscCall(VecGetSize(y, &Ny));
9255:   if (M == Ny) PetscCall(MatMult(A, x, y));
9256:   else PetscCall(MatMultTranspose(A, x, y));
9257:   PetscFunctionReturn(PETSC_SUCCESS);
9258: }

9260: /*@
9261:   MatRestrict - $y = A x$ or $A^T x$

9263:   Neighbor-wise Collective

9265:   Input Parameters:
9266: + A - the matrix
9267: - x - the vector to be restricted

9269:   Output Parameter:
9270: . y - the resulting vector

9272:   Level: intermediate

9274:   Note:
9275:   This allows one to use either the restriction or interpolation (its transpose)
9276:   matrix to do the restriction

9278: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9279: @*/
9280: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9281: {
9282:   PetscInt M, N, Nx;

9284:   PetscFunctionBegin;
9288:   PetscCall(MatGetSize(A, &M, &N));
9289:   PetscCall(VecGetSize(x, &Nx));
9290:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9291:   else PetscCall(MatMult(A, x, y));
9292:   PetscFunctionReturn(PETSC_SUCCESS);
9293: }

9295: /*@
9296:   MatMatInterpolateAdd - $Y = W + A X$ or $W + A^T X$ depending on the shape of `A`

9298:   Neighbor-wise Collective

9300:   Input Parameters:
9301: + A - the matrix
9302: . x - the input dense matrix to be multiplied
9303: - w - the input dense matrix to be added to the result

9305:   Output Parameter:
9306: . y - the output dense matrix

9308:   Level: intermediate

9310:   Note:
9311:   This allows one to use either the restriction or interpolation (its transpose)
9312:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9313:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9315: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9316: @*/
9317: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9318: {
9319:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9320:   PetscBool trans = PETSC_TRUE;
9321:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9323:   PetscFunctionBegin;
9329:   PetscCall(MatGetSize(A, &M, &N));
9330:   PetscCall(MatGetSize(x, &Mx, &Nx));
9331:   if (N == Mx) trans = PETSC_FALSE;
9332:   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);
9333:   Mo = trans ? N : M;
9334:   if (*y) {
9335:     PetscCall(MatGetSize(*y, &My, &Ny));
9336:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9337:     else {
9338:       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);
9339:       PetscCall(MatDestroy(y));
9340:     }
9341:   }

9343:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9344:     PetscBool flg;

9346:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9347:     if (w) {
9348:       PetscInt My, Ny, Mw, Nw;

9350:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9351:       PetscCall(MatGetSize(*y, &My, &Ny));
9352:       PetscCall(MatGetSize(w, &Mw, &Nw));
9353:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9354:     }
9355:     if (!w) {
9356:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9357:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9358:       PetscCall(PetscObjectDereference((PetscObject)w));
9359:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9360:   }
9361:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9362:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9363:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9364:   PetscFunctionReturn(PETSC_SUCCESS);
9365: }

9367: /*@
9368:   MatMatInterpolate - $Y = A X$ or $A^T X$ depending on the shape of `A`

9370:   Neighbor-wise Collective

9372:   Input Parameters:
9373: + A - the matrix
9374: - x - the input dense matrix

9376:   Output Parameter:
9377: . y - the output dense matrix

9379:   Level: intermediate

9381:   Note:
9382:   This allows one to use either the restriction or interpolation (its transpose)
9383:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9384:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9386: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9387: @*/
9388: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9389: {
9390:   PetscFunctionBegin;
9391:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9392:   PetscFunctionReturn(PETSC_SUCCESS);
9393: }

9395: /*@
9396:   MatMatRestrict - $Y = A X$ or $A^T X$ depending on the shape of `A`

9398:   Neighbor-wise Collective

9400:   Input Parameters:
9401: + A - the matrix
9402: - x - the input dense matrix

9404:   Output Parameter:
9405: . y - the output dense matrix

9407:   Level: intermediate

9409:   Note:
9410:   This allows one to use either the restriction or interpolation (its transpose)
9411:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9412:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9414: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9415: @*/
9416: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9417: {
9418:   PetscFunctionBegin;
9419:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9420:   PetscFunctionReturn(PETSC_SUCCESS);
9421: }

9423: /*@
9424:   MatGetNullSpace - retrieves the null space of a matrix that was provided with `MatSetNullSpace()`

9426:   Logically Collective

9428:   Input Parameters:
9429: + mat    - the matrix
9430: - nullsp - the null space object

9432:   Level: developer

9434: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9435: @*/
9436: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9437: {
9438:   PetscFunctionBegin;
9440:   PetscAssertPointer(nullsp, 2);
9441:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9442:   PetscFunctionReturn(PETSC_SUCCESS);
9443: }

9445: /*@
9446:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices that were supplied with `MatSetNullSpace()`,
9447:   `MatSetTransposeNullSpace()`, and `MatSetNearNullSpace()`

9449:   Logically Collective

9451:   Input Parameters:
9452: + n   - the number of matrices
9453: - mat - the array of matrices

9455:   Output Parameters:
9456: . nullsp - an array of null spaces, `NULL` will be inserted for each matrix that does not have a null space, length 3 * `n`

9458:   Level: developer

9460:   Note:
9461:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9463: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9464:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`, `MatNullSpace`
9465: @*/
9466: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9467: {
9468:   PetscFunctionBegin;
9469:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9470:   PetscAssertPointer(mat, 2);
9471:   PetscAssertPointer(nullsp, 3);

9473:   PetscCall(PetscCalloc1(3 * n, nullsp));
9474:   for (PetscInt i = 0; i < n; i++) {
9476:     (*nullsp)[i] = mat[i]->nullsp;
9477:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9478:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9479:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9480:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9481:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9482:   }
9483:   PetscFunctionReturn(PETSC_SUCCESS);
9484: }

9486: /*@
9487:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9489:   Logically Collective

9491:   Input Parameters:
9492: + n      - the number of matrices
9493: . mat    - the array of matrices
9494: - nullsp - an array of null spaces, of length  3 * `n`

9496:   Level: developer

9498:   Notes:
9499:   Call `MatGetNullSpaces()` to create `nullsp`.

9501:   Frees `nullsp`.

9503:   Developer Note:
9504:   The name of this function is confusing. Traditionally in PETSc, a restore operation undoes something that was previously done on an object (or objects) with a get operation.
9505:   This restore routine does something to a new set of objects using the results of a get operation on a previous set of objects. Perhaps this routine
9506:   should have simply been called `MatSetNullSpaces()`

9508: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9509:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`, `MatNullSpace`
9510: @*/
9511: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9512: {
9513:   PetscFunctionBegin;
9514:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9515:   PetscAssertPointer(mat, 2);
9516:   PetscAssertPointer(nullsp, 3);
9517:   PetscAssertPointer(*nullsp, 3);

9519:   for (PetscInt i = 0; i < n; i++) {
9521:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9522:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9523:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9524:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9525:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9526:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9527:   }
9528:   PetscCall(PetscFree(*nullsp));
9529:   PetscFunctionReturn(PETSC_SUCCESS);
9530: }

9532: /*@
9533:   MatSetNullSpace - attaches a null space to a matrix.

9535:   Logically Collective

9537:   Input Parameters:
9538: + mat    - the matrix
9539: - nullsp - the null space object

9541:   Level: advanced

9543:   Notes:
9544:   This null space is used by the `KSP` linear solvers to solve singular systems.

9546:   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`

9548:   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
9549:   to zero but the linear system will still be solved in a least squares sense.

9551:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9552:   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)$.
9553:   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
9554:   $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
9555:   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)$.
9556:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9558:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9559:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9560:   routine also automatically calls `MatSetTransposeNullSpace()`.

9562:   The user should call `MatNullSpaceDestroy()`.

9564: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9565:           `KSPSetPCSide()`, `MatNullSpace`
9566: @*/
9567: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9568: {
9569:   PetscFunctionBegin;
9572:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9573:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9574:   mat->nullsp = nullsp;
9575:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9576:   PetscFunctionReturn(PETSC_SUCCESS);
9577: }

9579: /*@
9580:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix that was set with `MatSetTransposeNullSpace()`

9582:   Logically Collective

9584:   Input Parameters:
9585: + mat    - the matrix
9586: - nullsp - the null space object

9588:   Level: developer

9590: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9591: @*/
9592: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9593: {
9594:   PetscFunctionBegin;
9597:   PetscAssertPointer(nullsp, 2);
9598:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9599:   PetscFunctionReturn(PETSC_SUCCESS);
9600: }

9602: /*@
9603:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9605:   Logically Collective

9607:   Input Parameters:
9608: + mat    - the matrix
9609: - nullsp - the null space object

9611:   Level: advanced

9613:   Notes:
9614:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9616:   See `MatSetNullSpace()`

9618: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9619: @*/
9620: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9621: {
9622:   PetscFunctionBegin;
9625:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9626:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9627:   mat->transnullsp = nullsp;
9628:   PetscFunctionReturn(PETSC_SUCCESS);
9629: }

9631: /*@
9632:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9633:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9635:   Logically Collective

9637:   Input Parameters:
9638: + mat    - the matrix
9639: - nullsp - the null space object

9641:   Level: advanced

9643:   Notes:
9644:   Overwrites any previous near null space that may have been attached

9646:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9648: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9649: @*/
9650: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9651: {
9652:   PetscFunctionBegin;
9656:   MatCheckPreallocated(mat, 1);
9657:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9658:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9659:   mat->nearnullsp = nullsp;
9660:   PetscFunctionReturn(PETSC_SUCCESS);
9661: }

9663: /*@
9664:   MatGetNearNullSpace - Get null space from a matrix that was attached with `MatSetNearNullSpace()`

9666:   Not Collective

9668:   Input Parameter:
9669: . mat - the matrix

9671:   Output Parameter:
9672: . nullsp - the null space object, `NULL` if not set

9674:   Level: advanced

9676: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9677: @*/
9678: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9679: {
9680:   PetscFunctionBegin;
9683:   PetscAssertPointer(nullsp, 2);
9684:   MatCheckPreallocated(mat, 1);
9685:   *nullsp = mat->nearnullsp;
9686:   PetscFunctionReturn(PETSC_SUCCESS);
9687: }

9689: /*@
9690:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9692:   Collective

9694:   Input Parameters:
9695: + mat  - the matrix
9696: . row  - row/column permutation
9697: - info - information on desired factorization process

9699:   Level: developer

9701:   Notes:
9702:   Probably really in-place only when level of fill is zero, otherwise allocates
9703:   new space to store factored matrix and deletes previous memory.

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

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

9712: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9713: @*/
9714: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9715: {
9716:   PetscFunctionBegin;
9720:   PetscAssertPointer(info, 3);
9721:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9722:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9723:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9724:   MatCheckPreallocated(mat, 1);
9725:   PetscUseTypeMethod(mat, iccfactor, row, info);
9726:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9727:   PetscFunctionReturn(PETSC_SUCCESS);
9728: }

9730: /*@
9731:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9732:   ghosted ones.

9734:   Not Collective

9736:   Input Parameters:
9737: + mat  - the matrix
9738: - diag - the diagonal values, including ghost ones

9740:   Level: developer

9742:   Notes:
9743:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9745:   `diag` is a sequential vector that has a length which is the same as the local (ghosted) length of the vector associated with
9746:   the matrix's `ISLocalToGlobalMapping` set with `MatSetLocalToGlobalMapping()`.

9748:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`.

9750: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`, `MatSetLocalToGlobalMapping()`, `ISLocalToGlobalMapping`
9751: @*/
9752: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9753: {
9754:   PetscMPIInt size;

9756:   PetscFunctionBegin;

9761:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9762:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9763:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9764:   if (size == 1) {
9765:     PetscInt n, m;
9766:     PetscCall(VecGetSize(diag, &n));
9767:     PetscCall(MatGetSize(mat, NULL, &m));
9768:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9769:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9770:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9771:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9772:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9773:   PetscFunctionReturn(PETSC_SUCCESS);
9774: }

9776: /*@
9777:   MatGetInertia - Gets the inertia from a factored matrix

9779:   Collective

9781:   Input Parameter:
9782: . mat - the matrix

9784:   Output Parameters:
9785: + nneg  - number of negative eigenvalues
9786: . nzero - number of zero eigenvalues
9787: - npos  - number of positive eigenvalues

9789:   Level: advanced

9791:   Note:
9792:   Matrix must have been factored by `MatCholeskyFactor()`

9794: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9795: @*/
9796: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9797: {
9798:   PetscFunctionBegin;
9801:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9802:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9803:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9804:   PetscFunctionReturn(PETSC_SUCCESS);
9805: }

9807: /*@
9808:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9810:   Neighbor-wise Collective

9812:   Input Parameters:
9813: + mat - the factored matrix obtained with `MatGetFactor()`
9814: - b   - the right-hand-side vectors

9816:   Output Parameter:
9817: . x - the result vectors

9819:   Level: developer

9821:   Note:
9822:   The vectors `b` and `x` cannot be the same. I.e., one cannot
9823:   call `MatSolves`(A,x,x).

9825: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatGetFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9826: @*/
9827: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9828: {
9829:   PetscFunctionBegin;
9832:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9833:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9834:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9836:   MatCheckPreallocated(mat, 1);
9837:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9838:   PetscUseTypeMethod(mat, solves, b, x);
9839:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9840:   PetscFunctionReturn(PETSC_SUCCESS);
9841: }

9843: /*@
9844:   MatIsSymmetric - Test whether a matrix is symmetric

9846:   Collective

9848:   Input Parameters:
9849: + A   - the matrix to test
9850: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9852:   Output Parameter:
9853: . flg - the result

9855:   Level: intermediate

9857:   Notes:
9858:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9860:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9862:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9863:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9864:   have been set then `MatIsSymmetric()` does not need to perform any computations and returns immediately with the result.

9866: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9867:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9868: @*/
9869: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9870: {
9871:   PetscFunctionBegin;
9873:   PetscAssertPointer(flg, 3);
9874:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9875:   else {
9876:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9877:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9878:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9879:   }
9880:   PetscFunctionReturn(PETSC_SUCCESS);
9881: }

9883: /*@
9884:   MatIsHermitian - Test whether a matrix is Hermitian

9886:   Collective

9888:   Input Parameters:
9889: + A   - the matrix to test
9890: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9892:   Output Parameter:
9893: . flg - the result

9895:   Level: intermediate

9897:   Notes:
9898:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9900:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9902:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9903:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9904:   have been set then `MatIsHermitian()` does not need to perform any computations and returns immediately with the result.

9906: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9907:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9908: @*/
9909: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9910: {
9911:   PetscFunctionBegin;
9913:   PetscAssertPointer(flg, 3);
9914:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9915:   else {
9916:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9917:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9918:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9919:   }
9920:   PetscFunctionReturn(PETSC_SUCCESS);
9921: }

9923: /*@
9924:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9926:   Not Collective

9928:   Input Parameter:
9929: . A - the matrix to check

9931:   Output Parameters:
9932: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9933: - flg - the result (only valid if set is `PETSC_TRUE`)

9935:   Level: advanced

9937:   Notes:
9938:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9939:   if you want it explicitly checked

9941:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9942:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9944: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9945: @*/
9946: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9947: {
9948:   PetscFunctionBegin;
9950:   PetscAssertPointer(set, 2);
9951:   PetscAssertPointer(flg, 3);
9952:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9953:     *set = PETSC_TRUE;
9954:     *flg = PetscBool3ToBool(A->symmetric);
9955:   } else *set = PETSC_FALSE;
9956:   PetscFunctionReturn(PETSC_SUCCESS);
9957: }

9959: /*@
9960:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9962:   Not Collective

9964:   Input Parameter:
9965: . A - the matrix to check

9967:   Output Parameters:
9968: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9969: - flg - the result (only valid if set is `PETSC_TRUE`)

9971:   Level: advanced

9973:   Notes:
9974:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9976:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9977:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9979: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9980: @*/
9981: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9982: {
9983:   PetscFunctionBegin;
9985:   PetscAssertPointer(set, 2);
9986:   PetscAssertPointer(flg, 3);
9987:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9988:     *set = PETSC_TRUE;
9989:     *flg = PetscBool3ToBool(A->spd);
9990:   } else *set = PETSC_FALSE;
9991:   PetscFunctionReturn(PETSC_SUCCESS);
9992: }

9994: /*@
9995:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9997:   Not Collective

9999:   Input Parameter:
10000: . A - the matrix to check

10002:   Output Parameters:
10003: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
10004: - flg - the result (only valid if set is `PETSC_TRUE`)

10006:   Level: advanced

10008:   Notes:
10009:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
10010:   if you want it explicitly checked

10012:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
10013:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10015: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
10016: @*/
10017: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
10018: {
10019:   PetscFunctionBegin;
10021:   PetscAssertPointer(set, 2);
10022:   PetscAssertPointer(flg, 3);
10023:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
10024:     *set = PETSC_TRUE;
10025:     *flg = PetscBool3ToBool(A->hermitian);
10026:   } else *set = PETSC_FALSE;
10027:   PetscFunctionReturn(PETSC_SUCCESS);
10028: }

10030: /*@
10031:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

10033:   Collective

10035:   Input Parameter:
10036: . A - the matrix to test

10038:   Output Parameter:
10039: . flg - the result

10041:   Level: intermediate

10043:   Notes:
10044:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

10046:   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
10047:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
10048:   have been set then `MatIsStructurallySymmetric()` does not need to perform any computations and returns immediately with the result.

10050: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
10051: @*/
10052: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
10053: {
10054:   PetscFunctionBegin;
10056:   PetscAssertPointer(flg, 2);
10057:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
10058:   else {
10059:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
10060:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
10061:   }
10062:   PetscFunctionReturn(PETSC_SUCCESS);
10063: }

10065: /*@
10066:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

10068:   Not Collective

10070:   Input Parameter:
10071: . A - the matrix to check

10073:   Output Parameters:
10074: + set - `PETSC_TRUE` if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
10075: - flg - the result (only valid if set is `PETSC_TRUE`)

10077:   Level: advanced

10079:   Notes:
10080:   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
10081:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10083:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

10085: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
10086: @*/
10087: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
10088: {
10089:   PetscFunctionBegin;
10091:   PetscAssertPointer(set, 2);
10092:   PetscAssertPointer(flg, 3);
10093:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
10094:     *set = PETSC_TRUE;
10095:     *flg = PetscBool3ToBool(A->structurally_symmetric);
10096:   } else *set = PETSC_FALSE;
10097:   PetscFunctionReturn(PETSC_SUCCESS);
10098: }

10100: /*@
10101:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10102:   to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10104:   Not Collective

10106:   Input Parameter:
10107: . mat - the matrix

10109:   Output Parameters:
10110: + nstash    - the size of the stash
10111: . reallocs  - the number of additional mallocs incurred.
10112: . bnstash   - the size of the block stash
10113: - breallocs - the number of additional mallocs incurred.in the block stash

10115:   Level: advanced

10117: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10118: @*/
10119: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10120: {
10121:   PetscFunctionBegin;
10122:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10123:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10124:   PetscFunctionReturn(PETSC_SUCCESS);
10125: }

10127: /*@
10128:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10129:   parallel layout, `PetscLayout` for rows and columns

10131:   Collective

10133:   Input Parameter:
10134: . mat - the matrix

10136:   Output Parameters:
10137: + right - (optional) vector that the matrix can be multiplied against
10138: - left  - (optional) vector that the matrix vector product can be stored in

10140:   Options Database Key:
10141: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10143:   Level: advanced

10145:   Notes:
10146:   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()`.

10148:   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`.

10150:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10152:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10153:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10155: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10156: @*/
10157: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10158: {
10159:   PetscFunctionBegin;
10162:   if (mat->ops->getvecs) {
10163:     PetscUseTypeMethod(mat, getvecs, right, left);
10164:   } else {
10165:     if (right) {
10166:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10167:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10168:       PetscCall(VecSetType(*right, mat->defaultvectype));
10169: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10170:       if (mat->boundtocpu && mat->bindingpropagates) {
10171:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10172:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10173:       }
10174: #endif
10175:     }
10176:     if (left) {
10177:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10178:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10179:       PetscCall(VecSetType(*left, mat->defaultvectype));
10180: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10181:       if (mat->boundtocpu && mat->bindingpropagates) {
10182:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10183:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10184:       }
10185: #endif
10186:     }
10187:   }
10188:   PetscFunctionReturn(PETSC_SUCCESS);
10189: }

10191: /*@
10192:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10193:   with default values.

10195:   Not Collective

10197:   Input Parameter:
10198: . info - the `MatFactorInfo` data structure

10200:   Level: developer

10202:   Notes:
10203:   The solvers are generally used through the `KSP` and `PC` objects, for example
10204:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10206:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10208: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10209: @*/
10210: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10211: {
10212:   PetscFunctionBegin;
10213:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10214:   PetscFunctionReturn(PETSC_SUCCESS);
10215: }

10217: /*@
10218:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10220:   Collective

10222:   Input Parameters:
10223: + mat - the factored matrix
10224: - is  - the index set defining the Schur indices (0-based)

10226:   Level: advanced

10228:   Notes:
10229:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10231:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10233:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10235: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10236:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10237: @*/
10238: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10239: {
10240:   PetscErrorCode (*f)(Mat, IS);

10242:   PetscFunctionBegin;
10247:   PetscCheckSameComm(mat, 1, is, 2);
10248:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10249:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10250:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10251:   PetscCall((*f)(mat, is));
10252:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10253:   PetscFunctionReturn(PETSC_SUCCESS);
10254: }

10256: /*@
10257:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10259:   Logically Collective

10261:   Input Parameters:
10262: + F      - the factored matrix obtained by calling `MatGetFactor()`
10263: . S      - location where to return the Schur complement, can be `NULL`
10264: - status - the status of the Schur complement matrix, can be `NULL`

10266:   Level: advanced

10268:   Notes:
10269:   You must call `MatFactorSetSchurIS()` before calling this routine.

10271:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10273:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10274:   The caller must destroy the object when it is no longer needed.
10275:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10277:   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)

10279:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10281:   Developer Note:
10282:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10283:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10285: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10286: @*/
10287: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10288: {
10289:   PetscFunctionBegin;
10291:   if (S) PetscAssertPointer(S, 2);
10292:   if (status) PetscAssertPointer(status, 3);
10293:   if (S) {
10294:     PetscErrorCode (*f)(Mat, Mat *);

10296:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10297:     if (f) PetscCall((*f)(F, S));
10298:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10299:   }
10300:   if (status) *status = F->schur_status;
10301:   PetscFunctionReturn(PETSC_SUCCESS);
10302: }

10304: /*@
10305:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10307:   Logically Collective

10309:   Input Parameters:
10310: + F      - the factored matrix obtained by calling `MatGetFactor()`
10311: . S      - location where to return the Schur complement, can be `NULL`
10312: - status - the status of the Schur complement matrix, can be `NULL`

10314:   Level: advanced

10316:   Notes:
10317:   You must call `MatFactorSetSchurIS()` before calling this routine.

10319:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10321:   The routine returns a the Schur Complement stored within the data structures of the solver.

10323:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10325:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10327:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10329:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10331: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10332: @*/
10333: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10334: {
10335:   PetscFunctionBegin;
10337:   if (S) {
10338:     PetscAssertPointer(S, 2);
10339:     *S = F->schur;
10340:   }
10341:   if (status) {
10342:     PetscAssertPointer(status, 3);
10343:     *status = F->schur_status;
10344:   }
10345:   PetscFunctionReturn(PETSC_SUCCESS);
10346: }

10348: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10349: {
10350:   Mat S = F->schur;

10352:   PetscFunctionBegin;
10353:   switch (F->schur_status) {
10354:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10355:   case MAT_FACTOR_SCHUR_INVERTED:
10356:     if (S) {
10357:       S->ops->solve             = NULL;
10358:       S->ops->matsolve          = NULL;
10359:       S->ops->solvetranspose    = NULL;
10360:       S->ops->matsolvetranspose = NULL;
10361:       S->ops->solveadd          = NULL;
10362:       S->ops->solvetransposeadd = NULL;
10363:       S->factortype             = MAT_FACTOR_NONE;
10364:       PetscCall(PetscFree(S->solvertype));
10365:     }
10366:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10367:     break;
10368:   default:
10369:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10370:   }
10371:   PetscFunctionReturn(PETSC_SUCCESS);
10372: }

10374: /*@
10375:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10377:   Logically Collective

10379:   Input Parameters:
10380: + F      - the factored matrix obtained by calling `MatGetFactor()`
10381: . S      - location where the Schur complement is stored
10382: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10384:   Level: advanced

10386: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10387: @*/
10388: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10389: {
10390:   PetscFunctionBegin;
10392:   if (S) {
10394:     *S = NULL;
10395:   }
10396:   F->schur_status = status;
10397:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10398:   PetscFunctionReturn(PETSC_SUCCESS);
10399: }

10401: /*@
10402:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10404:   Logically Collective

10406:   Input Parameters:
10407: + F   - the factored matrix obtained by calling `MatGetFactor()`
10408: . rhs - location where the right-hand side of the Schur complement system is stored
10409: - sol - location where the solution of the Schur complement system has to be returned

10411:   Level: advanced

10413:   Notes:
10414:   The sizes of the vectors should match the size of the Schur complement

10416:   Must be called after `MatFactorSetSchurIS()`

10418: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10419: @*/
10420: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10421: {
10422:   PetscFunctionBegin;
10429:   PetscCheckSameComm(F, 1, rhs, 2);
10430:   PetscCheckSameComm(F, 1, sol, 3);
10431:   PetscCall(MatFactorFactorizeSchurComplement(F));
10432:   switch (F->schur_status) {
10433:   case MAT_FACTOR_SCHUR_FACTORED:
10434:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10435:     break;
10436:   case MAT_FACTOR_SCHUR_INVERTED:
10437:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10438:     break;
10439:   default:
10440:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10441:   }
10442:   PetscFunctionReturn(PETSC_SUCCESS);
10443: }

10445: /*@
10446:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10448:   Logically Collective

10450:   Input Parameters:
10451: + F   - the factored matrix obtained by calling `MatGetFactor()`
10452: . rhs - location where the right-hand side of the Schur complement system is stored
10453: - sol - location where the solution of the Schur complement system has to be returned

10455:   Level: advanced

10457:   Notes:
10458:   The sizes of the vectors should match the size of the Schur complement

10460:   Must be called after `MatFactorSetSchurIS()`

10462: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10463: @*/
10464: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10465: {
10466:   PetscFunctionBegin;
10473:   PetscCheckSameComm(F, 1, rhs, 2);
10474:   PetscCheckSameComm(F, 1, sol, 3);
10475:   PetscCall(MatFactorFactorizeSchurComplement(F));
10476:   switch (F->schur_status) {
10477:   case MAT_FACTOR_SCHUR_FACTORED:
10478:     PetscCall(MatSolve(F->schur, rhs, sol));
10479:     break;
10480:   case MAT_FACTOR_SCHUR_INVERTED:
10481:     PetscCall(MatMult(F->schur, rhs, sol));
10482:     break;
10483:   default:
10484:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10485:   }
10486:   PetscFunctionReturn(PETSC_SUCCESS);
10487: }

10489: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10490: #if PetscDefined(HAVE_CUDA)
10491: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10492: #endif

10494: /* Schur status updated in the interface */
10495: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10496: {
10497:   Mat S = F->schur;

10499:   PetscFunctionBegin;
10500:   if (S) {
10501:     PetscMPIInt size;
10502:     PetscBool   isdense, isdensecuda;

10504:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10505:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10506:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10507:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10508:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10509:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10510:     if (isdense) {
10511:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10512:     } else if (isdensecuda) {
10513: #if PetscDefined(HAVE_CUDA)
10514:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10515: #endif
10516:     }
10517:     // HIP??????????????
10518:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10519:   }
10520:   PetscFunctionReturn(PETSC_SUCCESS);
10521: }

10523: /*@
10524:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10526:   Logically Collective

10528:   Input Parameter:
10529: . F - the factored matrix obtained by calling `MatGetFactor()`

10531:   Level: advanced

10533:   Notes:
10534:   Must be called after `MatFactorSetSchurIS()`.

10536:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10538: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10539: @*/
10540: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10541: {
10542:   PetscFunctionBegin;
10545:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10546:   PetscCall(MatFactorFactorizeSchurComplement(F));
10547:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10548:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10549:   PetscFunctionReturn(PETSC_SUCCESS);
10550: }

10552: /*@
10553:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10555:   Logically Collective

10557:   Input Parameter:
10558: . F - the factored matrix obtained by calling `MatGetFactor()`

10560:   Level: advanced

10562:   Note:
10563:   Must be called after `MatFactorSetSchurIS()`

10565: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10566: @*/
10567: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10568: {
10569:   MatFactorInfo info;

10571:   PetscFunctionBegin;
10574:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10575:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10576:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10577:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10578:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10579:   } else {
10580:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10581:   }
10582:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10583:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10584:   PetscFunctionReturn(PETSC_SUCCESS);
10585: }

10587: /*@
10588:   MatPtAP - Creates the matrix product $C = P^T A P$

10590:   Neighbor-wise Collective

10592:   Input Parameters:
10593: + A     - the matrix
10594: . P     - the projection matrix
10595: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10596: - 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
10597:           if the result is a dense matrix this is irrelevant

10599:   Output Parameter:
10600: . C - the product matrix

10602:   Level: intermediate

10604:   Notes:
10605:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10607:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10608:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10610:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10612:   Developer Note:
10613:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10615: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10616: @*/
10617: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10618: {
10619:   PetscFunctionBegin;
10620:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10621:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10623:   if (scall == MAT_INITIAL_MATRIX) {
10624:     PetscCall(MatProductCreate(A, P, NULL, C));
10625:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10626:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10627:     PetscCall(MatProductSetFill(*C, fill));

10629:     (*C)->product->api_user = PETSC_TRUE;
10630:     PetscCall(MatProductSetFromOptions(*C));
10631:     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);
10632:     PetscCall(MatProductSymbolic(*C));
10633:   } else { /* scall == MAT_REUSE_MATRIX */
10634:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10635:   }

10637:   PetscCall(MatProductNumeric(*C));
10638:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10639:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10640:     (*C)->spd = A->spd;
10641:   }
10642:   PetscFunctionReturn(PETSC_SUCCESS);
10643: }

10645: /*@
10646:   MatRARt - Creates the matrix product $C = R A R^T$

10648:   Neighbor-wise Collective

10650:   Input Parameters:
10651: + A     - the matrix
10652: . R     - the projection matrix
10653: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10654: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10655:           if the result is a dense matrix this is irrelevant

10657:   Output Parameter:
10658: . C - the product matrix

10660:   Level: intermediate

10662:   Notes:
10663:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10665:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10666:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10668:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10669:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10670:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10671:   We recommend using `MatPtAP()` when possible.

10673:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10675: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10676: @*/
10677: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10678: {
10679:   PetscFunctionBegin;
10680:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10681:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10683:   if (scall == MAT_INITIAL_MATRIX) {
10684:     PetscCall(MatProductCreate(A, R, NULL, C));
10685:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10686:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10687:     PetscCall(MatProductSetFill(*C, fill));

10689:     (*C)->product->api_user = PETSC_TRUE;
10690:     PetscCall(MatProductSetFromOptions(*C));
10691:     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);
10692:     PetscCall(MatProductSymbolic(*C));
10693:   } else { /* scall == MAT_REUSE_MATRIX */
10694:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10695:   }

10697:   PetscCall(MatProductNumeric(*C));
10698:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10699:   PetscFunctionReturn(PETSC_SUCCESS);
10700: }

10702: /* MatProductComputeWithMat_Private - Computes D = A * B or D = A^T * B into an existing matrix D, keeping the product on a dense D

10704:    Collective

10706:    Input Parameters:
10707: +  A     - the left matrix
10708: .  B     - the right matrix
10709: .  ptype - MATPRODUCT_AB or MATPRODUCT_AtB
10710: -  D     - the result, of the size of the product

10712:    Level: developer

10714:    Notes:
10715:    For a dense D, this routine keeps the product on D between calls, so only the first call runs the symbolic phase. The product is created
10716:    again only when ptype, A, or the nonzero pattern of A changes; a different B of the same size and type reuses it. The kept product holds
10717:    references to A and B until MatProductClear() is called on D or D is destroyed. In contrast, MatMatMult() with MAT_REUSE_MATRIX creates the
10718:    product and destroys it again on every call into a dense D that does not already have a product.

10720:    For any other D, which must already have a product, this calls MatMatMult() or MatTransposeMatMult() with MAT_REUSE_MATRIX.

10722:    Developer Note:
10723:    The nonzero state of A is compared without a reduction, since the parallel AIJ and BAIJ types make it the same on all processes during
10724:    assembly.

10726: .seealso: `MatMatMult()`, `MatTransposeMatMult()`, `MatProductReplaceMats()`, `PCMGMatResidualDefault()`
10727: */
10728: PetscErrorCode MatProductComputeWithMat_Private(Mat A, Mat B, MatProductType ptype, Mat D)
10729: {
10730:   Mat_Product     *product = D->product;
10731:   PetscObjectState state;
10732:   PetscBool        flg;

10734:   PetscFunctionBegin;
10735:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)D, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10736:   if (!flg) { /* only a dense result can be given without a product, MatMatMult() and MatTransposeMatMult() reuse the product of any other */
10737:     if (ptype == MATPRODUCT_AB) PetscCall(MatMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10738:     else PetscCall(MatTransposeMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10739:     PetscFunctionReturn(PETSC_SUCCESS);
10740:   }
10741:   PetscCall(MatGetNonzeroState(A, &state));
10742:   if (product == NULL || product->type != ptype || product->A != A || product->Anonzerostate != state) {
10743:     PetscCall(PetscInfo(D, "Setting up the %s product into the supplied dense matrix\n", MatProductTypes[ptype]));
10744:     PetscCall(MatProductCreateWithMat(A, B, NULL, D));
10745:     D->product->api_user = PETSC_TRUE;
10746:     PetscCall(MatProductSetType(D, ptype));
10747:     PetscCall(MatProductSetFromOptions(D));
10748:     PetscCall(MatProductSymbolic(D));
10749:   } else {
10750:     PetscCall(PetscInfo(D, "Reusing the %s product attached to the supplied dense matrix\n", MatProductTypes[ptype]));
10751:     if (product->B != B) PetscCall(MatProductReplaceMats(NULL, B, NULL, D));
10752:   }
10753:   PetscCall(MatProductNumeric(D));
10754:   PetscFunctionReturn(PETSC_SUCCESS);
10755: }

10757: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10758: {
10759:   PetscBool flg = PETSC_TRUE;

10761:   PetscFunctionBegin;
10762:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10763:   if (scall == MAT_INITIAL_MATRIX) {
10764:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10765:     PetscCall(MatProductCreate(A, B, NULL, C));
10766:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10767:     PetscCall(MatProductSetFill(*C, fill));
10768:   } else { /* scall == MAT_REUSE_MATRIX */
10769:     Mat_Product *product = (*C)->product;

10771:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10772:     if (flg && product && product->type != ptype) {
10773:       PetscCall(MatProductClear(*C));
10774:       product = NULL;
10775:     }
10776:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10777:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10778:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10779:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10780:       product        = (*C)->product;
10781:       product->fill  = fill;
10782:       product->clear = PETSC_TRUE;
10783:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10784:       flg = PETSC_FALSE;
10785:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10786:     }
10787:   }
10788:   if (flg) {
10789:     (*C)->product->api_user = PETSC_TRUE;
10790:     PetscCall(MatProductSetType(*C, ptype));
10791:     PetscCall(MatProductSetFromOptions(*C));
10792:     PetscCall(MatProductSymbolic(*C));
10793:   }
10794:   PetscCall(MatProductNumeric(*C));
10795:   PetscFunctionReturn(PETSC_SUCCESS);
10796: }

10798: /*@
10799:   MatMatMult - Performs matrix-matrix multiplication $C=A B$.

10801:   Neighbor-wise Collective

10803:   Input Parameters:
10804: + A     - the left matrix
10805: . B     - the right matrix
10806: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10807: - 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
10808:           if the result is a dense matrix this is irrelevant

10810:   Output Parameter:
10811: . C - the product matrix

10813:   Notes:
10814:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10816:   `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
10817:   call to this function with `MAT_INITIAL_MATRIX`.

10819:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10821:   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`,
10822:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10824:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10826:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10827:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10829:   Example of Usage:
10830: .vb
10831:      MatProductCreate(A,B,NULL,&C);
10832:      MatProductSetType(C,MATPRODUCT_AB);
10833:      MatProductSymbolic(C);
10834:      MatProductNumeric(C); // compute C=A * B
10835:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10836:      MatProductNumeric(C);
10837:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10838:      MatProductNumeric(C);
10839: .ve

10841:   Level: intermediate

10843: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10844: @*/
10845: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10846: {
10847:   PetscFunctionBegin;
10848:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10849:   PetscFunctionReturn(PETSC_SUCCESS);
10850: }

10852: /*@
10853:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A B^T$.

10855:   Neighbor-wise Collective

10857:   Input Parameters:
10858: + A     - the left matrix
10859: . B     - the right matrix
10860: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10861: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10863:   Output Parameter:
10864: . C - the product matrix

10866:   Options Database Key:
10867: . -matmattransmult_mpidense_mpidense_via (allgatherv|cyclic|backend) - Choose the algorithm for `MATMPIDENSE`. The default
10868:               `allgatherv` replicates the transpose of `B` in O(log P) communication steps. The `cyclic` algorithm stores
10869:               one portion of `B` at a time and takes O(P) steps. With matching CUDA or HIP matrices, `backend` gathers
10870:               `B` through `PetscSF` and computes the local product on the device.

10872:   Level: intermediate

10874:   Notes:
10875:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10877:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10879:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10880:   actually needed.

10882:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10883:   and for pairs of `MATMPIDENSE` matrices.

10885:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10886:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10888:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10890: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10891: @*/
10892: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10893: {
10894:   PetscFunctionBegin;
10895:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10896:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10897:   PetscFunctionReturn(PETSC_SUCCESS);
10898: }

10900: /*@
10901:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T B$.

10903:   Neighbor-wise Collective

10905:   Input Parameters:
10906: + A     - the left matrix
10907: . B     - the right matrix
10908: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10909: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10911:   Output Parameter:
10912: . C - the product matrix

10914:   Options Database Key:
10915: . -mattransmatmult_mpidense_mpidense_via (default|backend) - For `MATMPIDENSE`, use `backend` to reduce local products through `PetscSF` in their native memory.

10917:   Level: intermediate

10919:   Notes:
10920:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10922:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10924:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10925:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10927:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10928:   actually needed.

10930:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10931:   which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.

10933:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10935: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10936: @*/
10937: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10938: {
10939:   PetscFunctionBegin;
10940:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10941:   PetscFunctionReturn(PETSC_SUCCESS);
10942: }

10944: /*@
10945:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10947:   Neighbor-wise Collective

10949:   Input Parameters:
10950: + A     - the left matrix
10951: . B     - the middle matrix
10952: . C     - the right matrix
10953: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10954: - 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
10955:           if the result is a dense matrix this is irrelevant

10957:   Output Parameter:
10958: . D - the product matrix

10960:   Level: intermediate

10962:   Notes:
10963:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10965:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10967:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10968:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10970:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10971:   actually needed.

10973:   If you have many matrices with the same non-zero structure to multiply, you
10974:   should use `MAT_REUSE_MATRIX` in all calls but the first

10976:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10978: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10979: @*/
10980: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10981: {
10982:   PetscFunctionBegin;
10983:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10984:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10986:   if (scall == MAT_INITIAL_MATRIX) {
10987:     PetscCall(MatProductCreate(A, B, C, D));
10988:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10989:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10990:     PetscCall(MatProductSetFill(*D, fill));

10992:     (*D)->product->api_user = PETSC_TRUE;
10993:     PetscCall(MatProductSetFromOptions(*D));
10994:     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,
10995:                ((PetscObject)C)->type_name);
10996:     PetscCall(MatProductSymbolic(*D));
10997:   } else { /* user may change input matrices when REUSE */
10998:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10999:   }
11000:   PetscCall(MatProductNumeric(*D));
11001:   PetscFunctionReturn(PETSC_SUCCESS);
11002: }

11004: /*@
11005:   MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.

11007:   Collective

11009:   Input Parameters:
11010: + mat      - the matrix
11011: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
11012: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
11013: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11015:   Output Parameter:
11016: . matredundant - redundant matrix

11018:   Level: advanced

11020:   Notes:
11021:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
11022:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

11024:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
11025:   calling it.

11027:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

11029: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
11030: @*/
11031: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
11032: {
11033:   MPI_Comm       comm;
11034:   PetscMPIInt    size;
11035:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
11036:   Mat_Redundant *redund     = NULL;
11037:   PetscSubcomm   psubcomm   = NULL;
11038:   MPI_Comm       subcomm_in = subcomm;
11039:   Mat           *matseq;
11040:   IS             isrow, iscol;
11041:   PetscBool      newsubcomm = PETSC_FALSE;

11043:   PetscFunctionBegin;
11045:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
11046:     PetscAssertPointer(*matredundant, 5);
11048:   }

11050:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11051:   if (size == 1 || nsubcomm == 1) {
11052:     if (reuse == MAT_INITIAL_MATRIX) {
11053:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
11054:     } else {
11055:       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");
11056:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
11057:     }
11058:     PetscFunctionReturn(PETSC_SUCCESS);
11059:   }

11061:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11062:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11063:   MatCheckPreallocated(mat, 1);

11065:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
11066:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
11067:     /* create psubcomm, then get subcomm */
11068:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11069:     PetscCallMPI(MPI_Comm_size(comm, &size));
11070:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

11072:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
11073:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
11074:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
11075:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
11076:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
11077:     newsubcomm = PETSC_TRUE;
11078:     PetscCall(PetscSubcommDestroy(&psubcomm));
11079:   }

11081:   /* get isrow, iscol and a local sequential matrix matseq[0] */
11082:   if (reuse == MAT_INITIAL_MATRIX) {
11083:     mloc_sub = PETSC_DECIDE;
11084:     nloc_sub = PETSC_DECIDE;
11085:     if (bs < 1) {
11086:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
11087:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
11088:     } else {
11089:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
11090:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
11091:     }
11092:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
11093:     rstart = rend - mloc_sub;
11094:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
11095:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
11096:     PetscCall(ISSetIdentity(iscol));
11097:   } else { /* reuse == MAT_REUSE_MATRIX */
11098:     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");
11099:     /* retrieve subcomm */
11100:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
11101:     redund = (*matredundant)->redundant;
11102:     isrow  = redund->isrow;
11103:     iscol  = redund->iscol;
11104:     matseq = redund->matseq;
11105:   }
11106:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

11108:   /* get matredundant over subcomm */
11109:   if (reuse == MAT_INITIAL_MATRIX) {
11110:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

11112:     /* create a supporting struct and attach it to C for reuse */
11113:     PetscCall(PetscNew(&redund));
11114:     (*matredundant)->redundant = redund;
11115:     redund->isrow              = isrow;
11116:     redund->iscol              = iscol;
11117:     redund->matseq             = matseq;
11118:     if (newsubcomm) {
11119:       redund->subcomm = subcomm;
11120:     } else {
11121:       redund->subcomm = MPI_COMM_NULL;
11122:     }
11123:   } else {
11124:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
11125:   }
11126: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
11127:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
11128:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
11129:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
11130:   }
11131: #endif
11132:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
11133:   PetscFunctionReturn(PETSC_SUCCESS);
11134: }

11136: /*@
11137:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
11138:   a given `Mat`. Each submatrix can span multiple procs.

11140:   Collective

11142:   Input Parameters:
11143: + mat     - the matrix
11144: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
11145: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11147:   Output Parameter:
11148: . subMat - parallel sub-matrices each spanning a given `subcomm`

11150:   Level: advanced

11152:   Notes:
11153:   The submatrix partition across processes is dictated by `subComm` a
11154:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
11155:   is not restricted to be grouped with consecutive original MPI processes.

11157:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11158:   map directly to the layout of the original matrix [wrt the local
11159:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
11160:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11161:   the `subMat`. However the offDiagMat looses some columns - and this is
11162:   reconstructed with `MatSetValues()`

11164:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11166: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11167: @*/
11168: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11169: {
11170:   PetscMPIInt commsize, subCommSize;

11172:   PetscFunctionBegin;
11173:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11174:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11175:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11177:   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");
11178:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11179:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11180:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11181:   PetscFunctionReturn(PETSC_SUCCESS);
11182: }

11184: /*@
11185:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11187:   Not Collective

11189:   Input Parameters:
11190: + mat   - matrix to extract local submatrix from
11191: . isrow - local row indices for submatrix
11192: - iscol - local column indices for submatrix

11194:   Output Parameter:
11195: . submat - the submatrix

11197:   Level: intermediate

11199:   Notes:
11200:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11202:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11203:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11205:   `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11206:   `MatSetValuesBlockedLocal()` will also be implemented.

11208:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11209:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11211: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11212: @*/
11213: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11214: {
11215:   PetscFunctionBegin;
11219:   PetscCheckSameComm(isrow, 2, iscol, 3);
11220:   PetscAssertPointer(submat, 4);
11221:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11223:   if (mat->ops->getlocalsubmatrix) {
11224:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11225:   } else {
11226:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11227:   }
11228:   (*submat)->assembled = mat->assembled;
11229:   PetscFunctionReturn(PETSC_SUCCESS);
11230: }

11232: /*@
11233:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11235:   Not Collective

11237:   Input Parameters:
11238: + mat    - matrix to extract local submatrix from
11239: . isrow  - local row indices for submatrix
11240: . iscol  - local column indices for submatrix
11241: - submat - the submatrix

11243:   Level: intermediate

11245: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11246: @*/
11247: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11248: {
11249:   PetscFunctionBegin;
11253:   PetscCheckSameComm(isrow, 2, iscol, 3);
11254:   PetscAssertPointer(submat, 4);

11257:   if (mat->ops->restorelocalsubmatrix) {
11258:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11259:   } else {
11260:     PetscCall(MatDestroy(submat));
11261:   }
11262:   *submat = NULL;
11263:   PetscFunctionReturn(PETSC_SUCCESS);
11264: }

11266: /*@
11267:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11269:   Collective

11271:   Input Parameter:
11272: . mat - the matrix

11274:   Output Parameter:
11275: . is - if any rows have zero diagonals this contains the list of them

11277:   Level: developer

11279: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11280: @*/
11281: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11282: {
11283:   PetscFunctionBegin;
11286:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11287:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11289:   if (!mat->ops->findzerodiagonals) {
11290:     Vec                diag;
11291:     const PetscScalar *a;
11292:     PetscInt          *rows;
11293:     PetscInt           rStart, rEnd, r, nrow = 0;

11295:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11296:     PetscCall(MatGetDiagonal(mat, diag));
11297:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11298:     PetscCall(VecGetArrayRead(diag, &a));
11299:     for (r = 0; r < rEnd - rStart; ++r)
11300:       if (a[r] == 0.0) ++nrow;
11301:     PetscCall(PetscMalloc1(nrow, &rows));
11302:     nrow = 0;
11303:     for (r = 0; r < rEnd - rStart; ++r)
11304:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11305:     PetscCall(VecRestoreArrayRead(diag, &a));
11306:     PetscCall(VecDestroy(&diag));
11307:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11308:   } else {
11309:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11310:   }
11311:   PetscFunctionReturn(PETSC_SUCCESS);
11312: }

11314: /*@
11315:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11317:   Collective

11319:   Input Parameter:
11320: . mat - the matrix

11322:   Output Parameter:
11323: . is - contains the list of rows with off block diagonal entries

11325:   Level: developer

11327: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11328: @*/
11329: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11330: {
11331:   PetscFunctionBegin;
11334:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11335:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11337:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11338:   PetscFunctionReturn(PETSC_SUCCESS);
11339: }

11341: /*@
11342:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11344:   Collective; No Fortran Support

11346:   Input Parameter:
11347: . mat - the matrix

11349:   Output Parameter:
11350: . values - the block inverses in column major order (FORTRAN-like)

11352:   Level: advanced

11354:   Notes:
11355:   The size of the blocks is determined by the block size of the matrix.

11357:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11359:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11361: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11362: @*/
11363: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11364: {
11365:   PetscFunctionBegin;
11367:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11368:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11369:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11370:   PetscFunctionReturn(PETSC_SUCCESS);
11371: }

11373: /*@
11374:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11376:   Collective; No Fortran Support

11378:   Input Parameters:
11379: + mat     - the matrix
11380: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11381: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11383:   Output Parameter:
11384: . values - the block inverses in column major order (FORTRAN-like)

11386:   Level: advanced

11388:   Notes:
11389:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11391:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11393: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11394: @*/
11395: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11396: {
11397:   PetscFunctionBegin;
11399:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11400:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11401:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11402:   PetscFunctionReturn(PETSC_SUCCESS);
11403: }

11405: /*@
11406:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11408:   Collective

11410:   Input Parameters:
11411: + A - the matrix
11412: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.

11414:   Level: advanced

11416:   Note:
11417:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11419: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11420: @*/
11421: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11422: {
11423:   const PetscScalar *vals;
11424:   PetscInt          *dnnz;
11425:   PetscInt           m, rstart, rend, bs, i, j;
11426:   const PetscBool    nooffprocentries = C->nooffprocentries;

11428:   PetscFunctionBegin;
11429:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11430:   PetscCall(MatGetBlockSize(A, &bs));
11431:   PetscCall(MatGetLocalSize(A, &m, NULL));
11432:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11433:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11434:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11435:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11436:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11437:   PetscCall(PetscFree(dnnz));
11438:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11439:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11440:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11441:   C->nooffprocentries = PETSC_TRUE;
11442:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11443:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11444:   C->nooffprocentries = nooffprocentries;
11445:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11446:   PetscFunctionReturn(PETSC_SUCCESS);
11447: }

11449: /*@
11450:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A B^T$ that was created
11451:   via `MatTransposeColoringCreate()`.

11453:   Collective

11455:   Input Parameter:
11456: . c - coloring context

11458:   Level: intermediate

11460: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11461: @*/
11462: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11463: {
11464:   MatTransposeColoring matcolor = *c;

11466:   PetscFunctionBegin;
11467:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11468:   if (--((PetscObject)matcolor)->refct > 0) {
11469:     matcolor = NULL;
11470:     PetscFunctionReturn(PETSC_SUCCESS);
11471:   }

11473:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11474:   PetscCall(PetscFree(matcolor->rows));
11475:   PetscCall(PetscFree(matcolor->den2sp));
11476:   PetscCall(PetscFree(matcolor->colorforcol));
11477:   PetscCall(PetscFree(matcolor->columns));
11478:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11479:   PetscCall(PetscHeaderDestroy(c));
11480:   PetscFunctionReturn(PETSC_SUCCESS);
11481: }

11483: /*@
11484:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A B^T$ for which
11485:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11486:   `MatTransposeColoring` to sparse `B`.

11488:   Collective

11490:   Input Parameters:
11491: + coloring - coloring context created with `MatTransposeColoringCreate()`
11492: - B        - sparse matrix

11494:   Output Parameter:
11495: . Btdense - dense matrix $B^T$

11497:   Level: developer

11499:   Note:
11500:   These are used internally for some implementations of `MatRARt()`

11502: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11503: @*/
11504: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11505: {
11506:   PetscFunctionBegin;

11511:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11512:   PetscFunctionReturn(PETSC_SUCCESS);
11513: }

11515: /*@
11516:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A B^T$ for which
11517:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A B^T_{dense}$
11518:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11519:   $C_{sp}$ from $C_{den}$.

11521:   Collective

11523:   Input Parameters:
11524: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11525: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11527:   Output Parameter:
11528: . Csp - sparse matrix

11530:   Level: developer

11532:   Note:
11533:   These are used internally for some implementations of `MatRARt()`

11535: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11536: @*/
11537: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11538: {
11539:   PetscFunctionBegin;

11544:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11545:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11546:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11547:   PetscFunctionReturn(PETSC_SUCCESS);
11548: }

11550: /*@
11551:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A B^T$.

11553:   Collective

11555:   Input Parameters:
11556: + mat        - the matrix product C
11557: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11559:   Output Parameter:
11560: . color - the new coloring context

11562:   Level: intermediate

11564: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11565:           `MatTransColoringApplyDenToSp()`
11566: @*/
11567: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11568: {
11569:   MatTransposeColoring c;
11570:   MPI_Comm             comm;

11572:   PetscFunctionBegin;
11573:   PetscAssertPointer(color, 3);

11575:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11576:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11577:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11578:   c->ctype = iscoloring->ctype;
11579:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11580:   *color = c;
11581:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11582:   PetscFunctionReturn(PETSC_SUCCESS);
11583: }

11585: /*@
11586:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11587:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11589:   Not Collective

11591:   Input Parameter:
11592: . mat - the matrix

11594:   Output Parameter:
11595: . state - the current state

11597:   Level: intermediate

11599:   Notes:
11600:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11601:   different matrices

11603:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11605:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11607: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11608: @*/
11609: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11610: {
11611:   PetscFunctionBegin;
11613:   *state = mat->nonzerostate;
11614:   PetscFunctionReturn(PETSC_SUCCESS);
11615: }

11617: /*@
11618:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11619:   matrices from each process

11621:   Collective

11623:   Input Parameters:
11624: + comm   - the communicators the parallel matrix will live on
11625: . seqmat - the input sequential matrices
11626: . n      - number of local columns (or `PETSC_DECIDE`)
11627: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11629:   Output Parameter:
11630: . mpimat - the parallel matrix generated

11632:   Level: developer

11634:   Note:
11635:   The number of columns of the matrix in EACH process MUST be the same.

11637: .seealso: [](ch_matrices), `Mat`
11638: @*/
11639: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11640: {
11641:   PetscMPIInt size;

11643:   PetscFunctionBegin;
11644:   PetscCallMPI(MPI_Comm_size(comm, &size));
11645:   if (size == 1) {
11646:     if (reuse == MAT_INITIAL_MATRIX) {
11647:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11648:     } else {
11649:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11650:     }
11651:     PetscFunctionReturn(PETSC_SUCCESS);
11652:   }

11654:   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");

11656:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11657:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11658:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11659:   PetscFunctionReturn(PETSC_SUCCESS);
11660: }

11662: /*@
11663:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11665:   Collective

11667:   Input Parameters:
11668: + A - the matrix to create subdomains from
11669: - N - requested number of subdomains

11671:   Output Parameters:
11672: + n   - number of subdomains resulting on this MPI process
11673: - iss - `IS` list with indices of subdomains on this MPI process

11675:   Level: advanced

11677:   Note:
11678:   The number of subdomains must be smaller than the communicator size

11680: .seealso: [](ch_matrices), `Mat`, `IS`
11681: @*/
11682: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11683: {
11684:   MPI_Comm    comm, subcomm;
11685:   PetscMPIInt size, rank, color;
11686:   PetscInt    rstart, rend, k;

11688:   PetscFunctionBegin;
11689:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11690:   PetscCallMPI(MPI_Comm_size(comm, &size));
11691:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11692:   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);
11693:   *n    = 1;
11694:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11695:   color = rank / k;
11696:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11697:   PetscCall(PetscMalloc1(1, iss));
11698:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11699:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11700:   PetscCallMPI(MPI_Comm_free(&subcomm));
11701:   PetscFunctionReturn(PETSC_SUCCESS);
11702: }

11704: /*@
11705:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11707:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11708:   If they are not the same, uses `MatMatMatMult()`.

11710:   Once the coarse grid problem is constructed, correct for interpolation operators
11711:   that are not of full rank, which can legitimately happen in the case of non-nested
11712:   geometric multigrid.

11714:   Input Parameters:
11715: + restrct     - restriction operator
11716: . dA          - fine grid matrix
11717: . interpolate - interpolation operator
11718: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11719: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11721:   Output Parameter:
11722: . A - the Galerkin coarse matrix

11724:   Options Database Key:
11725: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11727:   Level: developer

11729:   Note:
11730:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11732: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11733: @*/
11734: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11735: {
11736:   IS  zerorows;
11737:   Vec diag;

11739:   PetscFunctionBegin;
11740:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11741:   /* Construct the coarse grid matrix */
11742:   if (interpolate == restrct) {
11743:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11744:   } else {
11745:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11746:   }

11748:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11749:      This can legitimately happen in the case of non-nested geometric multigrid.
11750:      In that event, we set the rows of the matrix to the rows of the identity,
11751:      ignoring the equations (as the RHS will also be zero). */

11753:   PetscCall(MatFindZeroRows(*A, &zerorows));

11755:   if (zerorows != NULL) { /* if there are any zero rows */
11756:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11757:     PetscCall(MatGetDiagonal(*A, diag));
11758:     PetscCall(VecISSet(diag, zerorows, 1.0));
11759:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11760:     PetscCall(VecDestroy(&diag));
11761:     PetscCall(ISDestroy(&zerorows));
11762:   }
11763:   PetscFunctionReturn(PETSC_SUCCESS);
11764: }

11766: /*@
11767:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11769:   Logically Collective

11771:   Input Parameters:
11772: + mat - the matrix
11773: . op  - the name of the operation
11774: - f   - the function that provides the operation

11776:   Level: developer

11778:   Example Usage:
11779: .vb
11780:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11782:   PetscCall(MatCreateXXX(comm, ..., &A));
11783:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11784: .ve

11786:   Notes:
11787:   See the file `include/petscmat.h` for a complete list of matrix
11788:   operations, which all have the form MATOP_<OPERATION>, where
11789:   <OPERATION> is the name (in all capital letters) of the
11790:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11792:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11793:   sequence as the usual matrix interface routines, since they
11794:   are intended to be accessed via the usual matrix interface
11795:   routines, e.g.,
11796: .vb
11797:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11798: .ve

11800:   In particular each function MUST return `PETSC_SUCCESS` on success and
11801:   nonzero on failure.

11803:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11805: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11806: @*/
11807: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11808: {
11809:   PetscFunctionBegin;
11812:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11813: #if !PetscDefined(USE_COMPLEX)
11814:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11815:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11816:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11817: #endif
11818:   ((PetscErrorCodeFn **)mat->ops)[op] = f;
11819:   PetscFunctionReturn(PETSC_SUCCESS);
11820: }

11822: /*@
11823:   MatGetOperation - Gets a matrix operation for any matrix type.

11825:   Not Collective

11827:   Input Parameters:
11828: + mat - the matrix
11829: - op  - the name of the operation

11831:   Output Parameter:
11832: . f - the function that provides the operation

11834:   Level: developer

11836:   Example Usage:
11837: .vb
11838:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11840:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11841: .ve

11843:   Notes:
11844:   See the file `include/petscmat.h` for a complete list of matrix
11845:   operations, which all have the form MATOP_<OPERATION>, where
11846:   <OPERATION> is the name (in all capital letters) of the
11847:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11849:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11851: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11852: @*/
11853: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11854: {
11855:   PetscFunctionBegin;
11857:   PetscAssertPointer(f, 3);
11858: #if !PetscDefined(USE_COMPLEX)
11859:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11860:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11861:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11862: #endif
11863:   *f = ((PetscErrorCodeFn **)mat->ops)[op];
11864:   PetscFunctionReturn(PETSC_SUCCESS);
11865: }

11867: /*@
11868:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11870:   Not Collective

11872:   Input Parameters:
11873: + mat - the matrix
11874: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11876:   Output Parameter:
11877: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11879:   Level: advanced

11881:   Note:
11882:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11884: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11885: @*/
11886: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11887: {
11888:   PetscFunctionBegin;
11890:   PetscAssertPointer(has, 3);
11891: #if !PetscDefined(USE_COMPLEX)
11892:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11893:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11894:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11895: #endif
11896:   if (op == MATOP_ADOT || op == MATOP_ANORM) {
11897:     /* MatADot() and MatANorm() fall back to MatMult() when the type has no method */
11898:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11899:     else PetscCall(MatHasOperation(mat, MATOP_MULT, has));
11900:     PetscFunctionReturn(PETSC_SUCCESS);
11901:   }
11902:   if (mat->ops->hasoperation) {
11903:     PetscUseTypeMethod(mat, hasoperation, op, has);
11904:   } else {
11905:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11906:     else {
11907:       *has = PETSC_FALSE;
11908:       if (op == MATOP_CREATE_SUBMATRIX) {
11909:         PetscMPIInt size;

11911:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11912:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11913:       }
11914:     }
11915:   }
11916:   PetscFunctionReturn(PETSC_SUCCESS);
11917: }

11919: /*@
11920:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11922:   Collective

11924:   Input Parameter:
11925: . mat - the matrix

11927:   Output Parameter:
11928: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11930:   Level: beginner

11932: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11933: @*/
11934: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11935: {
11936:   PetscFunctionBegin;
11939:   PetscAssertPointer(cong, 2);
11940:   if (!mat->rmap || !mat->cmap) {
11941:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11942:     PetscFunctionReturn(PETSC_SUCCESS);
11943:   }
11944:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11945:     PetscCall(PetscLayoutSetUp(mat->rmap));
11946:     PetscCall(PetscLayoutSetUp(mat->cmap));
11947:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11948:     if (*cong) mat->congruentlayouts = 1;
11949:     else mat->congruentlayouts = 0;
11950:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11951:   PetscFunctionReturn(PETSC_SUCCESS);
11952: }

11954: /*@
11955:   MatFlag - set infinity into the local part of the matrix on any subset of MPI processes

11957:   Logically Collective

11959:   Input Parameters:
11960: + A   - the matrix, can be `NULL` but only if on all processes
11961: - flg - indicates if this processes portion of the matrix should be set to infinity

11963:   Level: developer

11965:   Notes:
11966:   This is used to flag a block of solutions that a linear solver failed to compute, as `VecFlag()` does for a single solution.

11968:   The state of `A` is increased on all processes, whether or not their portion is flagged, so an outer solver that tracks it detects the failure even when the entries were already infinite.

11970:   Only the dense types (`MATSEQDENSE`, `MATMPIDENSE`, and their device variants) currently implement this operation.

11972: .seealso: [](ch_matrices), `Mat`, `VecFlag()`, `MatZeroEntries()`, `MatSetValues()`
11973: @*/
11974: PetscErrorCode MatFlag(Mat A, PetscInt flg)
11975: {
11976:   PetscFunctionBegin;
11977:   if (!A) PetscFunctionReturn(PETSC_SUCCESS);
11980:   MatCheckPreallocated(A, 1);
11981:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
11982:   if (flg) PetscUseTypeMethod(A, setinf);
11983:   PetscFunctionReturn(PETSC_SUCCESS);
11984: }

11986: /*@
11987:   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
11988:   and possibly removes small values from the graph structure.

11990:   Collective

11992:   Input Parameters:
11993: + A       - the matrix
11994: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11995: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11996: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with $|entries| \le filter$
11997: . num_idx - size of `index` array
11998: - index   - array of block indices to use for graph strength of connection weight

12000:   Output Parameter:
12001: . graph - the resulting graph

12003:   Level: advanced

12005: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
12006: @*/
12007: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
12008: {
12009:   PetscFunctionBegin;
12013:   PetscAssertPointer(graph, 7);
12014:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
12015:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
12016:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
12017:   PetscFunctionReturn(PETSC_SUCCESS);
12018: }

12020: /*@
12021:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
12022:   meaning the same memory is used for the matrix, and no new memory is allocated.

12024:   Collective

12026:   Input Parameters:
12027: + A    - the matrix
12028: - 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

12030:   Level: intermediate

12032:   Developer Note:
12033:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
12034:   of the arrays in the data structure may be no longer needed to represent the matrix.

12036: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
12037: @*/
12038: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
12039: {
12040:   PetscFunctionBegin;
12042:   PetscUseTypeMethod(A, eliminatezeros, keep);
12043:   PetscFunctionReturn(PETSC_SUCCESS);
12044: }

12046: /*@
12047:   MatGetCurrentMemType - Get the memory location of the matrix

12049:   Not Collective, but the result will be the same on all MPI processes

12051:   Input Parameter:
12052: . A - the matrix whose memory type we are checking

12054:   Output Parameter:
12055: . m - the memory type, see `PetscMemType`

12057:   Level: intermediate

12059: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
12060: @*/
12061: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
12062: {
12063:   PetscFunctionBegin;
12065:   PetscAssertPointer(m, 2);
12066:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
12067:   else *m = PETSC_MEMTYPE_HOST;
12068:   PetscFunctionReturn(PETSC_SUCCESS);
12069: }