Actual source code: matrix.c

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

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

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

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

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

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

 55:   Logically Collective

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

 62:   Level: intermediate

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

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

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

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

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

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

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

 91:   PetscFunctionBegin;
 95:   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");
 96:   MatCheckPreallocated(x, 1);

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

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

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

117:   Logically Collective

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

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

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

131:   Level: advanced

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

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

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

149:   Logically Collective

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

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

159:   Level: advanced

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

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

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

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

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

186:   Logically Collective

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

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

194:   Level: advanced

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

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

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

214:   Logically Collective

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

219:   Level: developer

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

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

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

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

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

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

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

302:   Level: intermediate

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

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

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

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

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

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

335:   Level: intermediate

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

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

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

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

368:   Not Collective

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

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

376:   Level: advanced

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

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

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

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

403: /*@
404:   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`

406:   Not Collective

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

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

414:   Level: advanced

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

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

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

425:   For `MATMPIAIJ`, `MATMPIBAIJ`, `MATMPIDENSE`, and `MATMPISELL`, this `PetscSF` is used within
426:   `MatMult()` to provide the contribution of vector entries that are not local to each MPI process to the matrix-vector product.
427:   For `MATMPISBAIJ` the returned `PetscSF` is instead the off-process column gather used by operations such as
428:   `MatDiagonalScale()`; `MatMult_MPISBAIJ()` uses a separate, augmented scatter context.
429:   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,
430:   so it can be reused to communicate any per-column data, for example with `PetscSFBcastBegin()`.

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

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

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

453:   Collective

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

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

461:   Level: advanced

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

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

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

482:   Logically Collective

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

487:   Level: advanced

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

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

507:   Collective

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

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

516:   Level: advanced

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

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

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

541:   Logically Collective

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

546:   Level: advanced

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

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

569:   Not Collective

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

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

580:   Level: advanced

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

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

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

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

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

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

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

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

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

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

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

639:   Logically Collective

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

644:   Level: advanced

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

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

663:   Not Collective

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

672:   Level: advanced

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

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

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

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

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

706:   Not Collective

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

711:   Level: advanced

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

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

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

733:   Not Collective

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

738:   Level: advanced

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

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

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

761:   Logically Collective

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

767:   Level: advanced

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

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

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

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

792:   Logically Collective

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

798:   Level: developer

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

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

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

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

828:   Logically Collective

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

834:   Level: developer

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

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

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

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

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

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

872:   Logically Collective

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

878:   Level: advanced

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

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

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

899:   Not Collective

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

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

907:   Level: advanced

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

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

923:   Not Collective, No Fortran Support

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

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

931:   Level: developer

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

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

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

952:   Not Collective, No Fortran Support

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

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

961:   Level: developer

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

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

976:   Not Collective, No Fortran Support

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

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

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

987:   Level: developer

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

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

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

1008:   Collective

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

1013:   Level: beginner

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

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

1022:   Currently only supported for  `MATAIJ` matrices.

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

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

1038:   Collective

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

1043:   Level: intermediate

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

1048:   Currently only supported for `MATAIJ` matrices.

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

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

1071:   Collective

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

1076:   Level: advanced

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

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

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

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

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

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

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

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

1120:   Collective

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

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

1130:   Level: intermediate

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

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

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

1152:   Collective on viewer

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

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

1162:   Level: beginner

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

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

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

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

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

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

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

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

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

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

1220:   PetscFunctionBegin;
1223:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

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

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

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

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

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

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

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

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

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

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

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

1362:   Collective

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

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

1372:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1481:   PetscFunctionBegin;

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

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

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

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

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

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

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

1533:   Collective

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

1538:   Level: beginner

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

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

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

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

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

1588:   Not Collective

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

1600:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

1679:   Not Collective

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

1689:   Level: beginner

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

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

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

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

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

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

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

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

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

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

1739:   Not Collective

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

1746:   Level: intermediate

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

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

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

1755:   `row` must belong to this MPI process

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

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

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

1776:   Not Collective

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

1783:   Level: advanced

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

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

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

1792:   `row` must belong to this process

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

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

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

1823:   Not Collective

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

1835:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1937:   Not Collective

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

1949:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2047:   Not Collective

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

2056:   Level: beginner

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

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

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

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

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

2089:   Not Collective

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

2101:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2234:   Level: advanced

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

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

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

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

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

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

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

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

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

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

2284:   Not Collective

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

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

2297:   Level: advanced

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

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

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

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

2351:   Not Collective

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

2360:   Level: advanced

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

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

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

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

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

2390:   Not Collective

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

2397:   Level: intermediate

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

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

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

2422:   Not Collective

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

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

2431:   Level: advanced

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

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

2454:   Logically Collective

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

2461:   Level: advanced

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

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

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

2480:   Not Collective

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

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

2489:   Level: advanced

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

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

2513:   Not Collective

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

2525:   Level: intermediate

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

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

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

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

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

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

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

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

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

2602:   Not Collective

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

2614:   Level: intermediate

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

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

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

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

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

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

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

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

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

2703:   Collective

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

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

2712:   Level: developer

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

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

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

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

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

2741:   Neighbor-wise Collective

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

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

2750:   Level: beginner

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

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

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

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

2789:   Neighbor-wise Collective

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

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

2798:   Level: beginner

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

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

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

2813:   PetscFunctionBegin;
2817:   VecCheckAssembled(x);

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

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

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

2847:   Neighbor-wise Collective

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

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

2856:   Level: beginner

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

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

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

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

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

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

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

2910:   Neighbor-wise Collective

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

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

2920:   Level: beginner

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

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

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

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

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

2959:   Neighbor-wise Collective

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

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

2969:   Level: beginner

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

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

2981:   PetscFunctionBegin;

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

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

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

3009:   Neighbor-wise Collective

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

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

3019:   Level: beginner

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

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

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

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

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

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

3079:   PetscFunctionBegin;
3080:   PetscCall(MatADot(mat, x, x, &sval));
3081:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3082:   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");
3083:   *val = PetscSqrtReal(PetscRealPart(sval));
3084:   PetscFunctionReturn(PETSC_SUCCESS);
3085: }

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

3091:   Collective

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

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

3101:   Level: intermediate

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

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

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

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

3150:   Collective

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

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

3159:   Level: intermediate

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

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

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

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

3200:   Not Collective

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

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

3208:   Level: intermediate

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

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

3226:   Logically Collective

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

3232:   Level: intermediate

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

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

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

3252:   Input Parameters:
3253: + mat  - the matrix
3254: - 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)

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

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

3262:   Level: intermediate

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

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

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

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

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

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

3311:   Collective

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

3324:   Level: developer

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

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

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

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

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

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

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

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

3371:   Collective

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

3385:   Level: developer

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

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

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

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

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

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

3425:   Collective

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

3438:   Level: developer

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

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

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

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

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

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

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

3483:   Collective

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

3490:   Level: developer

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

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

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

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

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

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

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

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

3538:   Collective

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

3545:   Level: developer

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

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

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

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

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

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

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

3590:   Collective

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

3603:   Level: developer

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

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

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

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

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

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

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

3651:   Collective

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

3658:   Level: developer

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

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

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

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

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

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

3701:   Collective

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

3713:   Level: developer

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

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

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

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

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

3750:   Collective

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

3763:   Level: developer

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

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

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

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

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

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

3805:   Collective

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

3812:   Level: developer

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

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

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

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

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

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

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

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

3858:   Neighbor-wise Collective

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

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

3867:   Level: developer

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

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

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

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

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

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

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

3942:   Neighbor-wise Collective

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

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

3951:   Level: developer

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

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

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

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

3990:   Neighbor-wise Collective

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

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

3999:   Level: developer

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

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

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

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

4040:   Neighbor-wise Collective

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

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

4049:   Level: developer

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

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

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

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

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

4089:   Neighbor-wise Collective

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

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

4098:   Level: developer

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

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

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

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

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

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

4142:   Neighbor-wise Collective

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

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

4151:   Level: developer

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

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

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

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

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

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

4194:   Neighbor-wise Collective

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

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

4204:   Level: developer

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

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

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

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

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

4262:   Neighbor-wise Collective

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

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

4271:   Level: developer

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

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

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

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

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

4316:   Neighbor-wise Collective

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

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

4326:   Level: developer

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

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

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

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

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

4385:   Neighbor-wise Collective

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

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

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

4410:   Level: developer

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

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

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

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

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

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

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

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

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

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

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

4489:   Collective

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

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

4498:   Level: intermediate

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

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

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

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

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

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

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

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

4547:   Collective

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

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

4560:   Level: intermediate

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

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

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

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

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

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

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

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

4609:   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4610:     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4611:     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
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:           PetscFunctionReturn(PETSC_SUCCESS);
4642:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4643:           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4644:           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4645:           PetscFunctionReturn(PETSC_SUCCESS);
4646:         }
4647:       }
4648:     }
4649:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4650:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4651:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4652:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4653:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4654:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4655:       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4656:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4657:       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4658:       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4659:       if (conv) goto foundconv;
4660:     }

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

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

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

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

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

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

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

4728:   Not Collective

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

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

4736:   Level: intermediate

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

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

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

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

4770: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4775:   Logically Collective, No Fortran Support

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

4783:   Level: developer

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

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

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

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

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

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

4852:   Level: developer

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

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

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

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

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

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

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

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

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

4987:   Logically Collective

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

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

4995:   Level: developer

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

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

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

5013:   Logically Collective

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

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

5022:   Level: developer

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

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

5038:   Collective

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

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

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

5054:   Level: intermediate

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

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

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

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

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

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

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

5090:   PetscFunctionBegin;

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

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

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

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

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

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

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

5133:   Not Collective

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

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

5143:   Level: intermediate

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

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

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

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

5161:   PetscFunctionBegin;
5163:   PetscAssertPointer(flg, 4);

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

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

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

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

5179:   Collective

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

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

5189:   Level: intermediate

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

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

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

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

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

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

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

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

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

5237:   B->nooffproczerorows = mat->nooffproczerorows;
5238:   B->nooffprocentries  = mat->nooffprocentries;

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

5251: /*@
5252:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5254:   Logically Collective

5256:   Input Parameter:
5257: . mat - the matrix

5259:   Output Parameter:
5260: . v - the diagonal of the matrix

5262:   Level: intermediate

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

5269:   Currently only correct in parallel for square matrices.

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

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

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

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

5299:   Logically Collective

5301:   Input Parameter:
5302: . mat - the matrix

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

5308:   Level: intermediate

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

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

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

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

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

5345:   Logically Collective

5347:   Input Parameter:
5348: . mat - the matrix

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

5354:   Level: intermediate

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

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

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

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

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

5392:   Logically Collective

5394:   Input Parameter:
5395: . mat - the matrix

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

5401:   Level: intermediate

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

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

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

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

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

5437:   Logically Collective

5439:   Input Parameter:
5440: . mat - the matrix

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

5446:   Level: intermediate

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

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

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

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

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

5482:   Logically Collective

5484:   Input Parameter:
5485: . mat - the matrix

5487:   Output Parameter:
5488: . v - the vector for storing the sum

5490:   Level: intermediate

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

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

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

5513: /*@
5514:   MatGetRowSum - Gets the sum of each row of the matrix

5516:   Logically or Neighborhood Collective

5518:   Input Parameter:
5519: . mat - the matrix

5521:   Output Parameter:
5522: . v - the vector for storing the sum of rows

5524:   Level: intermediate

5526:   Note:
5527:   This code is slow since it is not currently specialized for different formats

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

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

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

5552:   Collective

5554:   Input Parameter:
5555: . mat - the matrix to provide the transpose

5557:   Output Parameter:
5558: . 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

5560:   Level: advanced

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

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

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

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

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

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

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

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

5630:   Collective

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

5636:   Output Parameter:
5637: . B - the transpose of the matrix

5639:   Level: intermediate

5641:   Notes:
5642:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

5656: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5657:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5658: @*/
5659: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5660: {
5661:   PetscFunctionBegin;
5662:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5663:   PetscFunctionReturn(PETSC_SUCCESS);
5664: }

5666: /*@
5667:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5669:   Collective

5671:   Input Parameter:
5672: . A - the matrix to transpose

5674:   Output Parameter:
5675: . 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
5676:       numerical portion.

5678:   Level: intermediate

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

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

5696:   PetscCall(MatTransposeSetPrecursor(A, *B));
5697:   PetscFunctionReturn(PETSC_SUCCESS);
5698: }

5700: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5701: {
5702:   PetscContainer rB;
5703:   MatState      *rb;

5705:   PetscFunctionBegin;
5708:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5709:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5710:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5711:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5712:   PetscCall(PetscContainerGetPointer(rB, &rb));
5713:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5714:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5715:   PetscFunctionReturn(PETSC_SUCCESS);
5716: }

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

5722:   Collective

5724:   Input Parameters:
5725: + A   - the matrix to test
5726: . B   - the matrix to test against, this can equal the first parameter
5727: - tol - tolerance, differences between entries smaller than this are counted as zero

5729:   Output Parameter:
5730: . flg - the result

5732:   Level: intermediate

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

5738: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5739: @*/
5740: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5741: {
5742:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5744:   PetscFunctionBegin;
5747:   PetscAssertPointer(flg, 4);
5748:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5749:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5750:   *flg = PETSC_FALSE;
5751:   if (f && g) {
5752:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5753:     PetscCall((*f)(A, B, tol, flg));
5754:   } else {
5755:     MatType mattype;

5757:     PetscCall(MatGetType(f ? B : A, &mattype));
5758:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5759:   }
5760:   PetscFunctionReturn(PETSC_SUCCESS);
5761: }

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

5766:   Collective

5768:   Input Parameters:
5769: + mat   - the matrix to transpose and complex conjugate
5770: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5772:   Output Parameter:
5773: . B - the Hermitian transpose

5775:   Level: intermediate

5777: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5778: @*/
5779: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5780: {
5781:   PetscFunctionBegin;
5782:   PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5783:   PetscFunctionReturn(PETSC_SUCCESS);
5784: }

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

5789:   Collective

5791:   Input Parameters:
5792: + A   - the matrix to test
5793: . B   - the matrix to test against, this can equal the first parameter
5794: - tol - tolerance, differences between entries smaller than this are counted as zero

5796:   Output Parameter:
5797: . flg - the result

5799:   Level: intermediate

5801:   Notes:
5802:   Only available for `MATAIJ` matrices.

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

5808: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5809: @*/
5810: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5811: {
5812:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5814:   PetscFunctionBegin;
5817:   PetscAssertPointer(flg, 4);
5818:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5819:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5820:   if (f && g) {
5821:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5822:     PetscCall((*f)(A, B, tol, flg));
5823:   } else {
5824:     MatType mattype;

5826:     PetscCall(MatGetType(f ? B : A, &mattype));
5827:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5828:   }
5829:   PetscFunctionReturn(PETSC_SUCCESS);
5830: }

5832: /*@
5833:   MatPermute - Creates a new matrix with rows and columns permuted from the
5834:   original.

5836:   Collective

5838:   Input Parameters:
5839: + mat - the matrix to permute
5840: . row - row permutation, each process supplies only the permutation for its rows
5841: - col - column permutation, each process supplies only the permutation for its columns

5843:   Output Parameter:
5844: . B - the permuted matrix

5846:   Level: advanced

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

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

5858: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5859: @*/
5860: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5861: {
5862:   PetscFunctionBegin;
5867:   PetscAssertPointer(B, 4);
5868:   PetscCheckSameComm(mat, 1, row, 2);
5869:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5870:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5871:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5872:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5873:   MatCheckPreallocated(mat, 1);

5875:   if (mat->ops->permute) {
5876:     PetscUseTypeMethod(mat, permute, row, col, B);
5877:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5878:   } else {
5879:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5880:   }
5881:   PetscFunctionReturn(PETSC_SUCCESS);
5882: }

5884: /*@
5885:   MatEqual - Compares two matrices.

5887:   Collective

5889:   Input Parameters:
5890: + A - the first matrix
5891: - B - the second matrix

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

5896:   Level: intermediate

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

5902: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5903: @*/
5904: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5905: {
5906:   PetscFunctionBegin;
5911:   PetscAssertPointer(flg, 3);
5912:   PetscCheckSameComm(A, 1, B, 2);
5913:   MatCheckPreallocated(A, 1);
5914:   MatCheckPreallocated(B, 2);
5915:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5916:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5917:   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,
5918:              B->cmap->N);
5919:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5920:   else PetscCall(MatMultEqual(A, B, 10, flg));
5921:   PetscFunctionReturn(PETSC_SUCCESS);
5922: }

5924: /*@
5925:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5926:   matrices that are stored as vectors. Either of the two scaling
5927:   matrices can be `NULL`.

5929:   Collective

5931:   Input Parameters:
5932: + mat - the matrix to be scaled
5933: . l   - the left scaling vector (or `NULL`)
5934: - r   - the right scaling vector (or `NULL`)

5936:   Level: intermediate

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

5944: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5945: @*/
5946: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5947: {
5948:   PetscBool flg = PETSC_FALSE;

5950:   PetscFunctionBegin;
5953:   if (l) {
5955:     PetscCheckSameComm(mat, 1, l, 2);
5956:   }
5957:   if (r) {
5959:     PetscCheckSameComm(mat, 1, r, 3);
5960:   }
5961:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5962:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5963:   MatCheckPreallocated(mat, 1);
5964:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

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

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

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

6006:   Logically Collective

6008:   Input Parameters:
6009: + mat - the matrix to be scaled
6010: - a   - the scaling value

6012:   Level: intermediate

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

6026:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6027:   if (a != (PetscScalar)1.0) {
6028:     PetscUseTypeMethod(mat, scale, a);
6029:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6030:   }
6031:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6032:   PetscFunctionReturn(PETSC_SUCCESS);
6033: }

6035: /*@
6036:   MatNorm - Calculates various norms of a matrix.

6038:   Collective

6040:   Input Parameters:
6041: + mat  - the matrix
6042: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

6044:   Output Parameter:
6045: . nrm - the resulting norm

6047:   Level: intermediate

6049: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
6050: @*/
6051: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
6052: {
6053:   PetscFunctionBegin;
6057:   PetscAssertPointer(nrm, 3);

6059:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6060:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6061:   MatCheckPreallocated(mat, 1);

6063:   PetscUseTypeMethod(mat, norm, type, nrm);
6064:   PetscFunctionReturn(PETSC_SUCCESS);
6065: }

6067: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6068: {
6069:   PetscScalar *ax, nm1;
6070:   PetscInt     st, en, n;

6072:   PetscFunctionBegin;
6073:   PetscCall(VecGetSize(x, &n));
6074:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6075:   nm1 = n - 1;
6076:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6077:   PetscCall(VecGetArrayWrite(x, &ax));
6078:   for (PetscInt i = st; i < en; i++) {
6079:     const PetscInt    ii = i - st;
6080:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6082:     ax[ii] = s * (1.0 + i / nm1);
6083:   }
6084:   PetscCall(VecRestoreArrayWrite(x, &ax));
6085:   PetscFunctionReturn(PETSC_SUCCESS);
6086: }

6088: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6089: {
6090:   Vec         x, y;
6091:   PetscReal   normx, normy;
6092:   PetscInt    i, N;
6093:   PetscRandom rnd;

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

6132: /*@
6133:   MatNormApproximate - Approximate the norm of a matrix.

6135:   Collective

6137:   Input Parameters:
6138: + A        - the matrix
6139: . normtype - the `NormType`
6140: - maxit    - maximum number of iterations to use

6142:   Output Parameter:
6143: . n - the norm estimate

6145:   Level: intermediate

6147:   Notes:
6148:   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`.

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

6152: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6153: @*/
6154: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6155: {
6156:   Vec         x, y, w, z;
6157:   PetscReal   normz, adot;
6158:   PetscScalar dot;
6159:   PetscInt    i, j, N, jold = -1;
6160:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

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

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

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

6273:         PetscCall(VecNormalize(z, NULL));
6274:         t = x;
6275:         x = z;
6276:         z = t;
6277:       }
6278:     }
6279:     PetscCall(VecDestroy(&x));
6280:     PetscCall(VecDestroy(&y));
6281:     PetscCall(VecDestroy(&z));
6282:     break;
6283:   default:
6284:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6285:   }
6286:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6287:   PetscFunctionReturn(PETSC_SUCCESS);
6288: }

6290: /*
6291:      This variable is used to prevent counting of MatAssemblyBegin() that
6292:    are called from within a MatAssemblyEnd().
6293: */
6294: static PetscInt MatAssemblyEnd_InUse = 0;
6295: /*@
6296:   MatAssemblyBegin - Begins assembling the matrix. This routine should
6297:   be called after completing all calls to `MatSetValues()`.

6299:   Collective

6301:   Input Parameters:
6302: + mat  - the matrix
6303: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6305:   Level: beginner

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

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

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

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

6323: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6324: @*/
6325: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6326: {
6327:   PetscFunctionBegin;
6330:   MatCheckPreallocated(mat, 1);
6331:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6332:   if (mat->assembled) {
6333:     mat->was_assembled = PETSC_TRUE;
6334:     mat->assembled     = PETSC_FALSE;
6335:   }

6337:   if (!MatAssemblyEnd_InUse) {
6338:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6339:     PetscTryTypeMethod(mat, assemblybegin, type);
6340:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6341:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6342:   PetscFunctionReturn(PETSC_SUCCESS);
6343: }

6345: /*@
6346:   MatAssembled - Indicates if a matrix has been assembled and is ready for
6347:   use; for example, in matrix-vector product.

6349:   Not Collective

6351:   Input Parameter:
6352: . mat - the matrix

6354:   Output Parameter:
6355: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6357:   Level: advanced

6359: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6360: @*/
6361: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6362: {
6363:   PetscFunctionBegin;
6365:   PetscAssertPointer(assembled, 2);
6366:   *assembled = mat->assembled;
6367:   PetscFunctionReturn(PETSC_SUCCESS);
6368: }

6370: /*@
6371:   MatAssemblyEnd - Completes assembling the matrix. This routine should
6372:   be called after `MatAssemblyBegin()`.

6374:   Collective

6376:   Input Parameters:
6377: + mat  - the matrix
6378: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6380:   Options Database Key:
6381: . -mat_view viewer_specification - Displays the matrix during this function call. See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

6383:   Level: beginner

6385: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6386:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`, `PetscOptionsCreateViewer()`
6387: @*/
6388: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6389: {
6390:   static PetscInt inassm = 0;
6391:   PetscBool       flg    = PETSC_FALSE;

6393:   PetscFunctionBegin;

6397:   inassm++;
6398:   MatAssemblyEnd_InUse++;
6399:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6400:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6401:     PetscTryTypeMethod(mat, assemblyend, type);
6402:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6403:   } else PetscTryTypeMethod(mat, assemblyend, type);

6405:   /* Flush assembly is not a true assembly */
6406:   if (type != MAT_FLUSH_ASSEMBLY) {
6407:     if (mat->num_ass) {
6408:       if (!mat->symmetry_eternal) {
6409:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6410:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6411:       }
6412:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6413:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6414:     }
6415:     mat->num_ass++;
6416:     mat->assembled        = PETSC_TRUE;
6417:     mat->ass_nonzerostate = mat->nonzerostate;
6418:   }

6420:   mat->insertmode = NOT_SET_VALUES;
6421:   MatAssemblyEnd_InUse--;
6422:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6423:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6424:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6426:     if (mat->checksymmetryonassembly) {
6427:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6428:       if (flg) {
6429:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6430:       } else {
6431:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6432:       }
6433:     }
6434:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6435:   }
6436:   inassm--;
6437:   PetscFunctionReturn(PETSC_SUCCESS);
6438: }

6440: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6441: /*@
6442:   MatSetOption - Sets a parameter option for a matrix. Some options
6443:   may be specific to certain storage formats. Some options
6444:   determine how values will be inserted (or added). Sorted,
6445:   row-oriented input will generally assemble the fastest. The default
6446:   is row-oriented.

6448:   Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`

6450:   Input Parameters:
6451: + mat - the matrix
6452: . op  - the option, one of those listed below (and possibly others),
6453: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6455:   Options Describing Matrix Structure:
6456: + `MAT_SPD`                         - symmetric positive definite
6457: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6458: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6459: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6460: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6461: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6462: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

6464:    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6465:    do not need to be computed (usually at a high cost)

6467:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6468:    Insert a logically dense subblock, which can be
6469: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6471:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6472:    nothing to do with how the data is stored internally in the matrix
6473:    data structure.

6475:    When (re)assembling a matrix, we can restrict the input for
6476:    efficiency/debugging purposes. These options include
6477: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6478: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6479: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-process entries
6480: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6481: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6482: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6483:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6484:                                       performance for very large process counts.
6485: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6486:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6487:                                       functions, instead sending only neighbor messages.

6489:   Level: intermediate

6491:   Notes:
6492:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6494:   Some options are relevant only for particular matrix types and
6495:   are thus ignored by others. Other options are not supported by
6496:   certain matrix types and will generate an error message if set.

6498:   Once `MAT_STRUCTURE_ONLY` has been set to `PETSC_TRUE`, it cannot be set back to `PETSC_FALSE`.

6500:   The matrix properties must be consistent with one another. With real scalars, `MAT_SPD` implies `MAT_SYMMETRIC`, and
6501:   both `MAT_SYMMETRIC` and `MAT_HERMITIAN` imply `MAT_STRUCTURALLY_SYMMETRIC`. Setting a property that contradicts
6502:   another known property generates an error. Still with real scalars, setting either `MAT_SYMMETRIC` or `MAT_HERMITIAN`
6503:   also sets the other to the same value.

6505:   If using Fortran to compute a matrix, one may need to use the column-oriented
6506:   option (or convert to the row-oriented format).

6508:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6509:   that would generate a new entry in the nonzero structure is instead
6510:   ignored. Thus, if memory has not already been allocated for this particular
6511:   data, then the insertion is ignored. For dense matrices, in which
6512:   the entire array is allocated, no entries are ever ignored.
6513:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6515:   `MAT_NEW_NONZERO_LOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6516:   that would generate a new entry in the nonzero structure instead produces
6517:   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

6519:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6520:   that would generate a new entry that has not been preallocated will
6521:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6522:   only.) This is a useful flag when debugging matrix memory preallocation.
6523:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6525:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6526:   other processes should be dropped, rather than stashed.
6527:   This is useful if you know that the "owning" process is also
6528:   always generating the correct matrix entries, so that PETSc need
6529:   not transfer duplicate entries generated on another process.

6531:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6532:   searches during matrix assembly. When this flag is set, the hash table
6533:   is created during the first matrix assembly. This hash table is
6534:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6535:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6536:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6537:   supported by `MATMPIBAIJ` format only.

6539:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6540:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6542:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ`, `MATSELL`, and `MATIS` matrices this will stop zero values
6543:   from creating a zero location in the matrix. A zero on the diagonal is exempt and still creates its
6544:   location, so that operations needing a full diagonal, such as `MatSOR()`, keep working. The exemption
6545:   covers the diagonal portion of the owning process's rows; a zero added with `ADD_VALUES` to a row owned
6546:   by another process is dropped as it is stashed and never reaches that test. A matrix assembled without
6547:   preallocation, through `MatSetUp()`, decides the exemption from process-local indices, so it does not
6548:   hold there when the row and column layouts differ

6550:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6552:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6553:   zero row routines and thus improves performance for very large process counts.

6555:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6556:   part of the matrix (since they should match the upper triangular part).

6558:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6559:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6560:   with finite difference schemes with non-periodic boundary conditions.

6562:   Developer Note:
6563:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6564:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6565:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6566:   not changed.

6568: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6569: @*/
6570: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6571: {
6572:   PetscFunctionBegin;
6574:   if (op > 0) {
6577:   }

6579:   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);

6581:   switch (op) {
6582:   case MAT_FORCE_DIAGONAL_ENTRIES:
6583:     mat->force_diagonals = flg;
6584:     PetscFunctionReturn(PETSC_SUCCESS);
6585:   case MAT_NO_OFF_PROC_ENTRIES:
6586:     mat->nooffprocentries = flg;
6587:     PetscFunctionReturn(PETSC_SUCCESS);
6588:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6589:     mat->assembly_subset = flg;
6590:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6591: #if !PetscDefined(HAVE_MPIUNI)
6592:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6593: #endif
6594:       mat->stash.first_assembly_done = PETSC_FALSE;
6595:     }
6596:     PetscFunctionReturn(PETSC_SUCCESS);
6597:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6598:     mat->nooffproczerorows = flg;
6599:     PetscFunctionReturn(PETSC_SUCCESS);
6600:   case MAT_SPD:
6601:     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");
6602:     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");
6603:     if (flg) {
6604:       mat->spd                    = PETSC_BOOL3_TRUE;
6605:       mat->symmetric              = PETSC_BOOL3_TRUE;
6606:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6607:       if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_TRUE;
6608:     } else mat->spd = PETSC_BOOL3_FALSE;
6609:     break;
6610:   case MAT_SYMMETRIC:
6611:     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");
6612:     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");
6613:     mat->symmetric = PetscBoolToBool3(flg);
6614:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6615:     if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PetscBoolToBool3(flg);
6616:     break;
6617:   case MAT_HERMITIAN:
6618:     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");
6619:     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");
6620:     mat->hermitian = PetscBoolToBool3(flg);
6621:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6622:     if (!PetscDefined(USE_COMPLEX)) mat->symmetric = PetscBoolToBool3(flg);
6623:     break;
6624:   case MAT_STRUCTURALLY_SYMMETRIC:
6625:     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");
6626:     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");
6627:     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");
6628:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6629:     break;
6630:   case MAT_SYMMETRY_ETERNAL:
6631:     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");
6632:     mat->symmetry_eternal = flg;
6633:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6634:     break;
6635:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6636:     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");
6637:     mat->structural_symmetry_eternal = flg;
6638:     break;
6639:   case MAT_SPD_ETERNAL:
6640:     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");
6641:     mat->spd_eternal = flg;
6642:     if (flg) {
6643:       mat->structural_symmetry_eternal = PETSC_TRUE;
6644:       mat->symmetry_eternal            = PETSC_TRUE;
6645:     }
6646:     break;
6647:   case MAT_STRUCTURE_ONLY:
6648:     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");
6649:     mat->structure_only = flg;
6650:     break;
6651:   case MAT_SORTED_FULL:
6652:     mat->sortedfull = flg;
6653:     break;
6654:   default:
6655:     break;
6656:   }
6657:   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");
6658:   PetscTryTypeMethod(mat, setoption, op, flg);
6659:   PetscFunctionReturn(PETSC_SUCCESS);
6660: }

6662: /*@
6663:   MatGetOption - Gets a parameter option that has been set for a matrix.

6665:   Logically Collective

6667:   Input Parameters:
6668: + mat - the matrix
6669: - op  - the option, this only responds to certain options, check the code for which ones

6671:   Output Parameter:
6672: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6674:   Level: intermediate

6676:   Notes:
6677:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6679:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6680:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6682: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6683:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6684: @*/
6685: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6686: {
6687:   PetscFunctionBegin;

6691:   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);
6692:   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()");

6694:   switch (op) {
6695:   case MAT_NO_OFF_PROC_ENTRIES:
6696:     *flg = mat->nooffprocentries;
6697:     break;
6698:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6699:     *flg = mat->nooffproczerorows;
6700:     break;
6701:   case MAT_SYMMETRIC:
6702:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6703:     break;
6704:   case MAT_HERMITIAN:
6705:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6706:     break;
6707:   case MAT_STRUCTURALLY_SYMMETRIC:
6708:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6709:     break;
6710:   case MAT_SPD:
6711:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6712:     break;
6713:   case MAT_SYMMETRY_ETERNAL:
6714:     *flg = mat->symmetry_eternal;
6715:     break;
6716:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6717:     *flg = mat->symmetry_eternal;
6718:     break;
6719:   default:
6720:     break;
6721:   }
6722:   PetscFunctionReturn(PETSC_SUCCESS);
6723: }

6725: /*@
6726:   MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6727:   this routine retains the old nonzero structure.

6729:   Logically Collective

6731:   Input Parameter:
6732: . mat - the matrix

6734:   Level: intermediate

6736:   Note:
6737:   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.
6738:   See the Performance chapter of the users manual for information on preallocating matrices.
6739:   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.

6741: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6742: @*/
6743: PetscErrorCode MatZeroEntries(Mat mat)
6744: {
6745:   PetscFunctionBegin;
6748:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6749:   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");
6750:   MatCheckPreallocated(mat, 1);

6752:   if (mat->structure_only == PETSC_FALSE) {
6753:     PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6754:     PetscUseTypeMethod(mat, zeroentries);
6755:     PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6756:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6757:   }
6758:   PetscFunctionReturn(PETSC_SUCCESS);
6759: }

6761: /*@
6762:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6763:   of a set of rows and columns of a matrix.

6765:   Collective

6767:   Input Parameters:
6768: + mat     - the matrix
6769: . numRows - the number of rows/columns to zero
6770: . rows    - the global row indices
6771: . diag    - value put in the diagonal of the eliminated rows
6772: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6773: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6775:   Level: intermediate

6777:   Notes:
6778:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6780:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6781:   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

6783:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6784:   Krylov method to take advantage of the known solution on the zeroed rows.

6786:   For the parallel case, all processes that share the matrix (i.e.,
6787:   those in the communicator used for matrix creation) MUST call this
6788:   routine, regardless of whether any rows being zeroed are owned by
6789:   them.

6791:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6792:   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
6793:   missing.

6795:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6796:   list only rows local to itself).

6798:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6800: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6801:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6802: @*/
6803: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6804: {
6805:   PetscFunctionBegin;
6808:   if (numRows) PetscAssertPointer(rows, 3);
6809:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6810:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6811:   MatCheckPreallocated(mat, 1);

6813:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6814:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6815:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6816:   PetscFunctionReturn(PETSC_SUCCESS);
6817: }

6819: /*@
6820:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6821:   of a set of rows and columns of a matrix.

6823:   Collective

6825:   Input Parameters:
6826: + mat  - the matrix
6827: . is   - the rows to zero
6828: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6829: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6830: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6832:   Level: intermediate

6834:   Note:
6835:   See `MatZeroRowsColumns()` for details on how this routine operates.

6837: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6838:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6839: @*/
6840: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6841: {
6842:   PetscInt        numRows;
6843:   const PetscInt *rows;

6845:   PetscFunctionBegin;
6850:   PetscCall(ISGetLocalSize(is, &numRows));
6851:   PetscCall(ISGetIndices(is, &rows));
6852:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6853:   PetscCall(ISRestoreIndices(is, &rows));
6854:   PetscFunctionReturn(PETSC_SUCCESS);
6855: }

6857: /*@
6858:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6859:   of a set of rows of a matrix.

6861:   Collective

6863:   Input Parameters:
6864: + mat     - the matrix
6865: . numRows - the number of rows to zero
6866: . rows    - the global row indices
6867: . diag    - value put in the diagonal of the zeroed rows
6868: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6869: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6871:   Level: intermediate

6873:   Notes:
6874:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6876:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6878:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6879:   Krylov method to take advantage of the known solution on the zeroed rows.

6881:   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)
6882:   from the matrix.

6884:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6885:   but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6886:   formats this does not alter the nonzero structure.

6888:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6889:   of the matrix is not changed the values are
6890:   merely zeroed.

6892:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6893:   formats can optionally remove the main diagonal entry from the
6894:   nonzero structure as well, by passing 0.0 as the final argument).

6896:   For the parallel case, all processes that share the matrix (i.e.,
6897:   those in the communicator used for matrix creation) MUST call this
6898:   routine, regardless of whether any rows being zeroed are owned by
6899:   them.

6901:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6902:   list only rows local to itself).

6904:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6905:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6907: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6908:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6909: @*/
6910: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6911: {
6912:   PetscFunctionBegin;
6915:   if (numRows) PetscAssertPointer(rows, 3);
6916:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6917:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6918:   MatCheckPreallocated(mat, 1);

6920:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6921:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6922:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6923:   PetscFunctionReturn(PETSC_SUCCESS);
6924: }

6926: /*@
6927:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6928:   of a set of rows of a matrix indicated by an `IS`

6930:   Collective

6932:   Input Parameters:
6933: + mat  - the matrix
6934: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6935: . diag - value put in all diagonals of eliminated rows
6936: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6937: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6939:   Level: intermediate

6941:   Note:
6942:   See `MatZeroRows()` for details on how this routine operates.

6944: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6945:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6946: @*/
6947: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6948: {
6949:   PetscInt        numRows = 0;
6950:   const PetscInt *rows    = NULL;

6952:   PetscFunctionBegin;
6955:   if (is) {
6957:     PetscCall(ISGetLocalSize(is, &numRows));
6958:     PetscCall(ISGetIndices(is, &rows));
6959:   }
6960:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6961:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6962:   PetscFunctionReturn(PETSC_SUCCESS);
6963: }

6965: /*@
6966:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6967:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6969:   Collective

6971:   Input Parameters:
6972: + mat     - the matrix
6973: . numRows - the number of rows to remove
6974: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6975: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6976: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6977: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6979:   Level: intermediate

6981:   Notes:
6982:   See `MatZeroRows()` for details on how this routine operates.

6984:   The grid coordinates are across the entire grid, not just the local portion

6986:   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6987:   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6988:   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6989:   `DM_BOUNDARY_PERIODIC` boundary type.

6991:   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
6992:   a single value per point) you can skip filling those indices.

6994:   Fortran Note:
6995:   `idxm` and `idxn` should be declared as
6996: .vb
6997:     MatStencil idxm(4, m)
6998: .ve
6999:   and the values inserted using
7000: .vb
7001:     idxm(MatStencil_i, 1) = i
7002:     idxm(MatStencil_j, 1) = j
7003:     idxm(MatStencil_k, 1) = k
7004:     idxm(MatStencil_c, 1) = c
7005:    etc
7006: .ve

7008: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7009:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7010: @*/
7011: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7012: {
7013:   PetscInt  dim    = mat->stencil.dim;
7014:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7015:   PetscInt *dims   = mat->stencil.dims + 1;
7016:   PetscInt *starts = mat->stencil.starts;
7017:   PetscInt *dxm    = (PetscInt *)rows;
7018:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7020:   PetscFunctionBegin;
7023:   if (numRows) PetscAssertPointer(rows, 3);

7025:   PetscCall(PetscMalloc1(numRows, &jdxm));
7026:   for (i = 0; i < numRows; ++i) {
7027:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7028:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7029:     /* Local index in X dir */
7030:     tmp = *dxm++ - starts[0];
7031:     /* Loop over remaining dimensions */
7032:     for (j = 0; j < dim - 1; ++j) {
7033:       /* If nonlocal, set index to be negative */
7034:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7035:       /* Update local index */
7036:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7037:     }
7038:     /* Skip component slot if necessary */
7039:     if (mat->stencil.noc) dxm++;
7040:     /* Local row number */
7041:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7042:   }
7043:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
7044:   PetscCall(PetscFree(jdxm));
7045:   PetscFunctionReturn(PETSC_SUCCESS);
7046: }

7048: /*@
7049:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
7050:   of a set of rows and columns of a matrix.

7052:   Collective

7054:   Input Parameters:
7055: + mat     - the matrix
7056: . numRows - the number of rows/columns to remove
7057: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
7058: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
7059: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7060: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7062:   Level: intermediate

7064:   Notes:
7065:   See `MatZeroRowsColumns()` for details on how this routine operates.

7067:   The grid coordinates are across the entire grid, not just the local portion

7069:   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
7070:   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
7071:   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
7072:   `DM_BOUNDARY_PERIODIC` boundary type.

7074:   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
7075:   a single value per point) you can skip filling those indices.

7077:   Fortran Note:
7078:   `idxm` and `idxn` should be declared as
7079: .vb
7080:     MatStencil idxm(4, m)
7081: .ve
7082:   and the values inserted using
7083: .vb
7084:     idxm(MatStencil_i, 1) = i
7085:     idxm(MatStencil_j, 1) = j
7086:     idxm(MatStencil_k, 1) = k
7087:     idxm(MatStencil_c, 1) = c
7088:     etc
7089: .ve

7091: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7092:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7093: @*/
7094: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7095: {
7096:   PetscInt  dim    = mat->stencil.dim;
7097:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7098:   PetscInt *dims   = mat->stencil.dims + 1;
7099:   PetscInt *starts = mat->stencil.starts;
7100:   PetscInt *dxm    = (PetscInt *)rows;
7101:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7103:   PetscFunctionBegin;
7106:   if (numRows) PetscAssertPointer(rows, 3);

7108:   PetscCall(PetscMalloc1(numRows, &jdxm));
7109:   for (i = 0; i < numRows; ++i) {
7110:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7111:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7112:     /* Local index in X dir */
7113:     tmp = *dxm++ - starts[0];
7114:     /* Loop over remaining dimensions */
7115:     for (j = 0; j < dim - 1; ++j) {
7116:       /* If nonlocal, set index to be negative */
7117:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7118:       /* Update local index */
7119:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7120:     }
7121:     /* Skip component slot if necessary */
7122:     if (mat->stencil.noc) dxm++;
7123:     /* Local row number */
7124:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7125:   }
7126:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7127:   PetscCall(PetscFree(jdxm));
7128:   PetscFunctionReturn(PETSC_SUCCESS);
7129: }

7131: /*@
7132:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7133:   of a set of rows of a matrix; using local numbering of rows.

7135:   Collective

7137:   Input Parameters:
7138: + mat     - the matrix
7139: . numRows - the number of rows to remove
7140: . rows    - the local row indices
7141: . diag    - value put in all diagonals of eliminated rows
7142: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7143: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7145:   Level: intermediate

7147:   Notes:
7148:   Before calling `MatZeroRowsLocal()`, the user must first set the
7149:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7151:   See `MatZeroRows()` for details on how this routine operates.

7153: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7154:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7155: @*/
7156: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7157: {
7158:   PetscFunctionBegin;
7161:   if (numRows) PetscAssertPointer(rows, 3);
7162:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7163:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7164:   MatCheckPreallocated(mat, 1);

7166:   if (mat->ops->zerorowslocal) {
7167:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7168:   } else {
7169:     IS        is, newis;
7170:     PetscInt *newRows, nl = 0;

7172:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7173:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7174:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7175:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7176:     for (PetscInt i = 0; i < numRows; i++)
7177:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7178:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7179:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7180:     PetscCall(ISDestroy(&newis));
7181:     PetscCall(ISDestroy(&is));
7182:   }
7183:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7184:   PetscFunctionReturn(PETSC_SUCCESS);
7185: }

7187: /*@
7188:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7189:   of a set of rows of a matrix; using local numbering of rows.

7191:   Collective

7193:   Input Parameters:
7194: + mat  - the matrix
7195: . is   - index set of rows to remove
7196: . diag - value put in all diagonals of eliminated rows
7197: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7198: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7200:   Level: intermediate

7202:   Notes:
7203:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7204:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7206:   See `MatZeroRows()` for details on how this routine operates.

7208: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7209:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7210: @*/
7211: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7212: {
7213:   PetscInt        numRows;
7214:   const PetscInt *rows;

7216:   PetscFunctionBegin;
7220:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7221:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7222:   MatCheckPreallocated(mat, 1);

7224:   PetscCall(ISGetLocalSize(is, &numRows));
7225:   PetscCall(ISGetIndices(is, &rows));
7226:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7227:   PetscCall(ISRestoreIndices(is, &rows));
7228:   PetscFunctionReturn(PETSC_SUCCESS);
7229: }

7231: /*@
7232:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7233:   of a set of rows and columns of a matrix; using local numbering of rows.

7235:   Collective

7237:   Input Parameters:
7238: + mat     - the matrix
7239: . numRows - the number of rows to remove
7240: . rows    - the global row indices
7241: . diag    - value put in all diagonals of eliminated rows
7242: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7243: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7245:   Level: intermediate

7247:   Notes:
7248:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7249:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7251:   See `MatZeroRowsColumns()` for details on how this routine operates.

7253: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7254:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7255: @*/
7256: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7257: {
7258:   PetscFunctionBegin;
7261:   if (numRows) PetscAssertPointer(rows, 3);
7262:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7263:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7264:   MatCheckPreallocated(mat, 1);

7266:   if (mat->ops->zerorowscolumnslocal) {
7267:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7268:   } else {
7269:     IS        is, newis;
7270:     PetscInt *newRows, nl = 0;

7272:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7273:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7274:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7275:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7276:     for (PetscInt i = 0; i < numRows; i++)
7277:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7278:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7279:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7280:     PetscCall(ISDestroy(&newis));
7281:     PetscCall(ISDestroy(&is));
7282:   }
7283:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7284:   PetscFunctionReturn(PETSC_SUCCESS);
7285: }

7287: /*@
7288:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7289:   of a set of rows and columns of a matrix; using local numbering of rows.

7291:   Collective

7293:   Input Parameters:
7294: + mat  - the matrix
7295: . is   - index set of rows to remove
7296: . diag - value put in all diagonals of eliminated rows
7297: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7298: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7300:   Level: intermediate

7302:   Notes:
7303:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7304:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7306:   See `MatZeroRowsColumns()` for details on how this routine operates.

7308: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7309:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7310: @*/
7311: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7312: {
7313:   PetscInt        numRows;
7314:   const PetscInt *rows;

7316:   PetscFunctionBegin;
7320:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7321:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7322:   MatCheckPreallocated(mat, 1);

7324:   PetscCall(ISGetLocalSize(is, &numRows));
7325:   PetscCall(ISGetIndices(is, &rows));
7326:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7327:   PetscCall(ISRestoreIndices(is, &rows));
7328:   PetscFunctionReturn(PETSC_SUCCESS);
7329: }

7331: /*@
7332:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7334:   Not Collective

7336:   Input Parameter:
7337: . mat - the matrix

7339:   Output Parameters:
7340: + m - the number of global rows
7341: - n - the number of global columns

7343:   Level: beginner

7345:   Note:
7346:   Both output parameters can be `NULL` on input.

7348: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7349: @*/
7350: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7351: {
7352:   PetscFunctionBegin;
7354:   if (m) *m = mat->rmap->N;
7355:   if (n) *n = mat->cmap->N;
7356:   PetscFunctionReturn(PETSC_SUCCESS);
7357: }

7359: /*@
7360:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7361:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7363:   Not Collective

7365:   Input Parameter:
7366: . mat - the matrix

7368:   Output Parameters:
7369: + m - the number of local rows, use `NULL` to not obtain this value
7370: - n - the number of local columns, use `NULL` to not obtain this value

7372:   Level: beginner

7374: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7375: @*/
7376: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7377: {
7378:   PetscFunctionBegin;
7380:   if (m) PetscAssertPointer(m, 2);
7381:   if (n) PetscAssertPointer(n, 3);
7382:   if (m) *m = mat->rmap->n;
7383:   if (n) *n = mat->cmap->n;
7384:   PetscFunctionReturn(PETSC_SUCCESS);
7385: }

7387: /*@
7388:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7389:   vector one multiplies this matrix by that are owned by this process.

7391:   Not Collective, unless matrix has not been allocated, then collective

7393:   Input Parameter:
7394: . mat - the matrix

7396:   Output Parameters:
7397: + m - the global index of the first local column, use `NULL` to not obtain this value
7398: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7400:   Level: developer

7402:   Notes:
7403:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7405:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7406:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7408:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7409:   the local values in the matrix.

7411:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7412:   Layouts](sec_matlayout) for details on matrix layouts.

7414: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7415:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7416: @*/
7417: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7418: {
7419:   PetscFunctionBegin;
7422:   if (m) PetscAssertPointer(m, 2);
7423:   if (n) PetscAssertPointer(n, 3);
7424:   MatCheckPreallocated(mat, 1);
7425:   if (m) *m = mat->cmap->rstart;
7426:   if (n) *n = mat->cmap->rend;
7427:   PetscFunctionReturn(PETSC_SUCCESS);
7428: }

7430: /*@
7431:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7432:   this MPI process.

7434:   Not Collective

7436:   Input Parameter:
7437: . mat - the matrix

7439:   Output Parameters:
7440: + m - the global index of the first local row, use `NULL` to not obtain this value
7441: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7443:   Level: beginner

7445:   Notes:
7446:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7448:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7449:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7451:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7452:   the local values in the matrix.

7454:   The high argument is one more than the last element stored locally.

7456:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7457:   would contain the result of a matrix vector product with this matrix. See [Matrix
7458:   Layouts](sec_matlayout) for details on matrix layouts.

7460: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7461:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7462: @*/
7463: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7464: {
7465:   PetscFunctionBegin;
7468:   if (m) PetscAssertPointer(m, 2);
7469:   if (n) PetscAssertPointer(n, 3);
7470:   MatCheckPreallocated(mat, 1);
7471:   if (m) *m = mat->rmap->rstart;
7472:   if (n) *n = mat->rmap->rend;
7473:   PetscFunctionReturn(PETSC_SUCCESS);
7474: }

7476: /*@
7477:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7478:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7480:   Not Collective, unless matrix has not been allocated

7482:   Input Parameter:
7483: . mat - the matrix

7485:   Output Parameter:
7486: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7487:            where `size` is the number of MPI processes used by `mat`

7489:   Level: beginner

7491:   Notes:
7492:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7494:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7495:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7497:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7498:   the local values in the matrix.

7500:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7501:   would contain the result of a matrix vector product with this matrix. See [Matrix
7502:   Layouts](sec_matlayout) for details on matrix layouts.

7504: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7505:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7506:           `DMDAGetGhostCorners()`, `DM`
7507: @*/
7508: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7509: {
7510:   PetscFunctionBegin;
7513:   MatCheckPreallocated(mat, 1);
7514:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7515:   PetscFunctionReturn(PETSC_SUCCESS);
7516: }

7518: /*@
7519:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7520:   vector one multiplies this vector by that are owned by each process.

7522:   Not Collective, unless matrix has not been allocated

7524:   Input Parameter:
7525: . mat - the matrix

7527:   Output Parameter:
7528: . ranges - start of each process's portion plus one more than the total length at the end

7530:   Level: beginner

7532:   Notes:
7533:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7535:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7536:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7538:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7539:   the local values in the matrix.

7541:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7542:   Layouts](sec_matlayout) for details on matrix layouts.

7544: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7545:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7546:           `DMDAGetGhostCorners()`, `DM`
7547: @*/
7548: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7549: {
7550:   PetscFunctionBegin;
7553:   MatCheckPreallocated(mat, 1);
7554:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7555:   PetscFunctionReturn(PETSC_SUCCESS);
7556: }

7558: /*@
7559:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7561:   Not Collective

7563:   Input Parameter:
7564: . A - matrix

7566:   Output Parameters:
7567: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7568: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7570:   Level: intermediate

7572:   Note:
7573:   You should call `ISDestroy()` on the returned `IS`

7575:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7576:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7577:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7578:   details on matrix layouts.

7580: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7581: @*/
7582: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7583: {
7584:   PetscErrorCode (*f)(Mat, IS *, IS *);

7586:   PetscFunctionBegin;
7589:   MatCheckPreallocated(A, 1);
7590:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7591:   if (f) {
7592:     PetscCall((*f)(A, rows, cols));
7593:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7594:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7595:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7596:   }
7597:   PetscFunctionReturn(PETSC_SUCCESS);
7598: }

7600: /*@
7601:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7602:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7603:   to complete the factorization.

7605:   Collective

7607:   Input Parameters:
7608: + fact - the factorized matrix obtained with `MatGetFactor()`
7609: . mat  - the matrix
7610: . row  - row permutation
7611: . col  - column permutation
7612: - info - structure containing
7613: .vb
7614:       levels - number of levels of fill.
7615:       expected fill - as ratio of original fill.
7616:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7617:                 missing diagonal entries)
7618: .ve

7620:   Level: developer

7622:   Notes:
7623:   See [Matrix Factorization](sec_matfactor) for additional information.

7625:   Most users should employ the `KSP` interface for linear solvers
7626:   instead of working directly with matrix algebra routines such as this.
7627:   See, e.g., `KSPCreate()`.

7629:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

7631:   Fortran Note:
7632:   A valid (non-null) `info` argument must be provided

7634: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7635:           `MatGetOrdering()`, `MatFactorInfo`
7636: @*/
7637: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7638: {
7639:   PetscFunctionBegin;
7644:   PetscAssertPointer(info, 5);
7645:   PetscAssertPointer(fact, 1);
7646:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7647:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7648:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7649:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7650:   MatCheckPreallocated(mat, 2);

7652:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7653:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7654:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7655:   PetscFunctionReturn(PETSC_SUCCESS);
7656: }

7658: /*@
7659:   MatICCFactorSymbolic - Performs symbolic incomplete
7660:   Cholesky factorization for a symmetric matrix. Use
7661:   `MatCholeskyFactorNumeric()` to complete the factorization.

7663:   Collective

7665:   Input Parameters:
7666: + fact - the factorized matrix obtained with `MatGetFactor()`
7667: . mat  - the matrix to be factored
7668: . perm - row and column permutation
7669: - info - structure containing
7670: .vb
7671:       levels - number of levels of fill.
7672:       expected fill - as ratio of original fill.
7673: .ve

7675:   Level: developer

7677:   Notes:
7678:   Most users should employ the `KSP` interface for linear solvers
7679:   instead of working directly with matrix algebra routines such as this.
7680:   See, e.g., `KSPCreate()`.

7682:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

7684:   Fortran Note:
7685:   A valid (non-null) `info` argument must be provided

7687: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7688: @*/
7689: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7690: {
7691:   PetscFunctionBegin;
7695:   PetscAssertPointer(info, 4);
7696:   PetscAssertPointer(fact, 1);
7697:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7698:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7699:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7700:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7701:   MatCheckPreallocated(mat, 2);

7703:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7704:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7705:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7706:   PetscFunctionReturn(PETSC_SUCCESS);
7707: }

7709: /*@
7710:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7711:   points to an array of valid matrices, they may be reused to store the new
7712:   submatrices.

7714:   Collective

7716:   Input Parameters:
7717: + mat   - the matrix
7718: . n     - the number of submatrixes to be extracted (on this process, may be zero)
7719: . irow  - index set of rows to extract
7720: . icol  - index set of columns to extract
7721: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7723:   Output Parameter:
7724: . submat - the array of submatrices

7726:   Level: advanced

7728:   Notes:
7729:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7730:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7731:   to extract a parallel submatrix.

7733:   Some matrix types place restrictions on the row and column
7734:   indices, such as that they be sorted or that they be equal to each other.
7735:   `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.

7737:   The index sets may not have duplicate entries.

7739:   When extracting submatrices from a parallel matrix, each process can
7740:   form a different submatrix by setting the rows and columns of its
7741:   individual index sets according to the local submatrix desired.

7743:   When finished using the submatrices, the user should destroy
7744:   them with `MatDestroySubMatrices()`.

7746:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7747:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7749:   This routine creates the matrices in submat; you should NOT create them before
7750:   calling it. It also allocates the array of matrix pointers submat.

7752:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7753:   request one row/column in a block, they must request all rows/columns that are in
7754:   that block. For example, if the block size is 2 you cannot request just row 0 and
7755:   column 0.

7757:   Fortran Note:
7758: .vb
7759:   Mat, pointer :: submat(:)
7760: .ve

7762: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7763: @*/
7764: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7765: {
7766:   PetscInt  i;
7767:   PetscBool eq;

7769:   PetscFunctionBegin;
7772:   if (n) {
7773:     PetscAssertPointer(irow, 3);
7775:     PetscAssertPointer(icol, 4);
7777:   }
7778:   PetscAssertPointer(submat, 6);
7779:   if (n && scall == MAT_REUSE_MATRIX) {
7780:     PetscAssertPointer(*submat, 6);
7782:   }
7783:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7784:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7785:   MatCheckPreallocated(mat, 1);
7786:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7787:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7788:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7789:   for (i = 0; i < n; i++) {
7790:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7791:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7792:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7793: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7794:     if (mat->boundtocpu && mat->bindingpropagates) {
7795:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7796:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7797:     }
7798: #endif
7799:   }
7800:   PetscFunctionReturn(PETSC_SUCCESS);
7801: }

7803: /*@
7804:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7806:   Collective

7808:   Input Parameters:
7809: + mat   - the matrix
7810: . n     - the number of submatrixes to be extracted
7811: . irow  - index set of rows to extract
7812: . icol  - index set of columns to extract
7813: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7815:   Output Parameter:
7816: . submat - the array of submatrices

7818:   Level: advanced

7820:   Note:
7821:   This is used by `PCGASM`

7823: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7824: @*/
7825: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7826: {
7827:   PetscInt  i;
7828:   PetscBool eq;

7830:   PetscFunctionBegin;
7833:   if (n) {
7834:     PetscAssertPointer(irow, 3);
7836:     PetscAssertPointer(icol, 4);
7838:   }
7839:   PetscAssertPointer(submat, 6);
7840:   if (n && scall == MAT_REUSE_MATRIX) {
7841:     PetscAssertPointer(*submat, 6);
7843:   }
7844:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7845:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7846:   MatCheckPreallocated(mat, 1);

7848:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7849:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7850:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7851:   for (i = 0; i < n; i++) {
7852:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7853:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7854:   }
7855:   PetscFunctionReturn(PETSC_SUCCESS);
7856: }

7858: /*@
7859:   MatDestroyMatrices - Destroys an array of matrices

7861:   Collective

7863:   Input Parameters:
7864: + n   - the number of local matrices
7865: - mat - the matrices (this is a pointer to the array of matrices)

7867:   Level: advanced

7869:   Notes:
7870:   Frees not only the matrices, but also the array that contains the matrices

7872:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7874: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7875: @*/
7876: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7877: {
7878:   PetscInt i;

7880:   PetscFunctionBegin;
7881:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7882:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7883:   PetscAssertPointer(mat, 2);

7885:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7887:   /* memory is allocated even if n = 0 */
7888:   PetscCall(PetscFree(*mat));
7889:   PetscFunctionReturn(PETSC_SUCCESS);
7890: }

7892: /*@
7893:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7895:   Collective

7897:   Input Parameters:
7898: + n   - the number of local matrices
7899: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7901:   Level: advanced

7903:   Note:
7904:   Frees not only the matrices, but also the array that contains the matrices

7906: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7907: @*/
7908: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7909: {
7910:   Mat mat0;

7912:   PetscFunctionBegin;
7913:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7914:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7915:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7916:   PetscAssertPointer(mat, 2);

7918:   mat0 = (*mat)[0];
7919:   if (mat0 && mat0->ops->destroysubmatrices) {
7920:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7921:   } else {
7922:     PetscCall(MatDestroyMatrices(n, mat));
7923:   }
7924:   PetscFunctionReturn(PETSC_SUCCESS);
7925: }

7927: /*@
7928:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7930:   Collective

7932:   Input Parameter:
7933: . mat - the matrix

7935:   Output Parameter:
7936: . matstruct - the sequential matrix with the nonzero structure of `mat`

7938:   Level: developer

7940: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7941: @*/
7942: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7943: {
7944:   PetscFunctionBegin;
7946:   PetscAssertPointer(matstruct, 2);

7949:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7950:   MatCheckPreallocated(mat, 1);

7952:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7953:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7954:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7955:   PetscFunctionReturn(PETSC_SUCCESS);
7956: }

7958: /*@
7959:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7961:   Collective

7963:   Input Parameter:
7964: . mat - the matrix

7966:   Level: advanced

7968:   Note:
7969:   This is not needed, one can just call `MatDestroy()`

7971: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7972: @*/
7973: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7974: {
7975:   PetscFunctionBegin;
7976:   PetscAssertPointer(mat, 1);
7977:   PetscCall(MatDestroy(mat));
7978:   PetscFunctionReturn(PETSC_SUCCESS);
7979: }

7981: /*@
7982:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7983:   replaces the index sets by larger ones that represent submatrices with
7984:   additional overlap.

7986:   Collective

7988:   Input Parameters:
7989: + mat - the matrix
7990: . n   - the number of index sets
7991: . is  - the array of index sets (these index sets will changed during the call)
7992: - ov  - the additional overlap requested

7994:   Options Database Key:
7995: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7997:   Level: developer

7999:   Note:
8000:   The computed overlap preserves the matrix block sizes when the blocks are square.
8001:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
8002:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

8004: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
8005: @*/
8006: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
8007: {
8008:   PetscInt i, bs, cbs;

8010:   PetscFunctionBegin;
8014:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8015:   if (n) {
8016:     PetscAssertPointer(is, 3);
8018:   }
8019:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8020:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8021:   MatCheckPreallocated(mat, 1);

8023:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
8024:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8025:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
8026:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8027:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
8028:   if (bs == cbs) {
8029:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
8030:   }
8031:   PetscFunctionReturn(PETSC_SUCCESS);
8032: }

8034: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

8036: /*@
8037:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
8038:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
8039:   additional overlap.

8041:   Collective

8043:   Input Parameters:
8044: + mat - the matrix
8045: . n   - the number of index sets
8046: . is  - the array of index sets (these index sets will changed during the call)
8047: - ov  - the additional overlap requested

8049:   `   Options Database Key:
8050: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

8052:   Level: developer

8054: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
8055: @*/
8056: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
8057: {
8058:   PetscInt i;

8060:   PetscFunctionBegin;
8063:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8064:   if (n) {
8065:     PetscAssertPointer(is, 3);
8067:   }
8068:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8069:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8070:   MatCheckPreallocated(mat, 1);
8071:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
8072:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8073:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
8074:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8075:   PetscFunctionReturn(PETSC_SUCCESS);
8076: }

8078: /*@
8079:   MatGetBlockSize - Returns the matrix block size.

8081:   Not Collective

8083:   Input Parameter:
8084: . mat - the matrix

8086:   Output Parameter:
8087: . bs - block size

8089:   Level: intermediate

8091:   Notes:
8092:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8094:   If the block size has not been set yet this routine returns 1.

8096: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8097: @*/
8098: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8099: {
8100:   PetscFunctionBegin;
8102:   PetscAssertPointer(bs, 2);
8103:   *bs = mat->rmap->bs;
8104:   PetscFunctionReturn(PETSC_SUCCESS);
8105: }

8107: /*@
8108:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8110:   Not Collective

8112:   Input Parameter:
8113: . mat - the matrix

8115:   Output Parameters:
8116: + rbs - row block size
8117: - cbs - column block size

8119:   Level: intermediate

8121:   Notes:
8122:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8123:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8125:   If a block size has not been set yet this routine returns 1.

8127: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8128: @*/
8129: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8130: {
8131:   PetscFunctionBegin;
8133:   if (rbs) PetscAssertPointer(rbs, 2);
8134:   if (cbs) PetscAssertPointer(cbs, 3);
8135:   if (rbs) *rbs = mat->rmap->bs;
8136:   if (cbs) *cbs = mat->cmap->bs;
8137:   PetscFunctionReturn(PETSC_SUCCESS);
8138: }

8140: /*@
8141:   MatSetBlockSize - Sets the matrix block size.

8143:   Logically Collective

8145:   Input Parameters:
8146: + mat - the matrix
8147: - bs  - block size

8149:   Level: intermediate

8151:   Notes:
8152:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8153:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8155:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8156:   is compatible with the matrix local sizes.

8158: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8159: @*/
8160: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8161: {
8162:   PetscFunctionBegin;
8165:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8166:   PetscFunctionReturn(PETSC_SUCCESS);
8167: }

8169: typedef struct {
8170:   PetscInt         n;
8171:   IS              *is;
8172:   Mat             *mat;
8173:   PetscObjectState nonzerostate;
8174:   Mat              C;
8175: } EnvelopeData;

8177: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8178: {
8179:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8181:   PetscFunctionBegin;
8182:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8183:   PetscCall(PetscFree(edata->is));
8184:   PetscCall(PetscFree(edata));
8185:   PetscFunctionReturn(PETSC_SUCCESS);
8186: }

8188: /*@
8189:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8190:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8192:   Collective

8194:   Input Parameter:
8195: . mat - the matrix

8197:   Level: intermediate

8199:   Notes:
8200:   There can be zeros within the blocks

8202:   The blocks can overlap between processes, including laying on more than two processes

8204: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8205: @*/
8206: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8207: {
8208:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8209:   PetscInt          *diag, *odiag, sc;
8210:   VecScatter         scatter;
8211:   PetscScalar       *seqv;
8212:   const PetscScalar *parv;
8213:   const PetscInt    *ia, *ja;
8214:   PetscBool          set, flag, done;
8215:   Mat                AA = mat, A;
8216:   MPI_Comm           comm;
8217:   PetscMPIInt        rank, size, tag;
8218:   MPI_Status         status;
8219:   PetscContainer     container;
8220:   EnvelopeData      *edata;
8221:   Vec                seq, par;
8222:   IS                 isglobal;

8224:   PetscFunctionBegin;
8226:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8227:   if (!set || !flag) {
8228:     /* TODO: only needs nonzero structure of transpose */
8229:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8230:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8231:   }
8232:   PetscCall(MatAIJGetLocalMat(AA, &A));
8233:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8234:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8236:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8237:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8238:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8239:   PetscCallMPI(MPI_Comm_size(comm, &size));
8240:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8242:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8244:   if (rank > 0) {
8245:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8246:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8247:   }
8248:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8249:   for (i = 0; i < n; i++) {
8250:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8251:     II  = rstart + i;
8252:     if (env == II) {
8253:       starts[lblocks]  = tbs;
8254:       sizes[lblocks++] = 1 + II - tbs;
8255:       tbs              = 1 + II;
8256:     }
8257:   }
8258:   if (rank < size - 1) {
8259:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8260:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8261:   }

8263:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8264:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8265:   PetscCall(MatDestroy(&A));

8267:   PetscCall(PetscNew(&edata));
8268:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8269:   edata->n = lblocks;
8270:   /* create IS needed for extracting blocks from the original matrix */
8271:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8272:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8274:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8275:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8276:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8277:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8278:   PetscCall(MatSetType(edata->C, MATAIJ));

8280:   /* Communicate the start and end of each row, from each block to the correct rank */
8281:   /* TODO: Use PetscSF instead of VecScatter */
8282:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8283:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8284:   PetscCall(VecGetArrayWrite(seq, &seqv));
8285:   for (PetscInt i = 0; i < lblocks; i++) {
8286:     for (PetscInt j = 0; j < sizes[i]; j++) {
8287:       seqv[cnt]     = starts[i];
8288:       seqv[cnt + 1] = starts[i] + sizes[i];
8289:       cnt += 2;
8290:     }
8291:   }
8292:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
8293:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8294:   sc -= cnt;
8295:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8296:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8297:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8298:   PetscCall(ISDestroy(&isglobal));
8299:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8300:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8301:   PetscCall(VecScatterDestroy(&scatter));
8302:   PetscCall(VecDestroy(&seq));
8303:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8304:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8305:   PetscCall(VecGetArrayRead(par, &parv));
8306:   cnt = 0;
8307:   PetscCall(MatGetSize(mat, NULL, &n));
8308:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8309:     PetscInt start, end, d = 0, od = 0;

8311:     start = (PetscInt)PetscRealPart(parv[cnt]);
8312:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
8313:     cnt += 2;

8315:     if (start < cstart) {
8316:       od += cstart - start + n - cend;
8317:       d += cend - cstart;
8318:     } else if (start < cend) {
8319:       od += n - cend;
8320:       d += cend - start;
8321:     } else od += n - start;
8322:     if (end <= cstart) {
8323:       od -= cstart - end + n - cend;
8324:       d -= cend - cstart;
8325:     } else if (end < cend) {
8326:       od -= n - cend;
8327:       d -= cend - end;
8328:     } else od -= n - end;

8330:     odiag[i] = od;
8331:     diag[i]  = d;
8332:   }
8333:   PetscCall(VecRestoreArrayRead(par, &parv));
8334:   PetscCall(VecDestroy(&par));
8335:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8336:   PetscCall(PetscFree2(diag, odiag));
8337:   PetscCall(PetscFree2(sizes, starts));

8339:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8340:   PetscCall(PetscContainerSetPointer(container, edata));
8341:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8342:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8343:   PetscCall(PetscObjectDereference((PetscObject)container));
8344:   PetscFunctionReturn(PETSC_SUCCESS);
8345: }

8347: /*@
8348:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8350:   Collective

8352:   Input Parameters:
8353: + A     - the matrix
8354: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8356:   Output Parameter:
8357: . C - matrix with inverted block diagonal of `A`

8359:   Level: advanced

8361:   Note:
8362:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8364: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8365: @*/
8366: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8367: {
8368:   PetscContainer   container;
8369:   EnvelopeData    *edata;
8370:   PetscObjectState nonzerostate;

8372:   PetscFunctionBegin;
8373:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8374:   if (!container) {
8375:     PetscCall(MatComputeVariableBlockEnvelope(A));
8376:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8377:   }
8378:   PetscCall(PetscContainerGetPointer(container, &edata));
8379:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8380:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8381:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8383:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8384:   *C = edata->C;

8386:   for (PetscInt i = 0; i < edata->n; i++) {
8387:     Mat          D;
8388:     PetscScalar *dvalues;

8390:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8391:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8392:     PetscCall(MatSeqDenseInvert(D));
8393:     PetscCall(MatDenseGetArray(D, &dvalues));
8394:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8395:     PetscCall(MatDestroy(&D));
8396:   }
8397:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8398:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8399:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8400:   PetscFunctionReturn(PETSC_SUCCESS);
8401: }

8403: /*@
8404:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8406:   Not Collective

8408:   Input Parameters:
8409: + mat     - the matrix
8410: . nblocks - the number of blocks on this process, each block can only exist on a single MPI process
8411: - bsizes  - the block sizes

8413:   Level: intermediate

8415:   Note:
8416:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8418: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8419:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8420: @*/
8421: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8422: {
8423:   PetscInt ncnt = 0, nlocal;

8425:   PetscFunctionBegin;
8427:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8428:   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);
8429:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8430:   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);
8431:   PetscCall(PetscFree(mat->bsizes));
8432:   mat->nblocks = nblocks;
8433:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8434:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8435:   PetscFunctionReturn(PETSC_SUCCESS);
8436: }

8438: /*@
8439:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8441:   Not Collective; No Fortran Support

8443:   Input Parameter:
8444: . mat - the matrix

8446:   Output Parameters:
8447: + nblocks - the number of blocks on this process
8448: - bsizes  - the block sizes

8450:   Level: intermediate

8452: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8453: @*/
8454: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8455: {
8456:   PetscFunctionBegin;
8458:   if (nblocks) *nblocks = mat->nblocks;
8459:   if (bsizes) *bsizes = mat->bsizes;
8460:   PetscFunctionReturn(PETSC_SUCCESS);
8461: }

8463: /*@
8464:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8466:   Not Collective

8468:   Input Parameters:
8469: + subA  - the submatrix
8470: . A     - the original matrix
8471: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8473:   Level: developer

8475:   Note:
8476:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8478: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8479: @*/
8480: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8481: {
8482:   const PetscInt *rows;
8483:   PetscInt        n, rStart, rEnd, Nb = 0;
8484:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8486:   PetscFunctionBegin;
8487:   // The code for block size extraction does not support an unsorted IS
8488:   if (flg) PetscCall(ISSorted(isrow, &flg));
8489:   // We don't support originally off-diagonal blocks
8490:   if (flg) {
8491:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8492:     PetscCall(ISGetLocalSize(isrow, &n));
8493:     PetscCall(ISGetIndices(isrow, &rows));
8494:     for (PetscInt i = 0; i < n && flg; ++i) {
8495:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8496:     }
8497:     PetscCall(ISRestoreIndices(isrow, &rows));
8498:   }
8499:   // quiet return if we can't extract block size
8500:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8501:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8503:   // extract block sizes
8504:   PetscCall(ISGetIndices(isrow, &rows));
8505:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8506:     PetscBool occupied = PETSC_FALSE;

8508:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8509:       const PetscInt row = gr + br;

8511:       if (i == n) break;
8512:       if (rows[i] == row) {
8513:         occupied = PETSC_TRUE;
8514:         ++i;
8515:       }
8516:       while (i < n && rows[i] < row) ++i;
8517:     }
8518:     gr += A->bsizes[b];
8519:     if (occupied) ++Nb;
8520:   }
8521:   subA->nblocks = Nb;
8522:   PetscCall(PetscFree(subA->bsizes));
8523:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8524:   PetscInt sb = 0;
8525:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8526:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8527:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8528:       const PetscInt row = gr + br;

8530:       if (i == n) break;
8531:       if (rows[i] == row) {
8532:         ++subA->bsizes[sb];
8533:         ++i;
8534:       }
8535:       while (i < n && rows[i] < row) ++i;
8536:     }
8537:     gr += A->bsizes[b];
8538:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8539:   }
8540:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8541:   PetscInt nlocal, ncnt = 0;
8542:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8543:   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);
8544:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8545:   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);
8546:   PetscCall(ISRestoreIndices(isrow, &rows));
8547:   PetscFunctionReturn(PETSC_SUCCESS);
8548: }

8550: /*@
8551:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8553:   Logically Collective

8555:   Input Parameters:
8556: + mat - the matrix
8557: . rbs - row block size
8558: - cbs - column block size

8560:   Level: intermediate

8562:   Notes:
8563:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8564:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8565:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8567:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8568:   are compatible with the matrix local sizes.

8570:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8572: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8573: @*/
8574: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8575: {
8576:   PetscFunctionBegin;
8580:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8581:   if (mat->rmap->refcnt) {
8582:     ISLocalToGlobalMapping l2g  = NULL;
8583:     PetscLayout            nmap = NULL;

8585:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8586:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8587:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8588:     mat->rmap          = nmap;
8589:     mat->rmap->mapping = l2g;
8590:   }
8591:   if (mat->cmap->refcnt) {
8592:     ISLocalToGlobalMapping l2g  = NULL;
8593:     PetscLayout            nmap = NULL;

8595:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8596:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8597:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8598:     mat->cmap          = nmap;
8599:     mat->cmap->mapping = l2g;
8600:   }
8601:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8602:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8603:   PetscFunctionReturn(PETSC_SUCCESS);
8604: }

8606: /*@
8607:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8609:   Logically Collective

8611:   Input Parameters:
8612: + mat     - the matrix
8613: . fromRow - matrix from which to copy row block size
8614: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8616:   Level: developer

8618: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8619: @*/
8620: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8621: {
8622:   PetscFunctionBegin;
8626:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8627:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8628:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8629:   PetscFunctionReturn(PETSC_SUCCESS);
8630: }

8632: /*@
8633:   MatResidual - Default routine to calculate the residual $r = b - Ax$

8635:   Collective

8637:   Input Parameters:
8638: + mat - the matrix
8639: . b   - the right-hand-side
8640: - x   - the approximate solution

8642:   Output Parameter:
8643: . r - location to store the residual

8645:   Level: developer

8647: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8648: @*/
8649: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8650: {
8651:   PetscFunctionBegin;
8657:   MatCheckPreallocated(mat, 1);
8658:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8659:   if (!mat->ops->residual) {
8660:     PetscCall(MatMult(mat, x, r));
8661:     PetscCall(VecAYPX(r, -1.0, b));
8662:   } else {
8663:     PetscUseTypeMethod(mat, residual, b, x, r);
8664:   }
8665:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8666:   PetscFunctionReturn(PETSC_SUCCESS);
8667: }

8669: /*@
8670:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8672:   Collective

8674:   Input Parameters:
8675: + mat             - the matrix
8676: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8677: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8678: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8679:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8680:                     always used.

8682:   Output Parameters:
8683: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8684: . 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
8685: . ja   - the column indices, use `NULL` if not needed
8686: - done - indicates if the routine actually worked and returned appropriate `ia` and `ja` arrays; callers
8687:          are responsible for handling the case when done is `PETSC_FALSE` and `ia` and `ja` are not provided

8689:   Level: developer

8691:   Notes:
8692:   You CANNOT change any of the `ia` or `ja` values.

8694:   Use `MatRestoreRowIJ()` when you are finished accessing the `ia` and `ja` values.

8696:   Fortran Notes:
8697:   Use
8698: .vb
8699:     PetscInt, pointer :: ia(:),ja(:)
8700:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8701:     ! Access the ith and jth entries via ia(i) and ja(j)
8702: .ve

8704: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8705: @*/
8706: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8707: {
8708:   PetscFunctionBegin;
8711:   if (n) PetscAssertPointer(n, 5);
8712:   if (ia) PetscAssertPointer(ia, 6);
8713:   if (ja) PetscAssertPointer(ja, 7);
8714:   if (done) PetscAssertPointer(done, 8);
8715:   MatCheckPreallocated(mat, 1);
8716:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8717:   else {
8718:     if (done) *done = PETSC_TRUE;
8719:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8720:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8721:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8722:   }
8723:   PetscFunctionReturn(PETSC_SUCCESS);
8724: }

8726: /*@
8727:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8729:   Collective

8731:   Input Parameters:
8732: + mat             - the matrix
8733: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8734: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8735:                     symmetrized
8736: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8737:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8738:                     always used.

8740:   Output Parameters:
8741: + n    - number of columns in the (possibly compressed) matrix
8742: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8743: . ja   - the row indices
8744: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8746:   Level: developer

8748: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8749: @*/
8750: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8751: {
8752:   PetscFunctionBegin;
8755:   PetscAssertPointer(n, 5);
8756:   if (ia) PetscAssertPointer(ia, 6);
8757:   if (ja) PetscAssertPointer(ja, 7);
8758:   PetscAssertPointer(done, 8);
8759:   MatCheckPreallocated(mat, 1);
8760:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8761:   else {
8762:     *done = PETSC_TRUE;
8763:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8764:   }
8765:   PetscFunctionReturn(PETSC_SUCCESS);
8766: }

8768: /*@
8769:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8771:   Collective

8773:   Input Parameters:
8774: + mat             - the matrix
8775: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8776: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8777: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8778:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8779:                     always used.
8780: . n               - size of (possibly compressed) matrix, or `NULL`
8781: . ia              - the row pointers, or `NULL`
8782: - ja              - the column indices, or `NULL`

8784:   Output Parameter:
8785: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8787:   Level: developer

8789:   Note:
8790:   This routine zeros out `n`, `ia`, and `ja` if they are provided. Use of `ia` or `ja` after `MatRestoreRowIJ()` is always invalid.

8792: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8793: @*/
8794: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8795: {
8796:   PetscFunctionBegin;
8799:   if (ia) PetscAssertPointer(ia, 6);
8800:   if (ja) PetscAssertPointer(ja, 7);
8801:   if (done) PetscAssertPointer(done, 8);
8802:   MatCheckPreallocated(mat, 1);

8804:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8805:   else {
8806:     if (done) *done = PETSC_TRUE;
8807:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8808:     if (n) *n = 0;
8809:     if (ia) *ia = NULL;
8810:     if (ja) *ja = NULL;
8811:   }
8812:   PetscFunctionReturn(PETSC_SUCCESS);
8813: }

8815: /*@
8816:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8818:   Collective

8820:   Input Parameters:
8821: + mat             - the matrix
8822: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8823: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8824: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8825:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8826:                     always used.

8828:   Output Parameters:
8829: + n    - size of (possibly compressed) matrix
8830: . ia   - the column pointers
8831: . ja   - the row indices
8832: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8834:   Level: developer

8836: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8837: @*/
8838: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8839: {
8840:   PetscFunctionBegin;
8843:   if (ia) PetscAssertPointer(ia, 6);
8844:   if (ja) PetscAssertPointer(ja, 7);
8845:   PetscAssertPointer(done, 8);
8846:   MatCheckPreallocated(mat, 1);

8848:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8849:   else {
8850:     *done = PETSC_TRUE;
8851:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8852:     if (n) *n = 0;
8853:     if (ia) *ia = NULL;
8854:     if (ja) *ja = NULL;
8855:   }
8856:   PetscFunctionReturn(PETSC_SUCCESS);
8857: }

8859: /*@
8860:   MatColoringPatch - Utility routine used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8861:   `MatGetColumnIJ()`.

8863:   Collective

8865:   Input Parameters:
8866: + mat        - the matrix
8867: . ncolors    - maximum color value
8868: . n          - number of entries in `colorarray`
8869: - colorarray - array indicating color for each column

8871:   Output Parameter:
8872: . iscoloring - coloring generated using `colorarray` information

8874:   Level: developer

8876: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8877: @*/
8878: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8879: {
8880:   PetscFunctionBegin;
8883:   PetscAssertPointer(colorarray, 4);
8884:   PetscAssertPointer(iscoloring, 5);
8885:   MatCheckPreallocated(mat, 1);

8887:   if (!mat->ops->coloringpatch) {
8888:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8889:   } else {
8890:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8891:   }
8892:   PetscFunctionReturn(PETSC_SUCCESS);
8893: }

8895: /*@
8896:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8898:   Logically Collective

8900:   Input Parameter:
8901: . mat - the factored matrix to be reset

8903:   Level: developer

8905:   Notes:
8906:   This routine should be used only with factored matrices formed by in-place
8907:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8908:   format). This option can save memory, for example, when solving nonlinear
8909:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8910:   ILU(0) preconditioner.

8912:   One can specify in-place ILU(0) factorization by calling
8913: .vb
8914:      PCType(pc,PCILU);
8915:      PCFactorSeUseInPlace(pc);
8916: .ve
8917:   or by using the options -pc_type ilu -pc_factor_in_place

8919:   In-place factorization ILU(0) can also be used as a local
8920:   solver for the blocks within the block Jacobi or additive Schwarz
8921:   methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8922:   for details on setting local solver options.

8924:   Most users should employ the `KSP` interface for linear solvers
8925:   instead of working directly with matrix algebra routines such as this.
8926:   See, e.g., `KSPCreate()`.

8928: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8929: @*/
8930: PetscErrorCode MatSetUnfactored(Mat mat)
8931: {
8932:   PetscFunctionBegin;
8935:   MatCheckPreallocated(mat, 1);
8936:   mat->factortype = MAT_FACTOR_NONE;
8937:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8938:   PetscUseTypeMethod(mat, setunfactored);
8939:   PetscFunctionReturn(PETSC_SUCCESS);
8940: }

8942: /*@
8943:   MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8944:   as the original matrix.

8946:   Collective

8948:   Input Parameters:
8949: + mat   - the original matrix
8950: . isrow - parallel `IS` containing the rows this process should obtain
8951: . 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.
8952: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8954:   Output Parameter:
8955: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)

8957:   Level: advanced

8959:   Notes:
8960:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8962:   Some matrix types place restrictions on the row and column indices, such
8963:   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;
8964:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8965:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.

8967:   The index sets may not have duplicate entries.

8969:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8970:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8971:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8972:   will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8973:   you are finished using it.

8975:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8976:   the input matrix.

8978:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8980:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8981:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8983:   Example usage:
8984:   Consider the following 8x8 matrix with 34 non-zero values, that is
8985:   assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8986:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8987:   as follows
8988: .vb
8989:             1  2  0  |  0  3  0  |  0  4
8990:     Proc0   0  5  6  |  7  0  0  |  8  0
8991:             9  0 10  | 11  0  0  | 12  0
8992:     -------------------------------------
8993:            13  0 14  | 15 16 17  |  0  0
8994:     Proc1   0 18  0  | 19 20 21  |  0  0
8995:             0  0  0  | 22 23  0  | 24  0
8996:     -------------------------------------
8997:     Proc2  25 26 27  |  0  0 28  | 29  0
8998:            30  0  0  | 31 32 33  |  0 34
8999: .ve

9001:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is

9003: .vb
9004:             2  0  |  0  3  0  |  0
9005:     Proc0   5  6  |  7  0  0  |  8
9006:     -------------------------------
9007:     Proc1  18  0  | 19 20 21  |  0
9008:     -------------------------------
9009:     Proc2  26 27  |  0  0 28  | 29
9010:             0  0  | 31 32 33  |  0
9011: .ve

9013: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
9014: @*/
9015: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
9016: {
9017:   PetscMPIInt size;
9018:   Mat        *local;
9019:   IS          iscoltmp;
9020:   PetscBool   flg;

9022:   PetscFunctionBegin;
9026:   PetscAssertPointer(newmat, 5);
9029:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9030:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
9031:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

9033:   MatCheckPreallocated(mat, 1);
9034:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

9036:   if (!iscol || isrow == iscol) {
9037:     PetscBool   stride;
9038:     PetscMPIInt grab = 0;
9039:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
9040:     if (stride) {
9041:       PetscInt first, step, n, rstart, rend;
9042:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
9043:       if (step == 1) {
9044:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
9045:         if (rstart == first) {
9046:           PetscCall(ISGetLocalSize(isrow, &n));
9047:           if (n == rend - rstart) grab = 1;
9048:         }
9049:       }
9050:     }
9051:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
9052:     if (grab) {
9053:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
9054:       if (cll == MAT_INITIAL_MATRIX) {
9055:         *newmat = mat;
9056:         PetscCall(PetscObjectReference((PetscObject)mat));
9057:       }
9058:       PetscFunctionReturn(PETSC_SUCCESS);
9059:     }
9060:   }

9062:   if (!iscol) {
9063:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
9064:   } else {
9065:     iscoltmp = iscol;
9066:   }

9068:   /* if original matrix is on just one process then use submatrix generated */
9069:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
9070:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
9071:     goto setproperties;
9072:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
9073:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
9074:     *newmat = *local;
9075:     PetscCall(PetscFree(local));
9076:     goto setproperties;
9077:   } else if (!mat->ops->createsubmatrix) {
9078:     /* Create a new matrix type that implements the operation using the full matrix */
9079:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9080:     switch (cll) {
9081:     case MAT_INITIAL_MATRIX:
9082:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9083:       break;
9084:     case MAT_REUSE_MATRIX:
9085:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9086:       break;
9087:     default:
9088:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9089:     }
9090:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9091:     goto setproperties;
9092:   }

9094:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9095:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9096:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9098: setproperties:
9099:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9100:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9101:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9102:   }
9103:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9104:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9105:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9106:   PetscFunctionReturn(PETSC_SUCCESS);
9107: }

9109: /*@
9110:   MatPropagateSymmetryOptions - Propagates symmetry properties set on a matrix to another matrix

9112:   Not Collective

9114:   Input Parameters:
9115: + A - the matrix we wish to propagate properties from
9116: - B - the matrix we wish to propagate properties to

9118:   Level: beginner

9120:   Note:
9121:   Propagates the properties associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9123: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9124: @*/
9125: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9126: {
9127:   PetscFunctionBegin;
9130:   B->symmetry_eternal            = A->symmetry_eternal;
9131:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9132:   B->symmetric                   = A->symmetric;
9133:   B->structurally_symmetric      = A->structurally_symmetric;
9134:   B->spd                         = A->spd;
9135:   B->hermitian                   = A->hermitian;
9136:   PetscFunctionReturn(PETSC_SUCCESS);
9137: }

9139: /*@
9140:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9141:   used during the assembly process to store values that belong to
9142:   other processes.

9144:   Not Collective

9146:   Input Parameters:
9147: + mat   - the matrix
9148: . size  - the initial size of the stash.
9149: - bsize - the initial size of the block-stash(if used).

9151:   Options Database Key:
9152: . -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

9154:   Level: intermediate

9156:   Notes:
9157:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9158:   the stash is used for values set with `MatSetValues()`

9160:   Run with the option `-info` and look for output of the form
9161:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9162:   to determine the appropriate value, MM, to use for size and
9163:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9164:   to determine the value, BMM to use for bsize

9166: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9167: @*/
9168: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9169: {
9170:   PetscFunctionBegin;
9173:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9174:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9175:   PetscFunctionReturn(PETSC_SUCCESS);
9176: }

9178: /*@
9179:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9180:   the matrix

9182:   Neighbor-wise Collective

9184:   Input Parameters:
9185: + A - the matrix
9186: . x - the vector to be multiplied by the interpolation operator
9187: - y - the vector to be added to the result

9189:   Output Parameter:
9190: . w - the resulting vector

9192:   Level: intermediate

9194:   Notes:
9195:   `w` may be the same vector as `y`.

9197:   This allows one to use either the restriction or interpolation (its transpose)
9198:   matrix to do the interpolation

9200: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9201: @*/
9202: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9203: {
9204:   PetscInt M, N, Ny;

9206:   PetscFunctionBegin;
9211:   PetscCall(MatGetSize(A, &M, &N));
9212:   PetscCall(VecGetSize(y, &Ny));
9213:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9214:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9215:   PetscFunctionReturn(PETSC_SUCCESS);
9216: }

9218: /*@
9219:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9220:   the matrix

9222:   Neighbor-wise Collective

9224:   Input Parameters:
9225: + A - the matrix
9226: - x - the vector to be interpolated

9228:   Output Parameter:
9229: . y - the resulting vector

9231:   Level: intermediate

9233:   Note:
9234:   This allows one to use either the restriction or interpolation (its transpose)
9235:   matrix to do the interpolation

9237: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9238: @*/
9239: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9240: {
9241:   PetscInt M, N, Ny;

9243:   PetscFunctionBegin;
9247:   PetscCall(MatGetSize(A, &M, &N));
9248:   PetscCall(VecGetSize(y, &Ny));
9249:   if (M == Ny) PetscCall(MatMult(A, x, y));
9250:   else PetscCall(MatMultTranspose(A, x, y));
9251:   PetscFunctionReturn(PETSC_SUCCESS);
9252: }

9254: /*@
9255:   MatRestrict - $y = A*x$ or $A^T*x$

9257:   Neighbor-wise Collective

9259:   Input Parameters:
9260: + A - the matrix
9261: - x - the vector to be restricted

9263:   Output Parameter:
9264: . y - the resulting vector

9266:   Level: intermediate

9268:   Note:
9269:   This allows one to use either the restriction or interpolation (its transpose)
9270:   matrix to do the restriction

9272: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9273: @*/
9274: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9275: {
9276:   PetscInt M, N, Nx;

9278:   PetscFunctionBegin;
9282:   PetscCall(MatGetSize(A, &M, &N));
9283:   PetscCall(VecGetSize(x, &Nx));
9284:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9285:   else PetscCall(MatMult(A, x, y));
9286:   PetscFunctionReturn(PETSC_SUCCESS);
9287: }

9289: /*@
9290:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

9292:   Neighbor-wise Collective

9294:   Input Parameters:
9295: + A - the matrix
9296: . x - the input dense matrix to be multiplied
9297: - w - the input dense matrix to be added to the result

9299:   Output Parameter:
9300: . y - the output dense matrix

9302:   Level: intermediate

9304:   Note:
9305:   This allows one to use either the restriction or interpolation (its transpose)
9306:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9307:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9309: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9310: @*/
9311: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9312: {
9313:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9314:   PetscBool trans = PETSC_TRUE;
9315:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9317:   PetscFunctionBegin;
9323:   PetscCall(MatGetSize(A, &M, &N));
9324:   PetscCall(MatGetSize(x, &Mx, &Nx));
9325:   if (N == Mx) trans = PETSC_FALSE;
9326:   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);
9327:   Mo = trans ? N : M;
9328:   if (*y) {
9329:     PetscCall(MatGetSize(*y, &My, &Ny));
9330:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9331:     else {
9332:       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);
9333:       PetscCall(MatDestroy(y));
9334:     }
9335:   }

9337:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9338:     PetscBool flg;

9340:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9341:     if (w) {
9342:       PetscInt My, Ny, Mw, Nw;

9344:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9345:       PetscCall(MatGetSize(*y, &My, &Ny));
9346:       PetscCall(MatGetSize(w, &Mw, &Nw));
9347:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9348:     }
9349:     if (!w) {
9350:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9351:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9352:       PetscCall(PetscObjectDereference((PetscObject)w));
9353:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9354:   }
9355:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9356:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9357:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9358:   PetscFunctionReturn(PETSC_SUCCESS);
9359: }

9361: /*@
9362:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9364:   Neighbor-wise Collective

9366:   Input Parameters:
9367: + A - the matrix
9368: - x - the input dense matrix

9370:   Output Parameter:
9371: . y - the output dense matrix

9373:   Level: intermediate

9375:   Note:
9376:   This allows one to use either the restriction or interpolation (its transpose)
9377:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9378:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9380: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9381: @*/
9382: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9383: {
9384:   PetscFunctionBegin;
9385:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9386:   PetscFunctionReturn(PETSC_SUCCESS);
9387: }

9389: /*@
9390:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9392:   Neighbor-wise Collective

9394:   Input Parameters:
9395: + A - the matrix
9396: - x - the input dense matrix

9398:   Output Parameter:
9399: . y - the output dense matrix

9401:   Level: intermediate

9403:   Note:
9404:   This allows one to use either the restriction or interpolation (its transpose)
9405:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9406:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9408: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9409: @*/
9410: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9411: {
9412:   PetscFunctionBegin;
9413:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9414:   PetscFunctionReturn(PETSC_SUCCESS);
9415: }

9417: /*@
9418:   MatGetNullSpace - retrieves the null space of a matrix that was provided with `MatSetNullSpace()`

9420:   Logically Collective

9422:   Input Parameters:
9423: + mat    - the matrix
9424: - nullsp - the null space object

9426:   Level: developer

9428: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9429: @*/
9430: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9431: {
9432:   PetscFunctionBegin;
9434:   PetscAssertPointer(nullsp, 2);
9435:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9436:   PetscFunctionReturn(PETSC_SUCCESS);
9437: }

9439: /*@
9440:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices that were supplied with `MatSetNullSpace()`,
9441:   `MatSetTransposeNullSpace()`, and `MatSetNearNullSpace()`

9443:   Logically Collective

9445:   Input Parameters:
9446: + n   - the number of matrices
9447: - mat - the array of matrices

9449:   Output Parameters:
9450: . nullsp - an array of null spaces, `NULL` will be inserted for each matrix that does not have a null space, length 3 * `n`

9452:   Level: developer

9454:   Note:
9455:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9457: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9458:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`, `MatNullSpace`
9459: @*/
9460: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9461: {
9462:   PetscFunctionBegin;
9463:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9464:   PetscAssertPointer(mat, 2);
9465:   PetscAssertPointer(nullsp, 3);

9467:   PetscCall(PetscCalloc1(3 * n, nullsp));
9468:   for (PetscInt i = 0; i < n; i++) {
9470:     (*nullsp)[i] = mat[i]->nullsp;
9471:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9472:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9473:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9474:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9475:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9476:   }
9477:   PetscFunctionReturn(PETSC_SUCCESS);
9478: }

9480: /*@
9481:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9483:   Logically Collective

9485:   Input Parameters:
9486: + n      - the number of matrices
9487: . mat    - the array of matrices
9488: - nullsp - an array of null spaces, of length  3 * `n`

9490:   Level: developer

9492:   Notes:
9493:   Call `MatGetNullSpaces()` to create `nullsp`.

9495:   Frees `nullsp`.

9497:   Developer Note:
9498:   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.
9499:   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
9500:   should have simply been called `MatSetNullSpaces()`

9502: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9503:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`, `MatNullSpace`
9504: @*/
9505: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9506: {
9507:   PetscFunctionBegin;
9508:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9509:   PetscAssertPointer(mat, 2);
9510:   PetscAssertPointer(nullsp, 3);
9511:   PetscAssertPointer(*nullsp, 3);

9513:   for (PetscInt i = 0; i < n; i++) {
9515:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9516:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9517:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9518:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9519:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9520:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9521:   }
9522:   PetscCall(PetscFree(*nullsp));
9523:   PetscFunctionReturn(PETSC_SUCCESS);
9524: }

9526: /*@
9527:   MatSetNullSpace - attaches a null space to a matrix.

9529:   Logically Collective

9531:   Input Parameters:
9532: + mat    - the matrix
9533: - nullsp - the null space object

9535:   Level: advanced

9537:   Notes:
9538:   This null space is used by the `KSP` linear solvers to solve singular systems.

9540:   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`

9542:   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
9543:   to zero but the linear system will still be solved in a least squares sense.

9545:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9546:   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)$.
9547:   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
9548:   $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
9549:   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)$.
9550:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9552:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9553:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9554:   routine also automatically calls `MatSetTransposeNullSpace()`.

9556:   The user should call `MatNullSpaceDestroy()`.

9558: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9559:           `KSPSetPCSide()`, `MatNullSpace`
9560: @*/
9561: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9562: {
9563:   PetscFunctionBegin;
9566:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9567:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9568:   mat->nullsp = nullsp;
9569:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9570:   PetscFunctionReturn(PETSC_SUCCESS);
9571: }

9573: /*@
9574:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix that was set with `MatSetTransposeNullSpace()`

9576:   Logically Collective

9578:   Input Parameters:
9579: + mat    - the matrix
9580: - nullsp - the null space object

9582:   Level: developer

9584: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9585: @*/
9586: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9587: {
9588:   PetscFunctionBegin;
9591:   PetscAssertPointer(nullsp, 2);
9592:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9593:   PetscFunctionReturn(PETSC_SUCCESS);
9594: }

9596: /*@
9597:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9599:   Logically Collective

9601:   Input Parameters:
9602: + mat    - the matrix
9603: - nullsp - the null space object

9605:   Level: advanced

9607:   Notes:
9608:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9610:   See `MatSetNullSpace()`

9612: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9613: @*/
9614: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9615: {
9616:   PetscFunctionBegin;
9619:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9620:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9621:   mat->transnullsp = nullsp;
9622:   PetscFunctionReturn(PETSC_SUCCESS);
9623: }

9625: /*@
9626:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9627:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9629:   Logically Collective

9631:   Input Parameters:
9632: + mat    - the matrix
9633: - nullsp - the null space object

9635:   Level: advanced

9637:   Notes:
9638:   Overwrites any previous near null space that may have been attached

9640:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9642: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9643: @*/
9644: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9645: {
9646:   PetscFunctionBegin;
9650:   MatCheckPreallocated(mat, 1);
9651:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9652:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9653:   mat->nearnullsp = nullsp;
9654:   PetscFunctionReturn(PETSC_SUCCESS);
9655: }

9657: /*@
9658:   MatGetNearNullSpace - Get null space from a matrix that was attached with `MatSetNearNullSpace()`

9660:   Not Collective

9662:   Input Parameter:
9663: . mat - the matrix

9665:   Output Parameter:
9666: . nullsp - the null space object, `NULL` if not set

9668:   Level: advanced

9670: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9671: @*/
9672: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9673: {
9674:   PetscFunctionBegin;
9677:   PetscAssertPointer(nullsp, 2);
9678:   MatCheckPreallocated(mat, 1);
9679:   *nullsp = mat->nearnullsp;
9680:   PetscFunctionReturn(PETSC_SUCCESS);
9681: }

9683: /*@
9684:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9686:   Collective

9688:   Input Parameters:
9689: + mat  - the matrix
9690: . row  - row/column permutation
9691: - info - information on desired factorization process

9693:   Level: developer

9695:   Notes:
9696:   Probably really in-place only when level of fill is zero, otherwise allocates
9697:   new space to store factored matrix and deletes previous memory.

9699:   Most users should employ the `KSP` interface for linear solvers
9700:   instead of working directly with matrix algebra routines such as this.
9701:   See, e.g., `KSPCreate()`.

9703:   Fortran Note:
9704:   A valid (non-null) `info` argument must be provided

9706: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9707: @*/
9708: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9709: {
9710:   PetscFunctionBegin;
9714:   PetscAssertPointer(info, 3);
9715:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9716:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9717:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9718:   MatCheckPreallocated(mat, 1);
9719:   PetscUseTypeMethod(mat, iccfactor, row, info);
9720:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9721:   PetscFunctionReturn(PETSC_SUCCESS);
9722: }

9724: /*@
9725:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9726:   ghosted ones.

9728:   Not Collective

9730:   Input Parameters:
9731: + mat  - the matrix
9732: - diag - the diagonal values, including ghost ones

9734:   Level: developer

9736:   Notes:
9737:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9739:   `diag` is a sequential vector that has a length which is the same as the local (ghosted) length of the vector associated with
9740:   the matrix's `ISLocalToGlobalMapping` set with `MatSetLocalToGlobalMapping()`.

9742:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`.

9744: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`, `MatSetLocalToGlobalMapping()`, `ISLocalToGlobalMapping`
9745: @*/
9746: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9747: {
9748:   PetscMPIInt size;

9750:   PetscFunctionBegin;

9755:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9756:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9757:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9758:   if (size == 1) {
9759:     PetscInt n, m;
9760:     PetscCall(VecGetSize(diag, &n));
9761:     PetscCall(MatGetSize(mat, NULL, &m));
9762:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9763:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9764:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9765:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9766:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9767:   PetscFunctionReturn(PETSC_SUCCESS);
9768: }

9770: /*@
9771:   MatGetInertia - Gets the inertia from a factored matrix

9773:   Collective

9775:   Input Parameter:
9776: . mat - the matrix

9778:   Output Parameters:
9779: + nneg  - number of negative eigenvalues
9780: . nzero - number of zero eigenvalues
9781: - npos  - number of positive eigenvalues

9783:   Level: advanced

9785:   Note:
9786:   Matrix must have been factored by `MatCholeskyFactor()`

9788: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9789: @*/
9790: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9791: {
9792:   PetscFunctionBegin;
9795:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9796:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9797:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9798:   PetscFunctionReturn(PETSC_SUCCESS);
9799: }

9801: /*@
9802:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9804:   Neighbor-wise Collective

9806:   Input Parameters:
9807: + mat - the factored matrix obtained with `MatGetFactor()`
9808: - b   - the right-hand-side vectors

9810:   Output Parameter:
9811: . x - the result vectors

9813:   Level: developer

9815:   Note:
9816:   The vectors `b` and `x` cannot be the same. I.e., one cannot
9817:   call `MatSolves`(A,x,x).

9819: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatGetFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9820: @*/
9821: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9822: {
9823:   PetscFunctionBegin;
9826:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9827:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9828:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9830:   MatCheckPreallocated(mat, 1);
9831:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9832:   PetscUseTypeMethod(mat, solves, b, x);
9833:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9834:   PetscFunctionReturn(PETSC_SUCCESS);
9835: }

9837: /*@
9838:   MatIsSymmetric - Test whether a matrix is symmetric

9840:   Collective

9842:   Input Parameters:
9843: + A   - the matrix to test
9844: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9846:   Output Parameter:
9847: . flg - the result

9849:   Level: intermediate

9851:   Notes:
9852:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9854:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9856:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9857:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9858:   have been set then `MatIsSymmetric()` does not need to perform any computations and returns immediately with the result.

9860: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9861:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9862: @*/
9863: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9864: {
9865:   PetscFunctionBegin;
9867:   PetscAssertPointer(flg, 3);
9868:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9869:   else {
9870:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9871:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9872:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9873:   }
9874:   PetscFunctionReturn(PETSC_SUCCESS);
9875: }

9877: /*@
9878:   MatIsHermitian - Test whether a matrix is Hermitian

9880:   Collective

9882:   Input Parameters:
9883: + A   - the matrix to test
9884: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9886:   Output Parameter:
9887: . flg - the result

9889:   Level: intermediate

9891:   Notes:
9892:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9894:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9896:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9897:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9898:   have been set then `MatIsHermitian()` does not need to perform any computations and returns immediately with the result.

9900: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9901:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9902: @*/
9903: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9904: {
9905:   PetscFunctionBegin;
9907:   PetscAssertPointer(flg, 3);
9908:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9909:   else {
9910:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9911:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9912:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9913:   }
9914:   PetscFunctionReturn(PETSC_SUCCESS);
9915: }

9917: /*@
9918:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9920:   Not Collective

9922:   Input Parameter:
9923: . A - the matrix to check

9925:   Output Parameters:
9926: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9927: - flg - the result (only valid if set is `PETSC_TRUE`)

9929:   Level: advanced

9931:   Notes:
9932:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9933:   if you want it explicitly checked

9935:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9936:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9938: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9939: @*/
9940: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9941: {
9942:   PetscFunctionBegin;
9944:   PetscAssertPointer(set, 2);
9945:   PetscAssertPointer(flg, 3);
9946:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9947:     *set = PETSC_TRUE;
9948:     *flg = PetscBool3ToBool(A->symmetric);
9949:   } else *set = PETSC_FALSE;
9950:   PetscFunctionReturn(PETSC_SUCCESS);
9951: }

9953: /*@
9954:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9956:   Not Collective

9958:   Input Parameter:
9959: . A - the matrix to check

9961:   Output Parameters:
9962: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9963: - flg - the result (only valid if set is `PETSC_TRUE`)

9965:   Level: advanced

9967:   Notes:
9968:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9970:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9971:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9973: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9974: @*/
9975: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9976: {
9977:   PetscFunctionBegin;
9979:   PetscAssertPointer(set, 2);
9980:   PetscAssertPointer(flg, 3);
9981:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9982:     *set = PETSC_TRUE;
9983:     *flg = PetscBool3ToBool(A->spd);
9984:   } else *set = PETSC_FALSE;
9985:   PetscFunctionReturn(PETSC_SUCCESS);
9986: }

9988: /*@
9989:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9991:   Not Collective

9993:   Input Parameter:
9994: . A - the matrix to check

9996:   Output Parameters:
9997: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9998: - flg - the result (only valid if set is `PETSC_TRUE`)

10000:   Level: advanced

10002:   Notes:
10003:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
10004:   if you want it explicitly checked

10006:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
10007:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10009: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
10010: @*/
10011: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
10012: {
10013:   PetscFunctionBegin;
10015:   PetscAssertPointer(set, 2);
10016:   PetscAssertPointer(flg, 3);
10017:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
10018:     *set = PETSC_TRUE;
10019:     *flg = PetscBool3ToBool(A->hermitian);
10020:   } else *set = PETSC_FALSE;
10021:   PetscFunctionReturn(PETSC_SUCCESS);
10022: }

10024: /*@
10025:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

10027:   Collective

10029:   Input Parameter:
10030: . A - the matrix to test

10032:   Output Parameter:
10033: . flg - the result

10035:   Level: intermediate

10037:   Notes:
10038:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

10040:   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
10041:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
10042:   have been set then `MatIsStructurallySymmetric()` does not need to perform any computations and returns immediately with the result.

10044: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
10045: @*/
10046: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
10047: {
10048:   PetscFunctionBegin;
10050:   PetscAssertPointer(flg, 2);
10051:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
10052:   else {
10053:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
10054:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
10055:   }
10056:   PetscFunctionReturn(PETSC_SUCCESS);
10057: }

10059: /*@
10060:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

10062:   Not Collective

10064:   Input Parameter:
10065: . A - the matrix to check

10067:   Output Parameters:
10068: + set - `PETSC_TRUE` if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
10069: - flg - the result (only valid if set is `PETSC_TRUE`)

10071:   Level: advanced

10073:   Notes:
10074:   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
10075:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

10077:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

10079: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
10080: @*/
10081: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
10082: {
10083:   PetscFunctionBegin;
10085:   PetscAssertPointer(set, 2);
10086:   PetscAssertPointer(flg, 3);
10087:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
10088:     *set = PETSC_TRUE;
10089:     *flg = PetscBool3ToBool(A->structurally_symmetric);
10090:   } else *set = PETSC_FALSE;
10091:   PetscFunctionReturn(PETSC_SUCCESS);
10092: }

10094: /*@
10095:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10096:   to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10098:   Not Collective

10100:   Input Parameter:
10101: . mat - the matrix

10103:   Output Parameters:
10104: + nstash    - the size of the stash
10105: . reallocs  - the number of additional mallocs incurred.
10106: . bnstash   - the size of the block stash
10107: - breallocs - the number of additional mallocs incurred.in the block stash

10109:   Level: advanced

10111: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10112: @*/
10113: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10114: {
10115:   PetscFunctionBegin;
10116:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10117:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10118:   PetscFunctionReturn(PETSC_SUCCESS);
10119: }

10121: /*@
10122:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10123:   parallel layout, `PetscLayout` for rows and columns

10125:   Collective

10127:   Input Parameter:
10128: . mat - the matrix

10130:   Output Parameters:
10131: + right - (optional) vector that the matrix can be multiplied against
10132: - left  - (optional) vector that the matrix vector product can be stored in

10134:   Options Database Key:
10135: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10137:   Level: advanced

10139:   Notes:
10140:   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()`.

10142:   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`.

10144:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10146:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10147:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10149: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10150: @*/
10151: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10152: {
10153:   PetscFunctionBegin;
10156:   if (mat->ops->getvecs) {
10157:     PetscUseTypeMethod(mat, getvecs, right, left);
10158:   } else {
10159:     if (right) {
10160:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10161:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10162:       PetscCall(VecSetType(*right, mat->defaultvectype));
10163: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10164:       if (mat->boundtocpu && mat->bindingpropagates) {
10165:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10166:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10167:       }
10168: #endif
10169:     }
10170:     if (left) {
10171:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10172:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10173:       PetscCall(VecSetType(*left, mat->defaultvectype));
10174: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10175:       if (mat->boundtocpu && mat->bindingpropagates) {
10176:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10177:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10178:       }
10179: #endif
10180:     }
10181:   }
10182:   PetscFunctionReturn(PETSC_SUCCESS);
10183: }

10185: /*@
10186:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10187:   with default values.

10189:   Not Collective

10191:   Input Parameter:
10192: . info - the `MatFactorInfo` data structure

10194:   Level: developer

10196:   Notes:
10197:   The solvers are generally used through the `KSP` and `PC` objects, for example
10198:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10200:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10202: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10203: @*/
10204: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10205: {
10206:   PetscFunctionBegin;
10207:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10208:   PetscFunctionReturn(PETSC_SUCCESS);
10209: }

10211: /*@
10212:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10214:   Collective

10216:   Input Parameters:
10217: + mat - the factored matrix
10218: - is  - the index set defining the Schur indices (0-based)

10220:   Level: advanced

10222:   Notes:
10223:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10225:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10227:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10229: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10230:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10231: @*/
10232: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10233: {
10234:   PetscErrorCode (*f)(Mat, IS);

10236:   PetscFunctionBegin;
10241:   PetscCheckSameComm(mat, 1, is, 2);
10242:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10243:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10244:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10245:   PetscCall((*f)(mat, is));
10246:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10247:   PetscFunctionReturn(PETSC_SUCCESS);
10248: }

10250: /*@
10251:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10253:   Logically Collective

10255:   Input Parameters:
10256: + F      - the factored matrix obtained by calling `MatGetFactor()`
10257: . S      - location where to return the Schur complement, can be `NULL`
10258: - status - the status of the Schur complement matrix, can be `NULL`

10260:   Level: advanced

10262:   Notes:
10263:   You must call `MatFactorSetSchurIS()` before calling this routine.

10265:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10267:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10268:   The caller must destroy the object when it is no longer needed.
10269:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10271:   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)

10273:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10275:   Developer Note:
10276:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10277:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10279: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10280: @*/
10281: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10282: {
10283:   PetscFunctionBegin;
10285:   if (S) PetscAssertPointer(S, 2);
10286:   if (status) PetscAssertPointer(status, 3);
10287:   if (S) {
10288:     PetscErrorCode (*f)(Mat, Mat *);

10290:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10291:     if (f) PetscCall((*f)(F, S));
10292:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10293:   }
10294:   if (status) *status = F->schur_status;
10295:   PetscFunctionReturn(PETSC_SUCCESS);
10296: }

10298: /*@
10299:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10301:   Logically Collective

10303:   Input Parameters:
10304: + F      - the factored matrix obtained by calling `MatGetFactor()`
10305: . S      - location where to return the Schur complement, can be `NULL`
10306: - status - the status of the Schur complement matrix, can be `NULL`

10308:   Level: advanced

10310:   Notes:
10311:   You must call `MatFactorSetSchurIS()` before calling this routine.

10313:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10315:   The routine returns a the Schur Complement stored within the data structures of the solver.

10317:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10319:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10321:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10323:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10325: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10326: @*/
10327: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10328: {
10329:   PetscFunctionBegin;
10331:   if (S) {
10332:     PetscAssertPointer(S, 2);
10333:     *S = F->schur;
10334:   }
10335:   if (status) {
10336:     PetscAssertPointer(status, 3);
10337:     *status = F->schur_status;
10338:   }
10339:   PetscFunctionReturn(PETSC_SUCCESS);
10340: }

10342: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10343: {
10344:   Mat S = F->schur;

10346:   PetscFunctionBegin;
10347:   switch (F->schur_status) {
10348:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10349:   case MAT_FACTOR_SCHUR_INVERTED:
10350:     if (S) {
10351:       S->ops->solve             = NULL;
10352:       S->ops->matsolve          = NULL;
10353:       S->ops->solvetranspose    = NULL;
10354:       S->ops->matsolvetranspose = NULL;
10355:       S->ops->solveadd          = NULL;
10356:       S->ops->solvetransposeadd = NULL;
10357:       S->factortype             = MAT_FACTOR_NONE;
10358:       PetscCall(PetscFree(S->solvertype));
10359:     }
10360:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10361:     break;
10362:   default:
10363:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10364:   }
10365:   PetscFunctionReturn(PETSC_SUCCESS);
10366: }

10368: /*@
10369:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10371:   Logically Collective

10373:   Input Parameters:
10374: + F      - the factored matrix obtained by calling `MatGetFactor()`
10375: . S      - location where the Schur complement is stored
10376: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10378:   Level: advanced

10380: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10381: @*/
10382: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10383: {
10384:   PetscFunctionBegin;
10386:   if (S) {
10388:     *S = NULL;
10389:   }
10390:   F->schur_status = status;
10391:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10392:   PetscFunctionReturn(PETSC_SUCCESS);
10393: }

10395: /*@
10396:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10398:   Logically Collective

10400:   Input Parameters:
10401: + F   - the factored matrix obtained by calling `MatGetFactor()`
10402: . rhs - location where the right-hand side of the Schur complement system is stored
10403: - sol - location where the solution of the Schur complement system has to be returned

10405:   Level: advanced

10407:   Notes:
10408:   The sizes of the vectors should match the size of the Schur complement

10410:   Must be called after `MatFactorSetSchurIS()`

10412: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10413: @*/
10414: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10415: {
10416:   PetscFunctionBegin;
10423:   PetscCheckSameComm(F, 1, rhs, 2);
10424:   PetscCheckSameComm(F, 1, sol, 3);
10425:   PetscCall(MatFactorFactorizeSchurComplement(F));
10426:   switch (F->schur_status) {
10427:   case MAT_FACTOR_SCHUR_FACTORED:
10428:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10429:     break;
10430:   case MAT_FACTOR_SCHUR_INVERTED:
10431:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10432:     break;
10433:   default:
10434:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10435:   }
10436:   PetscFunctionReturn(PETSC_SUCCESS);
10437: }

10439: /*@
10440:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10442:   Logically Collective

10444:   Input Parameters:
10445: + F   - the factored matrix obtained by calling `MatGetFactor()`
10446: . rhs - location where the right-hand side of the Schur complement system is stored
10447: - sol - location where the solution of the Schur complement system has to be returned

10449:   Level: advanced

10451:   Notes:
10452:   The sizes of the vectors should match the size of the Schur complement

10454:   Must be called after `MatFactorSetSchurIS()`

10456: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10457: @*/
10458: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10459: {
10460:   PetscFunctionBegin;
10467:   PetscCheckSameComm(F, 1, rhs, 2);
10468:   PetscCheckSameComm(F, 1, sol, 3);
10469:   PetscCall(MatFactorFactorizeSchurComplement(F));
10470:   switch (F->schur_status) {
10471:   case MAT_FACTOR_SCHUR_FACTORED:
10472:     PetscCall(MatSolve(F->schur, rhs, sol));
10473:     break;
10474:   case MAT_FACTOR_SCHUR_INVERTED:
10475:     PetscCall(MatMult(F->schur, rhs, sol));
10476:     break;
10477:   default:
10478:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10479:   }
10480:   PetscFunctionReturn(PETSC_SUCCESS);
10481: }

10483: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10484: #if PetscDefined(HAVE_CUDA)
10485: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10486: #endif

10488: /* Schur status updated in the interface */
10489: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10490: {
10491:   Mat S = F->schur;

10493:   PetscFunctionBegin;
10494:   if (S) {
10495:     PetscMPIInt size;
10496:     PetscBool   isdense, isdensecuda;

10498:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10499:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10500:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10501:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10502:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10503:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10504:     if (isdense) {
10505:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10506:     } else if (isdensecuda) {
10507: #if PetscDefined(HAVE_CUDA)
10508:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10509: #endif
10510:     }
10511:     // HIP??????????????
10512:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10513:   }
10514:   PetscFunctionReturn(PETSC_SUCCESS);
10515: }

10517: /*@
10518:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10520:   Logically Collective

10522:   Input Parameter:
10523: . F - the factored matrix obtained by calling `MatGetFactor()`

10525:   Level: advanced

10527:   Notes:
10528:   Must be called after `MatFactorSetSchurIS()`.

10530:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10532: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10533: @*/
10534: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10535: {
10536:   PetscFunctionBegin;
10539:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10540:   PetscCall(MatFactorFactorizeSchurComplement(F));
10541:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10542:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10543:   PetscFunctionReturn(PETSC_SUCCESS);
10544: }

10546: /*@
10547:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10549:   Logically Collective

10551:   Input Parameter:
10552: . F - the factored matrix obtained by calling `MatGetFactor()`

10554:   Level: advanced

10556:   Note:
10557:   Must be called after `MatFactorSetSchurIS()`

10559: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10560: @*/
10561: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10562: {
10563:   MatFactorInfo info;

10565:   PetscFunctionBegin;
10568:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10569:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10570:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10571:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10572:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10573:   } else {
10574:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10575:   }
10576:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10577:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10578:   PetscFunctionReturn(PETSC_SUCCESS);
10579: }

10581: /*@
10582:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10584:   Neighbor-wise Collective

10586:   Input Parameters:
10587: + A     - the matrix
10588: . P     - the projection matrix
10589: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10590: - 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
10591:           if the result is a dense matrix this is irrelevant

10593:   Output Parameter:
10594: . C - the product matrix

10596:   Level: intermediate

10598:   Notes:
10599:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10601:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10602:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10604:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10606:   Developer Note:
10607:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10609: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10610: @*/
10611: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10612: {
10613:   PetscFunctionBegin;
10614:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10615:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10617:   if (scall == MAT_INITIAL_MATRIX) {
10618:     PetscCall(MatProductCreate(A, P, NULL, C));
10619:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10620:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10621:     PetscCall(MatProductSetFill(*C, fill));

10623:     (*C)->product->api_user = PETSC_TRUE;
10624:     PetscCall(MatProductSetFromOptions(*C));
10625:     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);
10626:     PetscCall(MatProductSymbolic(*C));
10627:   } else { /* scall == MAT_REUSE_MATRIX */
10628:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10629:   }

10631:   PetscCall(MatProductNumeric(*C));
10632:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10633:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10634:     (*C)->spd = A->spd;
10635:   }
10636:   PetscFunctionReturn(PETSC_SUCCESS);
10637: }

10639: /*@
10640:   MatRARt - Creates the matrix product $C = R * A * R^T$

10642:   Neighbor-wise Collective

10644:   Input Parameters:
10645: + A     - the matrix
10646: . R     - the projection matrix
10647: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10648: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10649:           if the result is a dense matrix this is irrelevant

10651:   Output Parameter:
10652: . C - the product matrix

10654:   Level: intermediate

10656:   Notes:
10657:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10659:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10660:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10662:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10663:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10664:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10665:   We recommend using `MatPtAP()` when possible.

10667:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10669: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10670: @*/
10671: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10672: {
10673:   PetscFunctionBegin;
10674:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10675:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10677:   if (scall == MAT_INITIAL_MATRIX) {
10678:     PetscCall(MatProductCreate(A, R, NULL, C));
10679:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10680:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10681:     PetscCall(MatProductSetFill(*C, fill));

10683:     (*C)->product->api_user = PETSC_TRUE;
10684:     PetscCall(MatProductSetFromOptions(*C));
10685:     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);
10686:     PetscCall(MatProductSymbolic(*C));
10687:   } else { /* scall == MAT_REUSE_MATRIX */
10688:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10689:   }

10691:   PetscCall(MatProductNumeric(*C));
10692:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10693:   PetscFunctionReturn(PETSC_SUCCESS);
10694: }

10696: /* MatProductComputeWithMat_Private - Computes D = A * B or D = A^T * B into an existing matrix D, keeping the product on a dense D

10698:    Collective

10700:    Input Parameters:
10701: +  A     - the left matrix
10702: .  B     - the right matrix
10703: .  ptype - MATPRODUCT_AB or MATPRODUCT_AtB
10704: -  D     - the result, of the size of the product

10706:    Level: developer

10708:    Notes:
10709:    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
10710:    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
10711:    references to A and B until MatProductClear() is called on D or D is destroyed. In contrast, MatMatMult() with MAT_REUSE_MATRIX creates the
10712:    product and destroys it again on every call into a dense D that does not already have a product.

10714:    For any other D, which must already have a product, this calls MatMatMult() or MatTransposeMatMult() with MAT_REUSE_MATRIX.

10716:    Developer Note:
10717:    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
10718:    assembly.

10720: .seealso: `MatMatMult()`, `MatTransposeMatMult()`, `MatProductReplaceMats()`, `PCMGMatResidualDefault()`
10721: */
10722: PetscErrorCode MatProductComputeWithMat_Private(Mat A, Mat B, MatProductType ptype, Mat D)
10723: {
10724:   Mat_Product     *product = D->product;
10725:   PetscObjectState state;
10726:   PetscBool        flg;

10728:   PetscFunctionBegin;
10729:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)D, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10730:   if (!flg) { /* only a dense result can be given without a product, MatMatMult() and MatTransposeMatMult() reuse the product of any other */
10731:     if (ptype == MATPRODUCT_AB) PetscCall(MatMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10732:     else PetscCall(MatTransposeMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10733:     PetscFunctionReturn(PETSC_SUCCESS);
10734:   }
10735:   PetscCall(MatGetNonzeroState(A, &state));
10736:   if (product == NULL || product->type != ptype || product->A != A || product->Anonzerostate != state) {
10737:     PetscCall(PetscInfo(D, "Setting up the %s product into the supplied dense matrix\n", MatProductTypes[ptype]));
10738:     PetscCall(MatProductCreateWithMat(A, B, NULL, D));
10739:     D->product->api_user = PETSC_TRUE;
10740:     PetscCall(MatProductSetType(D, ptype));
10741:     PetscCall(MatProductSetFromOptions(D));
10742:     PetscCall(MatProductSymbolic(D));
10743:   } else {
10744:     PetscCall(PetscInfo(D, "Reusing the %s product attached to the supplied dense matrix\n", MatProductTypes[ptype]));
10745:     if (product->B != B) PetscCall(MatProductReplaceMats(NULL, B, NULL, D));
10746:   }
10747:   PetscCall(MatProductNumeric(D));
10748:   PetscFunctionReturn(PETSC_SUCCESS);
10749: }

10751: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10752: {
10753:   PetscBool flg = PETSC_TRUE;

10755:   PetscFunctionBegin;
10756:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10757:   if (scall == MAT_INITIAL_MATRIX) {
10758:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10759:     PetscCall(MatProductCreate(A, B, NULL, C));
10760:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10761:     PetscCall(MatProductSetFill(*C, fill));
10762:   } else { /* scall == MAT_REUSE_MATRIX */
10763:     Mat_Product *product = (*C)->product;

10765:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10766:     if (flg && product && product->type != ptype) {
10767:       PetscCall(MatProductClear(*C));
10768:       product = NULL;
10769:     }
10770:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10771:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10772:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10773:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10774:       product        = (*C)->product;
10775:       product->fill  = fill;
10776:       product->clear = PETSC_TRUE;
10777:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10778:       flg = PETSC_FALSE;
10779:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10780:     }
10781:   }
10782:   if (flg) {
10783:     (*C)->product->api_user = PETSC_TRUE;
10784:     PetscCall(MatProductSetType(*C, ptype));
10785:     PetscCall(MatProductSetFromOptions(*C));
10786:     PetscCall(MatProductSymbolic(*C));
10787:   }
10788:   PetscCall(MatProductNumeric(*C));
10789:   PetscFunctionReturn(PETSC_SUCCESS);
10790: }

10792: /*@
10793:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10795:   Neighbor-wise Collective

10797:   Input Parameters:
10798: + A     - the left matrix
10799: . B     - the right matrix
10800: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10801: - 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
10802:           if the result is a dense matrix this is irrelevant

10804:   Output Parameter:
10805: . C - the product matrix

10807:   Notes:
10808:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10810:   `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
10811:   call to this function with `MAT_INITIAL_MATRIX`.

10813:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10815:   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`,
10816:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10818:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10820:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10821:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10823:   Example of Usage:
10824: .vb
10825:      MatProductCreate(A,B,NULL,&C);
10826:      MatProductSetType(C,MATPRODUCT_AB);
10827:      MatProductSymbolic(C);
10828:      MatProductNumeric(C); // compute C=A * B
10829:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10830:      MatProductNumeric(C);
10831:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10832:      MatProductNumeric(C);
10833: .ve

10835:   Level: intermediate

10837: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10838: @*/
10839: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10840: {
10841:   PetscFunctionBegin;
10842:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10843:   PetscFunctionReturn(PETSC_SUCCESS);
10844: }

10846: /*@
10847:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10849:   Neighbor-wise Collective

10851:   Input Parameters:
10852: + A     - the left matrix
10853: . B     - the right matrix
10854: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10855: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10857:   Output Parameter:
10858: . C - the product matrix

10860:   Options Database Key:
10861: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10862:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10863:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10865:   Level: intermediate

10867:   Notes:
10868:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10870:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10872:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10873:   actually needed.

10875:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10876:   and for pairs of `MATMPIDENSE` matrices.

10878:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10879:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10881:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10883: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10884: @*/
10885: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10886: {
10887:   PetscFunctionBegin;
10888:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10889:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10890:   PetscFunctionReturn(PETSC_SUCCESS);
10891: }

10893: /*@
10894:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10896:   Neighbor-wise Collective

10898:   Input Parameters:
10899: + A     - the left matrix
10900: . B     - the right matrix
10901: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10902: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10904:   Output Parameter:
10905: . C - the product matrix

10907:   Level: intermediate

10909:   Notes:
10910:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10912:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10914:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10915:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10917:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10918:   actually needed.

10920:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10921:   which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.

10923:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10925: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10926: @*/
10927: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10928: {
10929:   PetscFunctionBegin;
10930:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10931:   PetscFunctionReturn(PETSC_SUCCESS);
10932: }

10934: /*@
10935:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10937:   Neighbor-wise Collective

10939:   Input Parameters:
10940: + A     - the left matrix
10941: . B     - the middle matrix
10942: . C     - the right matrix
10943: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10944: - 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
10945:           if the result is a dense matrix this is irrelevant

10947:   Output Parameter:
10948: . D - the product matrix

10950:   Level: intermediate

10952:   Notes:
10953:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10955:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10957:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10958:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10960:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10961:   actually needed.

10963:   If you have many matrices with the same non-zero structure to multiply, you
10964:   should use `MAT_REUSE_MATRIX` in all calls but the first

10966:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10968: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10969: @*/
10970: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10971: {
10972:   PetscFunctionBegin;
10973:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10974:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10976:   if (scall == MAT_INITIAL_MATRIX) {
10977:     PetscCall(MatProductCreate(A, B, C, D));
10978:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10979:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10980:     PetscCall(MatProductSetFill(*D, fill));

10982:     (*D)->product->api_user = PETSC_TRUE;
10983:     PetscCall(MatProductSetFromOptions(*D));
10984:     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,
10985:                ((PetscObject)C)->type_name);
10986:     PetscCall(MatProductSymbolic(*D));
10987:   } else { /* user may change input matrices when REUSE */
10988:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10989:   }
10990:   PetscCall(MatProductNumeric(*D));
10991:   PetscFunctionReturn(PETSC_SUCCESS);
10992: }

10994: /*@
10995:   MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.

10997:   Collective

10999:   Input Parameters:
11000: + mat      - the matrix
11001: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
11002: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
11003: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11005:   Output Parameter:
11006: . matredundant - redundant matrix

11008:   Level: advanced

11010:   Notes:
11011:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
11012:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

11014:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
11015:   calling it.

11017:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

11019: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
11020: @*/
11021: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
11022: {
11023:   MPI_Comm       comm;
11024:   PetscMPIInt    size;
11025:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
11026:   Mat_Redundant *redund     = NULL;
11027:   PetscSubcomm   psubcomm   = NULL;
11028:   MPI_Comm       subcomm_in = subcomm;
11029:   Mat           *matseq;
11030:   IS             isrow, iscol;
11031:   PetscBool      newsubcomm = PETSC_FALSE;

11033:   PetscFunctionBegin;
11035:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
11036:     PetscAssertPointer(*matredundant, 5);
11038:   }

11040:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11041:   if (size == 1 || nsubcomm == 1) {
11042:     if (reuse == MAT_INITIAL_MATRIX) {
11043:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
11044:     } else {
11045:       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");
11046:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
11047:     }
11048:     PetscFunctionReturn(PETSC_SUCCESS);
11049:   }

11051:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11052:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11053:   MatCheckPreallocated(mat, 1);

11055:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
11056:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
11057:     /* create psubcomm, then get subcomm */
11058:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11059:     PetscCallMPI(MPI_Comm_size(comm, &size));
11060:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

11062:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
11063:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
11064:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
11065:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
11066:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
11067:     newsubcomm = PETSC_TRUE;
11068:     PetscCall(PetscSubcommDestroy(&psubcomm));
11069:   }

11071:   /* get isrow, iscol and a local sequential matrix matseq[0] */
11072:   if (reuse == MAT_INITIAL_MATRIX) {
11073:     mloc_sub = PETSC_DECIDE;
11074:     nloc_sub = PETSC_DECIDE;
11075:     if (bs < 1) {
11076:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
11077:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
11078:     } else {
11079:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
11080:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
11081:     }
11082:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
11083:     rstart = rend - mloc_sub;
11084:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
11085:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
11086:     PetscCall(ISSetIdentity(iscol));
11087:   } else { /* reuse == MAT_REUSE_MATRIX */
11088:     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");
11089:     /* retrieve subcomm */
11090:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
11091:     redund = (*matredundant)->redundant;
11092:     isrow  = redund->isrow;
11093:     iscol  = redund->iscol;
11094:     matseq = redund->matseq;
11095:   }
11096:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

11098:   /* get matredundant over subcomm */
11099:   if (reuse == MAT_INITIAL_MATRIX) {
11100:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

11102:     /* create a supporting struct and attach it to C for reuse */
11103:     PetscCall(PetscNew(&redund));
11104:     (*matredundant)->redundant = redund;
11105:     redund->isrow              = isrow;
11106:     redund->iscol              = iscol;
11107:     redund->matseq             = matseq;
11108:     if (newsubcomm) {
11109:       redund->subcomm = subcomm;
11110:     } else {
11111:       redund->subcomm = MPI_COMM_NULL;
11112:     }
11113:   } else {
11114:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
11115:   }
11116: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
11117:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
11118:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
11119:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
11120:   }
11121: #endif
11122:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
11123:   PetscFunctionReturn(PETSC_SUCCESS);
11124: }

11126: /*@
11127:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
11128:   a given `Mat`. Each submatrix can span multiple procs.

11130:   Collective

11132:   Input Parameters:
11133: + mat     - the matrix
11134: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
11135: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11137:   Output Parameter:
11138: . subMat - parallel sub-matrices each spanning a given `subcomm`

11140:   Level: advanced

11142:   Notes:
11143:   The submatrix partition across processes is dictated by `subComm` a
11144:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
11145:   is not restricted to be grouped with consecutive original MPI processes.

11147:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11148:   map directly to the layout of the original matrix [wrt the local
11149:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
11150:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11151:   the `subMat`. However the offDiagMat looses some columns - and this is
11152:   reconstructed with `MatSetValues()`

11154:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11156: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11157: @*/
11158: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11159: {
11160:   PetscMPIInt commsize, subCommSize;

11162:   PetscFunctionBegin;
11163:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11164:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11165:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11167:   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");
11168:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11169:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11170:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11171:   PetscFunctionReturn(PETSC_SUCCESS);
11172: }

11174: /*@
11175:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11177:   Not Collective

11179:   Input Parameters:
11180: + mat   - matrix to extract local submatrix from
11181: . isrow - local row indices for submatrix
11182: - iscol - local column indices for submatrix

11184:   Output Parameter:
11185: . submat - the submatrix

11187:   Level: intermediate

11189:   Notes:
11190:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11192:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11193:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11195:   `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11196:   `MatSetValuesBlockedLocal()` will also be implemented.

11198:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11199:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11201: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11202: @*/
11203: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11204: {
11205:   PetscFunctionBegin;
11209:   PetscCheckSameComm(isrow, 2, iscol, 3);
11210:   PetscAssertPointer(submat, 4);
11211:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11213:   if (mat->ops->getlocalsubmatrix) {
11214:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11215:   } else {
11216:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11217:   }
11218:   (*submat)->assembled = mat->assembled;
11219:   PetscFunctionReturn(PETSC_SUCCESS);
11220: }

11222: /*@
11223:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11225:   Not Collective

11227:   Input Parameters:
11228: + mat    - matrix to extract local submatrix from
11229: . isrow  - local row indices for submatrix
11230: . iscol  - local column indices for submatrix
11231: - submat - the submatrix

11233:   Level: intermediate

11235: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11236: @*/
11237: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11238: {
11239:   PetscFunctionBegin;
11243:   PetscCheckSameComm(isrow, 2, iscol, 3);
11244:   PetscAssertPointer(submat, 4);

11247:   if (mat->ops->restorelocalsubmatrix) {
11248:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11249:   } else {
11250:     PetscCall(MatDestroy(submat));
11251:   }
11252:   *submat = NULL;
11253:   PetscFunctionReturn(PETSC_SUCCESS);
11254: }

11256: /*@
11257:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11259:   Collective

11261:   Input Parameter:
11262: . mat - the matrix

11264:   Output Parameter:
11265: . is - if any rows have zero diagonals this contains the list of them

11267:   Level: developer

11269: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11270: @*/
11271: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11272: {
11273:   PetscFunctionBegin;
11276:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11277:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11279:   if (!mat->ops->findzerodiagonals) {
11280:     Vec                diag;
11281:     const PetscScalar *a;
11282:     PetscInt          *rows;
11283:     PetscInt           rStart, rEnd, r, nrow = 0;

11285:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11286:     PetscCall(MatGetDiagonal(mat, diag));
11287:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11288:     PetscCall(VecGetArrayRead(diag, &a));
11289:     for (r = 0; r < rEnd - rStart; ++r)
11290:       if (a[r] == 0.0) ++nrow;
11291:     PetscCall(PetscMalloc1(nrow, &rows));
11292:     nrow = 0;
11293:     for (r = 0; r < rEnd - rStart; ++r)
11294:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11295:     PetscCall(VecRestoreArrayRead(diag, &a));
11296:     PetscCall(VecDestroy(&diag));
11297:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11298:   } else {
11299:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11300:   }
11301:   PetscFunctionReturn(PETSC_SUCCESS);
11302: }

11304: /*@
11305:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11307:   Collective

11309:   Input Parameter:
11310: . mat - the matrix

11312:   Output Parameter:
11313: . is - contains the list of rows with off block diagonal entries

11315:   Level: developer

11317: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11318: @*/
11319: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11320: {
11321:   PetscFunctionBegin;
11324:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11325:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11327:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11328:   PetscFunctionReturn(PETSC_SUCCESS);
11329: }

11331: /*@
11332:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11334:   Collective; No Fortran Support

11336:   Input Parameter:
11337: . mat - the matrix

11339:   Output Parameter:
11340: . values - the block inverses in column major order (FORTRAN-like)

11342:   Level: advanced

11344:   Notes:
11345:   The size of the blocks is determined by the block size of the matrix.

11347:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11349:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11351: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11352: @*/
11353: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11354: {
11355:   PetscFunctionBegin;
11357:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11358:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11359:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11360:   PetscFunctionReturn(PETSC_SUCCESS);
11361: }

11363: /*@
11364:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11366:   Collective; No Fortran Support

11368:   Input Parameters:
11369: + mat     - the matrix
11370: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11371: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11373:   Output Parameter:
11374: . values - the block inverses in column major order (FORTRAN-like)

11376:   Level: advanced

11378:   Notes:
11379:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11381:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11383: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11384: @*/
11385: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11386: {
11387:   PetscFunctionBegin;
11389:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11390:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11391:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11392:   PetscFunctionReturn(PETSC_SUCCESS);
11393: }

11395: /*@
11396:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11398:   Collective

11400:   Input Parameters:
11401: + A - the matrix
11402: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.

11404:   Level: advanced

11406:   Note:
11407:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11409: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11410: @*/
11411: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11412: {
11413:   const PetscScalar *vals;
11414:   PetscInt          *dnnz;
11415:   PetscInt           m, rstart, rend, bs, i, j;

11417:   PetscFunctionBegin;
11418:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11419:   PetscCall(MatGetBlockSize(A, &bs));
11420:   PetscCall(MatGetLocalSize(A, &m, NULL));
11421:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11422:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11423:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11424:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11425:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11426:   PetscCall(PetscFree(dnnz));
11427:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11428:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11429:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11430:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11431:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11432:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11433:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11434:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11435:   PetscFunctionReturn(PETSC_SUCCESS);
11436: }

11438: /*@
11439:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11440:   via `MatTransposeColoringCreate()`.

11442:   Collective

11444:   Input Parameter:
11445: . c - coloring context

11447:   Level: intermediate

11449: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11450: @*/
11451: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11452: {
11453:   MatTransposeColoring matcolor = *c;

11455:   PetscFunctionBegin;
11456:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11457:   if (--((PetscObject)matcolor)->refct > 0) {
11458:     matcolor = NULL;
11459:     PetscFunctionReturn(PETSC_SUCCESS);
11460:   }

11462:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11463:   PetscCall(PetscFree(matcolor->rows));
11464:   PetscCall(PetscFree(matcolor->den2sp));
11465:   PetscCall(PetscFree(matcolor->colorforcol));
11466:   PetscCall(PetscFree(matcolor->columns));
11467:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11468:   PetscCall(PetscHeaderDestroy(c));
11469:   PetscFunctionReturn(PETSC_SUCCESS);
11470: }

11472: /*@
11473:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11474:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11475:   `MatTransposeColoring` to sparse `B`.

11477:   Collective

11479:   Input Parameters:
11480: + coloring - coloring context created with `MatTransposeColoringCreate()`
11481: - B        - sparse matrix

11483:   Output Parameter:
11484: . Btdense - dense matrix $B^T$

11486:   Level: developer

11488:   Note:
11489:   These are used internally for some implementations of `MatRARt()`

11491: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11492: @*/
11493: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11494: {
11495:   PetscFunctionBegin;

11500:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11501:   PetscFunctionReturn(PETSC_SUCCESS);
11502: }

11504: /*@
11505:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11506:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11507:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11508:   $C_{sp}$ from $C_{den}$.

11510:   Collective

11512:   Input Parameters:
11513: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11514: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11516:   Output Parameter:
11517: . Csp - sparse matrix

11519:   Level: developer

11521:   Note:
11522:   These are used internally for some implementations of `MatRARt()`

11524: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11525: @*/
11526: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11527: {
11528:   PetscFunctionBegin;

11533:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11534:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11535:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11536:   PetscFunctionReturn(PETSC_SUCCESS);
11537: }

11539: /*@
11540:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11542:   Collective

11544:   Input Parameters:
11545: + mat        - the matrix product C
11546: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11548:   Output Parameter:
11549: . color - the new coloring context

11551:   Level: intermediate

11553: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11554:           `MatTransColoringApplyDenToSp()`
11555: @*/
11556: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11557: {
11558:   MatTransposeColoring c;
11559:   MPI_Comm             comm;

11561:   PetscFunctionBegin;
11562:   PetscAssertPointer(color, 3);

11564:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11565:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11566:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11567:   c->ctype = iscoloring->ctype;
11568:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11569:   *color = c;
11570:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11571:   PetscFunctionReturn(PETSC_SUCCESS);
11572: }

11574: /*@
11575:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11576:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11578:   Not Collective

11580:   Input Parameter:
11581: . mat - the matrix

11583:   Output Parameter:
11584: . state - the current state

11586:   Level: intermediate

11588:   Notes:
11589:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11590:   different matrices

11592:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11594:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11596: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11597: @*/
11598: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11599: {
11600:   PetscFunctionBegin;
11602:   *state = mat->nonzerostate;
11603:   PetscFunctionReturn(PETSC_SUCCESS);
11604: }

11606: /*@
11607:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11608:   matrices from each process

11610:   Collective

11612:   Input Parameters:
11613: + comm   - the communicators the parallel matrix will live on
11614: . seqmat - the input sequential matrices
11615: . n      - number of local columns (or `PETSC_DECIDE`)
11616: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11618:   Output Parameter:
11619: . mpimat - the parallel matrix generated

11621:   Level: developer

11623:   Note:
11624:   The number of columns of the matrix in EACH process MUST be the same.

11626: .seealso: [](ch_matrices), `Mat`
11627: @*/
11628: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11629: {
11630:   PetscMPIInt size;

11632:   PetscFunctionBegin;
11633:   PetscCallMPI(MPI_Comm_size(comm, &size));
11634:   if (size == 1) {
11635:     if (reuse == MAT_INITIAL_MATRIX) {
11636:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11637:     } else {
11638:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11639:     }
11640:     PetscFunctionReturn(PETSC_SUCCESS);
11641:   }

11643:   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");

11645:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11646:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11647:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11648:   PetscFunctionReturn(PETSC_SUCCESS);
11649: }

11651: /*@
11652:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11654:   Collective

11656:   Input Parameters:
11657: + A - the matrix to create subdomains from
11658: - N - requested number of subdomains

11660:   Output Parameters:
11661: + n   - number of subdomains resulting on this MPI process
11662: - iss - `IS` list with indices of subdomains on this MPI process

11664:   Level: advanced

11666:   Note:
11667:   The number of subdomains must be smaller than the communicator size

11669: .seealso: [](ch_matrices), `Mat`, `IS`
11670: @*/
11671: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11672: {
11673:   MPI_Comm    comm, subcomm;
11674:   PetscMPIInt size, rank, color;
11675:   PetscInt    rstart, rend, k;

11677:   PetscFunctionBegin;
11678:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11679:   PetscCallMPI(MPI_Comm_size(comm, &size));
11680:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11681:   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);
11682:   *n    = 1;
11683:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11684:   color = rank / k;
11685:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11686:   PetscCall(PetscMalloc1(1, iss));
11687:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11688:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11689:   PetscCallMPI(MPI_Comm_free(&subcomm));
11690:   PetscFunctionReturn(PETSC_SUCCESS);
11691: }

11693: /*@
11694:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11696:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11697:   If they are not the same, uses `MatMatMatMult()`.

11699:   Once the coarse grid problem is constructed, correct for interpolation operators
11700:   that are not of full rank, which can legitimately happen in the case of non-nested
11701:   geometric multigrid.

11703:   Input Parameters:
11704: + restrct     - restriction operator
11705: . dA          - fine grid matrix
11706: . interpolate - interpolation operator
11707: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11708: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11710:   Output Parameter:
11711: . A - the Galerkin coarse matrix

11713:   Options Database Key:
11714: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11716:   Level: developer

11718:   Note:
11719:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11721: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11722: @*/
11723: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11724: {
11725:   IS  zerorows;
11726:   Vec diag;

11728:   PetscFunctionBegin;
11729:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11730:   /* Construct the coarse grid matrix */
11731:   if (interpolate == restrct) {
11732:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11733:   } else {
11734:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11735:   }

11737:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11738:      This can legitimately happen in the case of non-nested geometric multigrid.
11739:      In that event, we set the rows of the matrix to the rows of the identity,
11740:      ignoring the equations (as the RHS will also be zero). */

11742:   PetscCall(MatFindZeroRows(*A, &zerorows));

11744:   if (zerorows != NULL) { /* if there are any zero rows */
11745:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11746:     PetscCall(MatGetDiagonal(*A, diag));
11747:     PetscCall(VecISSet(diag, zerorows, 1.0));
11748:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11749:     PetscCall(VecDestroy(&diag));
11750:     PetscCall(ISDestroy(&zerorows));
11751:   }
11752:   PetscFunctionReturn(PETSC_SUCCESS);
11753: }

11755: /*@
11756:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11758:   Logically Collective

11760:   Input Parameters:
11761: + mat - the matrix
11762: . op  - the name of the operation
11763: - f   - the function that provides the operation

11765:   Level: developer

11767:   Example Usage:
11768: .vb
11769:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11771:   PetscCall(MatCreateXXX(comm, ..., &A));
11772:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11773: .ve

11775:   Notes:
11776:   See the file `include/petscmat.h` for a complete list of matrix
11777:   operations, which all have the form MATOP_<OPERATION>, where
11778:   <OPERATION> is the name (in all capital letters) of the
11779:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11781:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11782:   sequence as the usual matrix interface routines, since they
11783:   are intended to be accessed via the usual matrix interface
11784:   routines, e.g.,
11785: .vb
11786:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11787: .ve

11789:   In particular each function MUST return `PETSC_SUCCESS` on success and
11790:   nonzero on failure.

11792:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11794: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11795: @*/
11796: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11797: {
11798:   PetscFunctionBegin;
11801:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11802: #if !PetscDefined(USE_COMPLEX)
11803:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11804:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11805:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11806: #endif
11807:   ((PetscErrorCodeFn **)mat->ops)[op] = f;
11808:   PetscFunctionReturn(PETSC_SUCCESS);
11809: }

11811: /*@
11812:   MatGetOperation - Gets a matrix operation for any matrix type.

11814:   Not Collective

11816:   Input Parameters:
11817: + mat - the matrix
11818: - op  - the name of the operation

11820:   Output Parameter:
11821: . f - the function that provides the operation

11823:   Level: developer

11825:   Example Usage:
11826: .vb
11827:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11829:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11830: .ve

11832:   Notes:
11833:   See the file `include/petscmat.h` for a complete list of matrix
11834:   operations, which all have the form MATOP_<OPERATION>, where
11835:   <OPERATION> is the name (in all capital letters) of the
11836:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11838:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11840: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11841: @*/
11842: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11843: {
11844:   PetscFunctionBegin;
11846:   PetscAssertPointer(f, 3);
11847: #if !PetscDefined(USE_COMPLEX)
11848:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11849:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11850:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11851: #endif
11852:   *f = ((PetscErrorCodeFn **)mat->ops)[op];
11853:   PetscFunctionReturn(PETSC_SUCCESS);
11854: }

11856: /*@
11857:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11859:   Not Collective

11861:   Input Parameters:
11862: + mat - the matrix
11863: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11865:   Output Parameter:
11866: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11868:   Level: advanced

11870:   Note:
11871:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11873: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11874: @*/
11875: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11876: {
11877:   PetscFunctionBegin;
11879:   PetscAssertPointer(has, 3);
11880: #if !PetscDefined(USE_COMPLEX)
11881:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11882:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11883:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11884: #endif
11885:   if (op == MATOP_ADOT || op == MATOP_ANORM) {
11886:     /* MatADot() and MatANorm() fall back to MatMult() when the type has no method */
11887:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11888:     else PetscCall(MatHasOperation(mat, MATOP_MULT, has));
11889:     PetscFunctionReturn(PETSC_SUCCESS);
11890:   }
11891:   if (mat->ops->hasoperation) {
11892:     PetscUseTypeMethod(mat, hasoperation, op, has);
11893:   } else {
11894:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11895:     else {
11896:       *has = PETSC_FALSE;
11897:       if (op == MATOP_CREATE_SUBMATRIX) {
11898:         PetscMPIInt size;

11900:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11901:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11902:       }
11903:     }
11904:   }
11905:   PetscFunctionReturn(PETSC_SUCCESS);
11906: }

11908: /*@
11909:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11911:   Collective

11913:   Input Parameter:
11914: . mat - the matrix

11916:   Output Parameter:
11917: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11919:   Level: beginner

11921: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11922: @*/
11923: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11924: {
11925:   PetscFunctionBegin;
11928:   PetscAssertPointer(cong, 2);
11929:   if (!mat->rmap || !mat->cmap) {
11930:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11931:     PetscFunctionReturn(PETSC_SUCCESS);
11932:   }
11933:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11934:     PetscCall(PetscLayoutSetUp(mat->rmap));
11935:     PetscCall(PetscLayoutSetUp(mat->cmap));
11936:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11937:     if (*cong) mat->congruentlayouts = 1;
11938:     else mat->congruentlayouts = 0;
11939:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11940:   PetscFunctionReturn(PETSC_SUCCESS);
11941: }

11943: /*@
11944:   MatFlag - set infinity into the local part of the matrix on any subset of MPI processes

11946:   Logically Collective

11948:   Input Parameters:
11949: + A   - the matrix, can be `NULL` but only if on all processes
11950: - flg - indicates if this processes portion of the matrix should be set to infinity

11952:   Level: developer

11954:   Notes:
11955:   This is used to flag a block of solutions that a linear solver failed to compute, as `VecFlag()` does for a single solution.

11957:   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.

11959:   Only the dense types (`MATSEQDENSE`, `MATMPIDENSE`, and their device variants) currently implement this operation.

11961: .seealso: [](ch_matrices), `Mat`, `VecFlag()`, `MatZeroEntries()`, `MatSetValues()`
11962: @*/
11963: PetscErrorCode MatFlag(Mat A, PetscInt flg)
11964: {
11965:   PetscFunctionBegin;
11966:   if (!A) PetscFunctionReturn(PETSC_SUCCESS);
11969:   MatCheckPreallocated(A, 1);
11970:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
11971:   if (flg) PetscUseTypeMethod(A, setinf);
11972:   PetscFunctionReturn(PETSC_SUCCESS);
11973: }

11975: /*@
11976:   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
11977:   and possibly removes small values from the graph structure.

11979:   Collective

11981:   Input Parameters:
11982: + A       - the matrix
11983: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11984: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11985: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with $|entries| \le filter$
11986: . num_idx - size of `index` array
11987: - index   - array of block indices to use for graph strength of connection weight

11989:   Output Parameter:
11990: . graph - the resulting graph

11992:   Level: advanced

11994: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11995: @*/
11996: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11997: {
11998:   PetscFunctionBegin;
12002:   PetscAssertPointer(graph, 7);
12003:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
12004:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
12005:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
12006:   PetscFunctionReturn(PETSC_SUCCESS);
12007: }

12009: /*@
12010:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
12011:   meaning the same memory is used for the matrix, and no new memory is allocated.

12013:   Collective

12015:   Input Parameters:
12016: + A    - the matrix
12017: - 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

12019:   Level: intermediate

12021:   Developer Note:
12022:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
12023:   of the arrays in the data structure may be no longer needed to represent the matrix.

12025: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
12026: @*/
12027: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
12028: {
12029:   PetscFunctionBegin;
12031:   PetscUseTypeMethod(A, eliminatezeros, keep);
12032:   PetscFunctionReturn(PETSC_SUCCESS);
12033: }

12035: /*@
12036:   MatGetCurrentMemType - Get the memory location of the matrix

12038:   Not Collective, but the result will be the same on all MPI processes

12040:   Input Parameter:
12041: . A - the matrix whose memory type we are checking

12043:   Output Parameter:
12044: . m - the memory type, see `PetscMemType`

12046:   Level: intermediate

12048: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
12049: @*/
12050: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
12051: {
12052:   PetscFunctionBegin;
12054:   PetscAssertPointer(m, 2);
12055:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
12056:   else *m = PETSC_MEMTYPE_HOST;
12057:   PetscFunctionReturn(PETSC_SUCCESS);
12058: }